SemaDeclCXX.cpp 571 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for C++ declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/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/PartialDiagnostic.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/Lex/LiteralSupport.h"
  29. #include "clang/Lex/Preprocessor.h"
  30. #include "clang/Sema/CXXFieldCollector.h"
  31. #include "clang/Sema/DeclSpec.h"
  32. #include "clang/Sema/Initialization.h"
  33. #include "clang/Sema/Lookup.h"
  34. #include "clang/Sema/ParsedTemplate.h"
  35. #include "clang/Sema/Scope.h"
  36. #include "clang/Sema/ScopeInfo.h"
  37. #include "clang/Sema/SemaInternal.h"
  38. #include "clang/Sema/Template.h"
  39. #include "llvm/ADT/STLExtras.h"
  40. #include "llvm/ADT/SmallString.h"
  41. #include "llvm/ADT/StringExtras.h"
  42. #include <map>
  43. #include <set>
  44. using namespace clang;
  45. //===----------------------------------------------------------------------===//
  46. // CheckDefaultArgumentVisitor
  47. //===----------------------------------------------------------------------===//
  48. namespace {
  49. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  50. /// the default argument of a parameter to determine whether it
  51. /// contains any ill-formed subexpressions. For example, this will
  52. /// diagnose the use of local variables or parameters within the
  53. /// default argument expression.
  54. class CheckDefaultArgumentVisitor
  55. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  56. Expr *DefaultArg;
  57. Sema *S;
  58. public:
  59. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  60. : DefaultArg(defarg), S(s) {}
  61. bool VisitExpr(Expr *Node);
  62. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  63. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  64. bool VisitLambdaExpr(LambdaExpr *Lambda);
  65. bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
  66. };
  67. /// VisitExpr - Visit all of the children of this expression.
  68. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  69. bool IsInvalid = false;
  70. for (Stmt *SubStmt : Node->children())
  71. IsInvalid |= Visit(SubStmt);
  72. return IsInvalid;
  73. }
  74. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  75. /// determine whether this declaration can be used in the default
  76. /// argument expression.
  77. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  78. NamedDecl *Decl = DRE->getDecl();
  79. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  80. // C++ [dcl.fct.default]p9
  81. // Default arguments are evaluated each time the function is
  82. // called. The order of evaluation of function arguments is
  83. // unspecified. Consequently, parameters of a function shall not
  84. // be used in default argument expressions, even if they are not
  85. // evaluated. Parameters of a function declared before a default
  86. // argument expression are in scope and can hide namespace and
  87. // class member names.
  88. return S->Diag(DRE->getLocStart(),
  89. diag::err_param_default_argument_references_param)
  90. << Param->getDeclName() << DefaultArg->getSourceRange();
  91. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  92. // C++ [dcl.fct.default]p7
  93. // Local variables shall not be used in default argument
  94. // expressions.
  95. if (VDecl->isLocalVarDecl())
  96. return S->Diag(DRE->getLocStart(),
  97. diag::err_param_default_argument_references_local)
  98. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  99. }
  100. return false;
  101. }
  102. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  103. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  104. // C++ [dcl.fct.default]p8:
  105. // The keyword this shall not be used in a default argument of a
  106. // member function.
  107. return S->Diag(ThisE->getLocStart(),
  108. diag::err_param_default_argument_references_this)
  109. << ThisE->getSourceRange();
  110. }
  111. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  112. bool Invalid = false;
  113. for (PseudoObjectExpr::semantics_iterator
  114. i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
  115. Expr *E = *i;
  116. // Look through bindings.
  117. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  118. E = OVE->getSourceExpr();
  119. assert(E && "pseudo-object binding without source expression?");
  120. }
  121. Invalid |= Visit(E);
  122. }
  123. return Invalid;
  124. }
  125. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
  126. // C++11 [expr.lambda.prim]p13:
  127. // A lambda-expression appearing in a default argument shall not
  128. // implicitly or explicitly capture any entity.
  129. if (Lambda->capture_begin() == Lambda->capture_end())
  130. return false;
  131. return S->Diag(Lambda->getLocStart(),
  132. 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. switch(EST) {
  151. // If this function can throw any exceptions, make a note of that.
  152. case EST_MSAny:
  153. case EST_None:
  154. ClearExceptions();
  155. ComputedEST = EST;
  156. return;
  157. // FIXME: If the call to this decl is using any of its default arguments, we
  158. // need to search them for potentially-throwing calls.
  159. // If this function has a basic noexcept, it doesn't affect the outcome.
  160. case EST_BasicNoexcept:
  161. return;
  162. // If we're still at noexcept(true) and there's a nothrow() callee,
  163. // change to that specification.
  164. case EST_DynamicNone:
  165. if (ComputedEST == EST_BasicNoexcept)
  166. ComputedEST = EST_DynamicNone;
  167. return;
  168. // Check out noexcept specs.
  169. case EST_ComputedNoexcept:
  170. {
  171. FunctionProtoType::NoexceptResult NR =
  172. Proto->getNoexceptSpec(Self->Context);
  173. assert(NR != FunctionProtoType::NR_NoNoexcept &&
  174. "Must have noexcept result for EST_ComputedNoexcept.");
  175. assert(NR != FunctionProtoType::NR_Dependent &&
  176. "Should not generate implicit declarations for dependent cases, "
  177. "and don't know how to handle them anyway.");
  178. // noexcept(false) -> no spec on the new function
  179. if (NR == FunctionProtoType::NR_Throw) {
  180. ClearExceptions();
  181. ComputedEST = EST_None;
  182. }
  183. // noexcept(true) won't change anything either.
  184. return;
  185. }
  186. default:
  187. break;
  188. }
  189. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  190. assert(ComputedEST != EST_None &&
  191. "Shouldn't collect exceptions when throw-all is guaranteed.");
  192. ComputedEST = EST_Dynamic;
  193. // Record the exceptions in this function's exception specification.
  194. for (const auto &E : Proto->exceptions())
  195. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  196. Exceptions.push_back(E);
  197. }
  198. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  199. if (!E || ComputedEST == EST_MSAny)
  200. return;
  201. // FIXME:
  202. //
  203. // C++0x [except.spec]p14:
  204. // [An] implicit exception-specification specifies the type-id T if and
  205. // only if T is allowed by the exception-specification of a function directly
  206. // invoked by f's implicit definition; f shall allow all exceptions if any
  207. // function it directly invokes allows all exceptions, and f shall allow no
  208. // exceptions if every function it directly invokes allows no exceptions.
  209. //
  210. // Note in particular that if an implicit exception-specification is generated
  211. // for a function containing a throw-expression, that specification can still
  212. // be noexcept(true).
  213. //
  214. // Note also that 'directly invoked' is not defined in the standard, and there
  215. // is no indication that we should only consider potentially-evaluated calls.
  216. //
  217. // Ultimately we should implement the intent of the standard: the exception
  218. // specification should be the set of exceptions which can be thrown by the
  219. // implicit definition. For now, we assume that any non-nothrow expression can
  220. // throw any exception.
  221. if (Self->canThrow(E))
  222. ComputedEST = EST_None;
  223. }
  224. bool
  225. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  226. SourceLocation EqualLoc) {
  227. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  228. diag::err_typecheck_decl_incomplete_type)) {
  229. Param->setInvalidDecl();
  230. return true;
  231. }
  232. // C++ [dcl.fct.default]p5
  233. // A default argument expression is implicitly converted (clause
  234. // 4) to the parameter type. The default argument expression has
  235. // the same semantic constraints as the initializer expression in
  236. // a declaration of a variable of the parameter type, using the
  237. // copy-initialization semantics (8.5).
  238. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  239. Param);
  240. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  241. EqualLoc);
  242. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  243. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  244. if (Result.isInvalid())
  245. return true;
  246. Arg = Result.getAs<Expr>();
  247. CheckCompletedExpr(Arg, EqualLoc);
  248. Arg = MaybeCreateExprWithCleanups(Arg);
  249. // Okay: add the default argument to the parameter
  250. Param->setDefaultArg(Arg);
  251. // We have already instantiated this parameter; provide each of the
  252. // instantiations with the uninstantiated default argument.
  253. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  254. = UnparsedDefaultArgInstantiations.find(Param);
  255. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  256. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  257. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  258. // We're done tracking this parameter's instantiations.
  259. UnparsedDefaultArgInstantiations.erase(InstPos);
  260. }
  261. return false;
  262. }
  263. /// ActOnParamDefaultArgument - Check whether the default argument
  264. /// provided for a function parameter is well-formed. If so, attach it
  265. /// to the parameter declaration.
  266. void
  267. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  268. Expr *DefaultArg) {
  269. if (!param || !DefaultArg)
  270. return;
  271. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  272. UnparsedDefaultArgLocs.erase(Param);
  273. // Default arguments are only permitted in C++
  274. if (!getLangOpts().CPlusPlus) {
  275. Diag(EqualLoc, diag::err_param_default_argument)
  276. << DefaultArg->getSourceRange();
  277. Param->setInvalidDecl();
  278. return;
  279. }
  280. // Check for unexpanded parameter packs.
  281. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  282. Param->setInvalidDecl();
  283. return;
  284. }
  285. // C++11 [dcl.fct.default]p3
  286. // A default argument expression [...] shall not be specified for a
  287. // parameter pack.
  288. if (Param->isParameterPack()) {
  289. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  290. << DefaultArg->getSourceRange();
  291. return;
  292. }
  293. // Check that the default argument is well-formed
  294. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  295. if (DefaultArgChecker.Visit(DefaultArg)) {
  296. Param->setInvalidDecl();
  297. return;
  298. }
  299. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  300. }
  301. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  302. /// argument for a function parameter, but we can't parse it yet
  303. /// because we're inside a class definition. Note that this default
  304. /// argument will be parsed later.
  305. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  306. SourceLocation EqualLoc,
  307. SourceLocation ArgLoc) {
  308. if (!param)
  309. return;
  310. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  311. Param->setUnparsedDefaultArg();
  312. UnparsedDefaultArgLocs[Param] = ArgLoc;
  313. }
  314. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  315. /// the default argument for the parameter param failed.
  316. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  317. SourceLocation EqualLoc) {
  318. if (!param)
  319. return;
  320. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  321. Param->setInvalidDecl();
  322. UnparsedDefaultArgLocs.erase(Param);
  323. Param->setDefaultArg(new(Context)
  324. OpaqueValueExpr(EqualLoc,
  325. Param->getType().getNonReferenceType(),
  326. VK_RValue));
  327. }
  328. /// CheckExtraCXXDefaultArguments - Check for any extra default
  329. /// arguments in the declarator, which is not a function declaration
  330. /// or definition and therefore is not permitted to have default
  331. /// arguments. This routine should be invoked for every declarator
  332. /// that is not a function declaration or definition.
  333. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  334. // C++ [dcl.fct.default]p3
  335. // A default argument expression shall be specified only in the
  336. // parameter-declaration-clause of a function declaration or in a
  337. // template-parameter (14.1). It shall not be specified for a
  338. // parameter pack. If it is specified in a
  339. // parameter-declaration-clause, it shall not occur within a
  340. // declarator or abstract-declarator of a parameter-declaration.
  341. bool MightBeFunction = D.isFunctionDeclarationContext();
  342. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  343. DeclaratorChunk &chunk = D.getTypeObject(i);
  344. if (chunk.Kind == DeclaratorChunk::Function) {
  345. if (MightBeFunction) {
  346. // This is a function declaration. It can have default arguments, but
  347. // keep looking in case its return type is a function type with default
  348. // arguments.
  349. MightBeFunction = false;
  350. continue;
  351. }
  352. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  353. ++argIdx) {
  354. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  355. if (Param->hasUnparsedDefaultArg()) {
  356. std::unique_ptr<CachedTokens> Toks =
  357. std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
  358. SourceRange SR;
  359. if (Toks->size() > 1)
  360. SR = SourceRange((*Toks)[1].getLocation(),
  361. Toks->back().getLocation());
  362. else
  363. SR = UnparsedDefaultArgLocs[Param];
  364. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  365. << SR;
  366. } else if (Param->getDefaultArg()) {
  367. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  368. << Param->getDefaultArg()->getSourceRange();
  369. Param->setDefaultArg(nullptr);
  370. }
  371. }
  372. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  373. MightBeFunction = false;
  374. }
  375. }
  376. }
  377. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  378. for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
  379. const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
  380. if (!PVD->hasDefaultArg())
  381. return false;
  382. if (!PVD->hasInheritedDefaultArg())
  383. return true;
  384. }
  385. return false;
  386. }
  387. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  388. /// function, once we already know that they have the same
  389. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  390. /// error, false otherwise.
  391. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  392. Scope *S) {
  393. bool Invalid = false;
  394. // The declaration context corresponding to the scope is the semantic
  395. // parent, unless this is a local function declaration, in which case
  396. // it is that surrounding function.
  397. DeclContext *ScopeDC = New->isLocalExternDecl()
  398. ? New->getLexicalDeclContext()
  399. : New->getDeclContext();
  400. // Find the previous declaration for the purpose of default arguments.
  401. FunctionDecl *PrevForDefaultArgs = Old;
  402. for (/**/; PrevForDefaultArgs;
  403. // Don't bother looking back past the latest decl if this is a local
  404. // extern declaration; nothing else could work.
  405. PrevForDefaultArgs = New->isLocalExternDecl()
  406. ? nullptr
  407. : PrevForDefaultArgs->getPreviousDecl()) {
  408. // Ignore hidden declarations.
  409. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  410. continue;
  411. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  412. !New->isCXXClassMember()) {
  413. // Ignore default arguments of old decl if they are not in
  414. // the same scope and this is not an out-of-line definition of
  415. // a member function.
  416. continue;
  417. }
  418. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  419. // If only one of these is a local function declaration, then they are
  420. // declared in different scopes, even though isDeclInScope may think
  421. // they're in the same scope. (If both are local, the scope check is
  422. // sufficent, and if neither is local, then they are in the same scope.)
  423. continue;
  424. }
  425. // We found the right previous declaration.
  426. break;
  427. }
  428. // C++ [dcl.fct.default]p4:
  429. // For non-template functions, default arguments can be added in
  430. // later declarations of a function in the same
  431. // scope. Declarations in different scopes have completely
  432. // distinct sets of default arguments. That is, declarations in
  433. // inner scopes do not acquire default arguments from
  434. // declarations in outer scopes, and vice versa. In a given
  435. // function declaration, all parameters subsequent to a
  436. // parameter with a default argument shall have default
  437. // arguments supplied in this or previous declarations. A
  438. // default argument shall not be redefined by a later
  439. // declaration (not even to the same value).
  440. //
  441. // C++ [dcl.fct.default]p6:
  442. // Except for member functions of class templates, the default arguments
  443. // in a member function definition that appears outside of the class
  444. // definition are added to the set of default arguments provided by the
  445. // member function declaration in the class definition.
  446. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  447. ? PrevForDefaultArgs->getNumParams()
  448. : 0;
  449. p < NumParams; ++p) {
  450. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  451. ParmVarDecl *NewParam = New->getParamDecl(p);
  452. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  453. bool NewParamHasDfl = NewParam->hasDefaultArg();
  454. if (OldParamHasDfl && NewParamHasDfl) {
  455. unsigned DiagDefaultParamID =
  456. diag::err_param_default_argument_redefinition;
  457. // MSVC accepts that default parameters be redefined for member functions
  458. // of template class. The new default parameter's value is ignored.
  459. Invalid = true;
  460. if (getLangOpts().MicrosoftExt) {
  461. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  462. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  463. // Merge the old default argument into the new parameter.
  464. NewParam->setHasInheritedDefaultArg();
  465. if (OldParam->hasUninstantiatedDefaultArg())
  466. NewParam->setUninstantiatedDefaultArg(
  467. OldParam->getUninstantiatedDefaultArg());
  468. else
  469. NewParam->setDefaultArg(OldParam->getInit());
  470. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  471. Invalid = false;
  472. }
  473. }
  474. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  475. // hint here. Alternatively, we could walk the type-source information
  476. // for NewParam to find the last source location in the type... but it
  477. // isn't worth the effort right now. This is the kind of test case that
  478. // is hard to get right:
  479. // int f(int);
  480. // void g(int (*fp)(int) = f);
  481. // void g(int (*fp)(int) = &f);
  482. Diag(NewParam->getLocation(), DiagDefaultParamID)
  483. << NewParam->getDefaultArgRange();
  484. // Look for the function declaration where the default argument was
  485. // actually written, which may be a declaration prior to Old.
  486. for (auto Older = PrevForDefaultArgs;
  487. OldParam->hasInheritedDefaultArg(); /**/) {
  488. Older = Older->getPreviousDecl();
  489. OldParam = Older->getParamDecl(p);
  490. }
  491. Diag(OldParam->getLocation(), diag::note_previous_definition)
  492. << OldParam->getDefaultArgRange();
  493. } else if (OldParamHasDfl) {
  494. // Merge the old default argument into the new parameter.
  495. // It's important to use getInit() here; getDefaultArg()
  496. // strips off any top-level ExprWithCleanups.
  497. NewParam->setHasInheritedDefaultArg();
  498. if (OldParam->hasUnparsedDefaultArg())
  499. NewParam->setUnparsedDefaultArg();
  500. else if (OldParam->hasUninstantiatedDefaultArg())
  501. NewParam->setUninstantiatedDefaultArg(
  502. OldParam->getUninstantiatedDefaultArg());
  503. else
  504. NewParam->setDefaultArg(OldParam->getInit());
  505. } else if (NewParamHasDfl) {
  506. if (New->getDescribedFunctionTemplate()) {
  507. // Paragraph 4, quoted above, only applies to non-template functions.
  508. Diag(NewParam->getLocation(),
  509. diag::err_param_default_argument_template_redecl)
  510. << NewParam->getDefaultArgRange();
  511. Diag(PrevForDefaultArgs->getLocation(),
  512. diag::note_template_prev_declaration)
  513. << false;
  514. } else if (New->getTemplateSpecializationKind()
  515. != TSK_ImplicitInstantiation &&
  516. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  517. // C++ [temp.expr.spec]p21:
  518. // Default function arguments shall not be specified in a declaration
  519. // or a definition for one of the following explicit specializations:
  520. // - the explicit specialization of a function template;
  521. // - the explicit specialization of a member function template;
  522. // - the explicit specialization of a member function of a class
  523. // template where the class template specialization to which the
  524. // member function specialization belongs is implicitly
  525. // instantiated.
  526. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  527. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  528. << New->getDeclName()
  529. << NewParam->getDefaultArgRange();
  530. } else if (New->getDeclContext()->isDependentContext()) {
  531. // C++ [dcl.fct.default]p6 (DR217):
  532. // Default arguments for a member function of a class template shall
  533. // be specified on the initial declaration of the member function
  534. // within the class template.
  535. //
  536. // Reading the tea leaves a bit in DR217 and its reference to DR205
  537. // leads me to the conclusion that one cannot add default function
  538. // arguments for an out-of-line definition of a member function of a
  539. // dependent type.
  540. int WhichKind = 2;
  541. if (CXXRecordDecl *Record
  542. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  543. if (Record->getDescribedClassTemplate())
  544. WhichKind = 0;
  545. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  546. WhichKind = 1;
  547. else
  548. WhichKind = 2;
  549. }
  550. Diag(NewParam->getLocation(),
  551. diag::err_param_default_argument_member_template_redecl)
  552. << WhichKind
  553. << NewParam->getDefaultArgRange();
  554. }
  555. }
  556. }
  557. // DR1344: If a default argument is added outside a class definition and that
  558. // default argument makes the function a special member function, the program
  559. // is ill-formed. This can only happen for constructors.
  560. if (isa<CXXConstructorDecl>(New) &&
  561. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  562. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  563. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  564. if (NewSM != OldSM) {
  565. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  566. assert(NewParam->hasDefaultArg());
  567. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  568. << NewParam->getDefaultArgRange() << NewSM;
  569. Diag(Old->getLocation(), diag::note_previous_declaration);
  570. }
  571. }
  572. const FunctionDecl *Def;
  573. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  574. // template has a constexpr specifier then all its declarations shall
  575. // contain the constexpr specifier.
  576. if (New->isConstexpr() != Old->isConstexpr()) {
  577. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  578. << New << New->isConstexpr();
  579. Diag(Old->getLocation(), diag::note_previous_declaration);
  580. Invalid = true;
  581. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  582. Old->isDefined(Def)) {
  583. // C++11 [dcl.fcn.spec]p4:
  584. // If the definition of a function appears in a translation unit before its
  585. // first declaration as inline, the program is ill-formed.
  586. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  587. Diag(Def->getLocation(), diag::note_previous_definition);
  588. Invalid = true;
  589. }
  590. // FIXME: It's not clear what should happen if multiple declarations of a
  591. // deduction guide have different explicitness. For now at least we simply
  592. // reject any case where the explicitness changes.
  593. auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
  594. if (NewGuide && NewGuide->isExplicitSpecified() !=
  595. cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
  596. Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
  597. << NewGuide->isExplicitSpecified();
  598. Diag(Old->getLocation(), diag::note_previous_declaration);
  599. }
  600. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  601. // argument expression, that declaration shall be a definition and shall be
  602. // the only declaration of the function or function template in the
  603. // translation unit.
  604. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  605. functionDeclHasDefaultArgument(Old)) {
  606. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  607. Diag(Old->getLocation(), diag::note_previous_declaration);
  608. Invalid = true;
  609. }
  610. return Invalid;
  611. }
  612. NamedDecl *
  613. Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
  614. MultiTemplateParamsArg TemplateParamLists) {
  615. assert(D.isDecompositionDeclarator());
  616. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  617. // The syntax only allows a decomposition declarator as a simple-declaration
  618. // or a for-range-declaration, but we parse it in more cases than that.
  619. if (!D.mayHaveDecompositionDeclarator()) {
  620. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  621. << Decomp.getSourceRange();
  622. return nullptr;
  623. }
  624. if (!TemplateParamLists.empty()) {
  625. // FIXME: There's no rule against this, but there are also no rules that
  626. // would actually make it usable, so we reject it for now.
  627. Diag(TemplateParamLists.front()->getTemplateLoc(),
  628. diag::err_decomp_decl_template);
  629. return nullptr;
  630. }
  631. Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
  632. ? diag::warn_cxx14_compat_decomp_decl
  633. : diag::ext_decomp_decl)
  634. << Decomp.getSourceRange();
  635. // The semantic context is always just the current context.
  636. DeclContext *const DC = CurContext;
  637. // C++1z [dcl.dcl]/8:
  638. // The decl-specifier-seq shall contain only the type-specifier auto
  639. // and cv-qualifiers.
  640. auto &DS = D.getDeclSpec();
  641. {
  642. SmallVector<StringRef, 8> BadSpecifiers;
  643. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  644. if (auto SCS = DS.getStorageClassSpec()) {
  645. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  646. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  647. }
  648. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  649. BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  650. BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  651. }
  652. if (DS.isConstexprSpecified()) {
  653. BadSpecifiers.push_back("constexpr");
  654. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  655. }
  656. if (DS.isInlineSpecified()) {
  657. BadSpecifiers.push_back("inline");
  658. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  659. }
  660. if (!BadSpecifiers.empty()) {
  661. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  662. Err << (int)BadSpecifiers.size()
  663. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  664. // Don't add FixItHints to remove the specifiers; we do still respect
  665. // them when building the underlying variable.
  666. for (auto Loc : BadSpecifierLocs)
  667. Err << SourceRange(Loc, Loc);
  668. }
  669. // We can't recover from it being declared as a typedef.
  670. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  671. return nullptr;
  672. }
  673. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  674. QualType R = TInfo->getType();
  675. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  676. UPPC_DeclarationType))
  677. D.setInvalidType();
  678. // The syntax only allows a single ref-qualifier prior to the decomposition
  679. // declarator. No other declarator chunks are permitted. Also check the type
  680. // specifier here.
  681. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  682. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  683. (D.getNumTypeObjects() == 1 &&
  684. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  685. Diag(Decomp.getLSquareLoc(),
  686. (D.hasGroupingParens() ||
  687. (D.getNumTypeObjects() &&
  688. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  689. ? diag::err_decomp_decl_parens
  690. : diag::err_decomp_decl_type)
  691. << R;
  692. // In most cases, there's no actual problem with an explicitly-specified
  693. // type, but a function type won't work here, and ActOnVariableDeclarator
  694. // shouldn't be called for such a type.
  695. if (R->isFunctionType())
  696. D.setInvalidType();
  697. }
  698. // Build the BindingDecls.
  699. SmallVector<BindingDecl*, 8> Bindings;
  700. // Build the BindingDecls.
  701. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  702. // Check for name conflicts.
  703. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  704. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  705. ForRedeclaration);
  706. LookupName(Previous, S,
  707. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  708. // It's not permitted to shadow a template parameter name.
  709. if (Previous.isSingleResult() &&
  710. Previous.getFoundDecl()->isTemplateParameter()) {
  711. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  712. Previous.getFoundDecl());
  713. Previous.clear();
  714. }
  715. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  716. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  717. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  718. /*AllowInlineNamespace*/false);
  719. if (!Previous.empty()) {
  720. auto *Old = Previous.getRepresentativeDecl();
  721. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  722. Diag(Old->getLocation(), diag::note_previous_definition);
  723. }
  724. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  725. PushOnScopeChains(BD, S, true);
  726. Bindings.push_back(BD);
  727. ParsingInitForAutoVars.insert(BD);
  728. }
  729. // There are no prior lookup results for the variable itself, because it
  730. // is unnamed.
  731. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  732. Decomp.getLSquareLoc());
  733. LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
  734. // Build the variable that holds the non-decomposed object.
  735. bool AddToScope = true;
  736. NamedDecl *New =
  737. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  738. MultiTemplateParamsArg(), AddToScope, Bindings);
  739. CurContext->addHiddenDecl(New);
  740. if (isInOpenMPDeclareTargetContext())
  741. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  742. return New;
  743. }
  744. static bool checkSimpleDecomposition(
  745. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  746. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  747. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  748. if ((int64_t)Bindings.size() != NumElems) {
  749. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  750. << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
  751. << (NumElems < Bindings.size());
  752. return true;
  753. }
  754. unsigned I = 0;
  755. for (auto *B : Bindings) {
  756. SourceLocation Loc = B->getLocation();
  757. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  758. if (E.isInvalid())
  759. return true;
  760. E = GetInit(Loc, E.get(), I++);
  761. if (E.isInvalid())
  762. return true;
  763. B->setBinding(ElemType, E.get());
  764. }
  765. return false;
  766. }
  767. static bool checkArrayLikeDecomposition(Sema &S,
  768. ArrayRef<BindingDecl *> Bindings,
  769. ValueDecl *Src, QualType DecompType,
  770. const llvm::APSInt &NumElems,
  771. QualType ElemType) {
  772. return checkSimpleDecomposition(
  773. S, Bindings, Src, DecompType, NumElems, ElemType,
  774. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  775. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  776. if (E.isInvalid())
  777. return ExprError();
  778. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  779. });
  780. }
  781. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  782. ValueDecl *Src, QualType DecompType,
  783. const ConstantArrayType *CAT) {
  784. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  785. llvm::APSInt(CAT->getSize()),
  786. CAT->getElementType());
  787. }
  788. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  789. ValueDecl *Src, QualType DecompType,
  790. const VectorType *VT) {
  791. return checkArrayLikeDecomposition(
  792. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  793. S.Context.getQualifiedType(VT->getElementType(),
  794. DecompType.getQualifiers()));
  795. }
  796. static bool checkComplexDecomposition(Sema &S,
  797. ArrayRef<BindingDecl *> Bindings,
  798. ValueDecl *Src, QualType DecompType,
  799. const ComplexType *CT) {
  800. return checkSimpleDecomposition(
  801. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  802. S.Context.getQualifiedType(CT->getElementType(),
  803. DecompType.getQualifiers()),
  804. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  805. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  806. });
  807. }
  808. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  809. TemplateArgumentListInfo &Args) {
  810. SmallString<128> SS;
  811. llvm::raw_svector_ostream OS(SS);
  812. bool First = true;
  813. for (auto &Arg : Args.arguments()) {
  814. if (!First)
  815. OS << ", ";
  816. Arg.getArgument().print(PrintingPolicy, OS);
  817. First = false;
  818. }
  819. return OS.str();
  820. }
  821. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  822. SourceLocation Loc, StringRef Trait,
  823. TemplateArgumentListInfo &Args,
  824. unsigned DiagID) {
  825. auto DiagnoseMissing = [&] {
  826. if (DiagID)
  827. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  828. Args);
  829. return true;
  830. };
  831. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  832. NamespaceDecl *Std = S.getStdNamespace();
  833. if (!Std)
  834. return DiagnoseMissing();
  835. // Look up the trait itself, within namespace std. We can diagnose various
  836. // problems with this lookup even if we've been asked to not diagnose a
  837. // missing specialization, because this can only fail if the user has been
  838. // declaring their own names in namespace std or we don't support the
  839. // standard library implementation in use.
  840. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  841. Loc, Sema::LookupOrdinaryName);
  842. if (!S.LookupQualifiedName(Result, Std))
  843. return DiagnoseMissing();
  844. if (Result.isAmbiguous())
  845. return true;
  846. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  847. if (!TraitTD) {
  848. Result.suppressDiagnostics();
  849. NamedDecl *Found = *Result.begin();
  850. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  851. S.Diag(Found->getLocation(), diag::note_declared_at);
  852. return true;
  853. }
  854. // Build the template-id.
  855. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  856. if (TraitTy.isNull())
  857. return true;
  858. if (!S.isCompleteType(Loc, TraitTy)) {
  859. if (DiagID)
  860. S.RequireCompleteType(
  861. Loc, TraitTy, DiagID,
  862. printTemplateArgs(S.Context.getPrintingPolicy(), Args));
  863. return true;
  864. }
  865. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  866. assert(RD && "specialization of class template is not a class?");
  867. // Look up the member of the trait type.
  868. S.LookupQualifiedName(TraitMemberLookup, RD);
  869. return TraitMemberLookup.isAmbiguous();
  870. }
  871. static TemplateArgumentLoc
  872. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  873. uint64_t I) {
  874. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  875. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  876. }
  877. static TemplateArgumentLoc
  878. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  879. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  880. }
  881. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  882. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  883. llvm::APSInt &Size) {
  884. EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
  885. DeclarationName Value = S.PP.getIdentifierInfo("value");
  886. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  887. // Form template argument list for tuple_size<T>.
  888. TemplateArgumentListInfo Args(Loc, Loc);
  889. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  890. // If there's no tuple_size specialization, it's not tuple-like.
  891. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
  892. return IsTupleLike::NotTupleLike;
  893. // If we get this far, we've committed to the tuple interpretation, but
  894. // we can still fail if there actually isn't a usable ::value.
  895. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  896. LookupResult &R;
  897. TemplateArgumentListInfo &Args;
  898. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  899. : R(R), Args(Args) {}
  900. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
  901. S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  902. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  903. }
  904. } Diagnoser(R, Args);
  905. if (R.empty()) {
  906. Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
  907. return IsTupleLike::Error;
  908. }
  909. ExprResult E =
  910. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  911. if (E.isInvalid())
  912. return IsTupleLike::Error;
  913. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
  914. if (E.isInvalid())
  915. return IsTupleLike::Error;
  916. return IsTupleLike::TupleLike;
  917. }
  918. /// \return std::tuple_element<I, T>::type.
  919. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  920. unsigned I, QualType T) {
  921. // Form template argument list for tuple_element<I, T>.
  922. TemplateArgumentListInfo Args(Loc, Loc);
  923. Args.addArgument(
  924. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  925. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  926. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  927. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  928. if (lookupStdTypeTraitMember(
  929. S, R, Loc, "tuple_element", Args,
  930. diag::err_decomp_decl_std_tuple_element_not_specialized))
  931. return QualType();
  932. auto *TD = R.getAsSingle<TypeDecl>();
  933. if (!TD) {
  934. R.suppressDiagnostics();
  935. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  936. << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
  937. if (!R.empty())
  938. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  939. return QualType();
  940. }
  941. return S.Context.getTypeDeclType(TD);
  942. }
  943. namespace {
  944. struct BindingDiagnosticTrap {
  945. Sema &S;
  946. DiagnosticErrorTrap Trap;
  947. BindingDecl *BD;
  948. BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
  949. : S(S), Trap(S.Diags), BD(BD) {}
  950. ~BindingDiagnosticTrap() {
  951. if (Trap.hasErrorOccurred())
  952. S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
  953. }
  954. };
  955. }
  956. static bool checkTupleLikeDecomposition(Sema &S,
  957. ArrayRef<BindingDecl *> Bindings,
  958. VarDecl *Src, QualType DecompType,
  959. const llvm::APSInt &TupleSize) {
  960. if ((int64_t)Bindings.size() != TupleSize) {
  961. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  962. << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
  963. << (TupleSize < Bindings.size());
  964. return true;
  965. }
  966. if (Bindings.empty())
  967. return false;
  968. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  969. // [dcl.decomp]p3:
  970. // The unqualified-id get is looked up in the scope of E by class member
  971. // access lookup
  972. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  973. bool UseMemberGet = false;
  974. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  975. if (auto *RD = DecompType->getAsCXXRecordDecl())
  976. S.LookupQualifiedName(MemberGet, RD);
  977. if (MemberGet.isAmbiguous())
  978. return true;
  979. UseMemberGet = !MemberGet.empty();
  980. S.FilterAcceptableTemplateNames(MemberGet);
  981. }
  982. unsigned I = 0;
  983. for (auto *B : Bindings) {
  984. BindingDiagnosticTrap Trap(S, B);
  985. SourceLocation Loc = B->getLocation();
  986. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  987. if (E.isInvalid())
  988. return true;
  989. // e is an lvalue if the type of the entity is an lvalue reference and
  990. // an xvalue otherwise
  991. if (!Src->getType()->isLValueReferenceType())
  992. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  993. E.get(), nullptr, VK_XValue);
  994. TemplateArgumentListInfo Args(Loc, Loc);
  995. Args.addArgument(
  996. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  997. if (UseMemberGet) {
  998. // if [lookup of member get] finds at least one declaration, the
  999. // initializer is e.get<i-1>().
  1000. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1001. CXXScopeSpec(), SourceLocation(), nullptr,
  1002. MemberGet, &Args, nullptr);
  1003. if (E.isInvalid())
  1004. return true;
  1005. E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
  1006. } else {
  1007. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1008. // in the associated namespaces.
  1009. Expr *Get = UnresolvedLookupExpr::Create(
  1010. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1011. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1012. UnresolvedSetIterator(), UnresolvedSetIterator());
  1013. Expr *Arg = E.get();
  1014. E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
  1015. }
  1016. if (E.isInvalid())
  1017. return true;
  1018. Expr *Init = E.get();
  1019. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1020. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1021. if (T.isNull())
  1022. return true;
  1023. // each vi is a variable of type "reference to T" initialized with the
  1024. // initializer, where the reference is an lvalue reference if the
  1025. // initializer is an lvalue and an rvalue reference otherwise
  1026. QualType RefType =
  1027. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1028. if (RefType.isNull())
  1029. return true;
  1030. auto *RefVD = VarDecl::Create(
  1031. S.Context, Src->getDeclContext(), Loc, Loc,
  1032. B->getDeclName().getAsIdentifierInfo(), RefType,
  1033. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1034. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1035. RefVD->setTSCSpec(Src->getTSCSpec());
  1036. RefVD->setImplicit();
  1037. if (Src->isInlineSpecified())
  1038. RefVD->setInlineSpecified();
  1039. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1040. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1041. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1042. InitializationSequence Seq(S, Entity, Kind, Init);
  1043. E = Seq.Perform(S, Entity, Kind, Init);
  1044. if (E.isInvalid())
  1045. return true;
  1046. E = S.ActOnFinishFullExpr(E.get(), Loc);
  1047. if (E.isInvalid())
  1048. return true;
  1049. RefVD->setInit(E.get());
  1050. RefVD->checkInitIsICE();
  1051. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1052. DeclarationNameInfo(B->getDeclName(), Loc),
  1053. RefVD);
  1054. if (E.isInvalid())
  1055. return true;
  1056. B->setBinding(T, E.get());
  1057. I++;
  1058. }
  1059. return false;
  1060. }
  1061. /// Find the base class to decompose in a built-in decomposition of a class type.
  1062. /// This base class search is, unfortunately, not quite like any other that we
  1063. /// perform anywhere else in C++.
  1064. static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
  1065. SourceLocation Loc,
  1066. const CXXRecordDecl *RD,
  1067. CXXCastPath &BasePath) {
  1068. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1069. CXXBasePath &Path) {
  1070. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1071. };
  1072. const CXXRecordDecl *ClassWithFields = nullptr;
  1073. if (RD->hasDirectFields())
  1074. // [dcl.decomp]p4:
  1075. // Otherwise, all of E's non-static data members shall be public direct
  1076. // members of E ...
  1077. ClassWithFields = RD;
  1078. else {
  1079. // ... or of ...
  1080. CXXBasePaths Paths;
  1081. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1082. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1083. // If no classes have fields, just decompose RD itself. (This will work
  1084. // if and only if zero bindings were provided.)
  1085. return RD;
  1086. }
  1087. CXXBasePath *BestPath = nullptr;
  1088. for (auto &P : Paths) {
  1089. if (!BestPath)
  1090. BestPath = &P;
  1091. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1092. BestPath->back().Base->getType())) {
  1093. // ... the same ...
  1094. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1095. << false << RD << BestPath->back().Base->getType()
  1096. << P.back().Base->getType();
  1097. return nullptr;
  1098. } else if (P.Access < BestPath->Access) {
  1099. BestPath = &P;
  1100. }
  1101. }
  1102. // ... unambiguous ...
  1103. QualType BaseType = BestPath->back().Base->getType();
  1104. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1105. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1106. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1107. return nullptr;
  1108. }
  1109. // ... public base class of E.
  1110. if (BestPath->Access != AS_public) {
  1111. S.Diag(Loc, diag::err_decomp_decl_non_public_base)
  1112. << RD << BaseType;
  1113. for (auto &BS : *BestPath) {
  1114. if (BS.Base->getAccessSpecifier() != AS_public) {
  1115. S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
  1116. << (BS.Base->getAccessSpecifier() == AS_protected)
  1117. << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
  1118. break;
  1119. }
  1120. }
  1121. return nullptr;
  1122. }
  1123. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1124. S.BuildBasePathArray(Paths, BasePath);
  1125. }
  1126. // The above search did not check whether the selected class itself has base
  1127. // classes with fields, so check that now.
  1128. CXXBasePaths Paths;
  1129. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1130. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1131. << (ClassWithFields == RD) << RD << ClassWithFields
  1132. << Paths.front().back().Base->getType();
  1133. return nullptr;
  1134. }
  1135. return ClassWithFields;
  1136. }
  1137. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1138. ValueDecl *Src, QualType DecompType,
  1139. const CXXRecordDecl *RD) {
  1140. CXXCastPath BasePath;
  1141. RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
  1142. if (!RD)
  1143. return true;
  1144. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1145. DecompType.getQualifiers());
  1146. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1147. unsigned NumFields =
  1148. std::count_if(RD->field_begin(), RD->field_end(),
  1149. [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1150. assert(Bindings.size() != NumFields);
  1151. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1152. << DecompType << (unsigned)Bindings.size() << NumFields
  1153. << (NumFields < Bindings.size());
  1154. return true;
  1155. };
  1156. // all of E's non-static data members shall be public [...] members,
  1157. // E shall not have an anonymous union member, ...
  1158. unsigned I = 0;
  1159. for (auto *FD : RD->fields()) {
  1160. if (FD->isUnnamedBitfield())
  1161. continue;
  1162. if (FD->isAnonymousStructOrUnion()) {
  1163. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1164. << DecompType << FD->getType()->isUnionType();
  1165. S.Diag(FD->getLocation(), diag::note_declared_at);
  1166. return true;
  1167. }
  1168. // We have a real field to bind.
  1169. if (I >= Bindings.size())
  1170. return DiagnoseBadNumberOfBindings();
  1171. auto *B = Bindings[I++];
  1172. SourceLocation Loc = B->getLocation();
  1173. if (FD->getAccess() != AS_public) {
  1174. S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
  1175. // Determine whether the access specifier was explicit.
  1176. bool Implicit = true;
  1177. for (const auto *D : RD->decls()) {
  1178. if (declaresSameEntity(D, FD))
  1179. break;
  1180. if (isa<AccessSpecDecl>(D)) {
  1181. Implicit = false;
  1182. break;
  1183. }
  1184. }
  1185. S.Diag(FD->getLocation(), diag::note_access_natural)
  1186. << (FD->getAccess() == AS_protected) << Implicit;
  1187. return true;
  1188. }
  1189. // Initialize the binding to Src.FD.
  1190. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1191. if (E.isInvalid())
  1192. return true;
  1193. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1194. VK_LValue, &BasePath);
  1195. if (E.isInvalid())
  1196. return true;
  1197. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1198. CXXScopeSpec(), FD,
  1199. DeclAccessPair::make(FD, FD->getAccess()),
  1200. DeclarationNameInfo(FD->getDeclName(), Loc));
  1201. if (E.isInvalid())
  1202. return true;
  1203. // If the type of the member is T, the referenced type is cv T, where cv is
  1204. // the cv-qualification of the decomposition expression.
  1205. //
  1206. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1207. // 'const' to the type of the field.
  1208. Qualifiers Q = DecompType.getQualifiers();
  1209. if (FD->isMutable())
  1210. Q.removeConst();
  1211. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1212. }
  1213. if (I != Bindings.size())
  1214. return DiagnoseBadNumberOfBindings();
  1215. return false;
  1216. }
  1217. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1218. QualType DecompType = DD->getType();
  1219. // If the type of the decomposition is dependent, then so is the type of
  1220. // each binding.
  1221. if (DecompType->isDependentType()) {
  1222. for (auto *B : DD->bindings())
  1223. B->setType(Context.DependentTy);
  1224. return;
  1225. }
  1226. DecompType = DecompType.getNonReferenceType();
  1227. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1228. // C++1z [dcl.decomp]/2:
  1229. // If E is an array type [...]
  1230. // As an extension, we also support decomposition of built-in complex and
  1231. // vector types.
  1232. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1233. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1234. DD->setInvalidDecl();
  1235. return;
  1236. }
  1237. if (auto *VT = DecompType->getAs<VectorType>()) {
  1238. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1239. DD->setInvalidDecl();
  1240. return;
  1241. }
  1242. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1243. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1244. DD->setInvalidDecl();
  1245. return;
  1246. }
  1247. // C++1z [dcl.decomp]/3:
  1248. // if the expression std::tuple_size<E>::value is a well-formed integral
  1249. // constant expression, [...]
  1250. llvm::APSInt TupleSize(32);
  1251. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1252. case IsTupleLike::Error:
  1253. DD->setInvalidDecl();
  1254. return;
  1255. case IsTupleLike::TupleLike:
  1256. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1257. DD->setInvalidDecl();
  1258. return;
  1259. case IsTupleLike::NotTupleLike:
  1260. break;
  1261. }
  1262. // C++1z [dcl.dcl]/8:
  1263. // [E shall be of array or non-union class type]
  1264. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1265. if (!RD || RD->isUnion()) {
  1266. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1267. << DD << !RD << DecompType;
  1268. DD->setInvalidDecl();
  1269. return;
  1270. }
  1271. // C++1z [dcl.decomp]/4:
  1272. // all of E's non-static data members shall be [...] direct members of
  1273. // E or of the same unambiguous public base class of E, ...
  1274. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1275. DD->setInvalidDecl();
  1276. }
  1277. /// \brief Merge the exception specifications of two variable declarations.
  1278. ///
  1279. /// This is called when there's a redeclaration of a VarDecl. The function
  1280. /// checks if the redeclaration might have an exception specification and
  1281. /// validates compatibility and merges the specs if necessary.
  1282. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1283. // Shortcut if exceptions are disabled.
  1284. if (!getLangOpts().CXXExceptions)
  1285. return;
  1286. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1287. "Should only be called if types are otherwise the same.");
  1288. QualType NewType = New->getType();
  1289. QualType OldType = Old->getType();
  1290. // We're only interested in pointers and references to functions, as well
  1291. // as pointers to member functions.
  1292. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1293. NewType = R->getPointeeType();
  1294. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  1295. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1296. NewType = P->getPointeeType();
  1297. OldType = OldType->getAs<PointerType>()->getPointeeType();
  1298. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1299. NewType = M->getPointeeType();
  1300. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  1301. }
  1302. if (!NewType->isFunctionProtoType())
  1303. return;
  1304. // There's lots of special cases for functions. For function pointers, system
  1305. // libraries are hopefully not as broken so that we don't need these
  1306. // workarounds.
  1307. if (CheckEquivalentExceptionSpec(
  1308. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1309. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1310. New->setInvalidDecl();
  1311. }
  1312. }
  1313. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1314. /// function declaration are well-formed according to C++
  1315. /// [dcl.fct.default].
  1316. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1317. unsigned NumParams = FD->getNumParams();
  1318. unsigned p;
  1319. // Find first parameter with a default argument
  1320. for (p = 0; p < NumParams; ++p) {
  1321. ParmVarDecl *Param = FD->getParamDecl(p);
  1322. if (Param->hasDefaultArg())
  1323. break;
  1324. }
  1325. // C++11 [dcl.fct.default]p4:
  1326. // In a given function declaration, each parameter subsequent to a parameter
  1327. // with a default argument shall have a default argument supplied in this or
  1328. // a previous declaration or shall be a function parameter pack. A default
  1329. // argument shall not be redefined by a later declaration (not even to the
  1330. // same value).
  1331. unsigned LastMissingDefaultArg = 0;
  1332. for (; p < NumParams; ++p) {
  1333. ParmVarDecl *Param = FD->getParamDecl(p);
  1334. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  1335. if (Param->isInvalidDecl())
  1336. /* We already complained about this parameter. */;
  1337. else if (Param->getIdentifier())
  1338. Diag(Param->getLocation(),
  1339. diag::err_param_default_argument_missing_name)
  1340. << Param->getIdentifier();
  1341. else
  1342. Diag(Param->getLocation(),
  1343. diag::err_param_default_argument_missing);
  1344. LastMissingDefaultArg = p;
  1345. }
  1346. }
  1347. if (LastMissingDefaultArg > 0) {
  1348. // Some default arguments were missing. Clear out all of the
  1349. // default arguments up to (and including) the last missing
  1350. // default argument, so that we leave the function parameters
  1351. // in a semantically valid state.
  1352. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  1353. ParmVarDecl *Param = FD->getParamDecl(p);
  1354. if (Param->hasDefaultArg()) {
  1355. Param->setDefaultArg(nullptr);
  1356. }
  1357. }
  1358. }
  1359. }
  1360. // CheckConstexprParameterTypes - Check whether a function's parameter types
  1361. // are all literal types. If so, return true. If not, produce a suitable
  1362. // diagnostic and return false.
  1363. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1364. const FunctionDecl *FD) {
  1365. unsigned ArgIndex = 0;
  1366. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  1367. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1368. e = FT->param_type_end();
  1369. i != e; ++i, ++ArgIndex) {
  1370. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1371. SourceLocation ParamLoc = PD->getLocation();
  1372. if (!(*i)->isDependentType() &&
  1373. SemaRef.RequireLiteralType(ParamLoc, *i,
  1374. diag::err_constexpr_non_literal_param,
  1375. ArgIndex+1, PD->getSourceRange(),
  1376. isa<CXXConstructorDecl>(FD)))
  1377. return false;
  1378. }
  1379. return true;
  1380. }
  1381. /// \brief Get diagnostic %select index for tag kind for
  1382. /// record diagnostic message.
  1383. /// WARNING: Indexes apply to particular diagnostics only!
  1384. ///
  1385. /// \returns diagnostic %select index.
  1386. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1387. switch (Tag) {
  1388. case TTK_Struct: return 0;
  1389. case TTK_Interface: return 1;
  1390. case TTK_Class: return 2;
  1391. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1392. }
  1393. }
  1394. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  1395. // the requirements of a constexpr function definition or a constexpr
  1396. // constructor definition. If so, return true. If not, produce appropriate
  1397. // diagnostics and return false.
  1398. //
  1399. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1400. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
  1401. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1402. if (MD && MD->isInstance()) {
  1403. // C++11 [dcl.constexpr]p4:
  1404. // The definition of a constexpr constructor shall satisfy the following
  1405. // constraints:
  1406. // - the class shall not have any virtual base classes;
  1407. const CXXRecordDecl *RD = MD->getParent();
  1408. if (RD->getNumVBases()) {
  1409. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1410. << isa<CXXConstructorDecl>(NewFD)
  1411. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1412. for (const auto &I : RD->vbases())
  1413. Diag(I.getLocStart(),
  1414. diag::note_constexpr_virtual_base_here) << I.getSourceRange();
  1415. return false;
  1416. }
  1417. }
  1418. if (!isa<CXXConstructorDecl>(NewFD)) {
  1419. // C++11 [dcl.constexpr]p3:
  1420. // The definition of a constexpr function shall satisfy the following
  1421. // constraints:
  1422. // - it shall not be virtual;
  1423. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1424. if (Method && Method->isVirtual()) {
  1425. Method = Method->getCanonicalDecl();
  1426. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1427. // If it's not obvious why this function is virtual, find an overridden
  1428. // function which uses the 'virtual' keyword.
  1429. const CXXMethodDecl *WrittenVirtual = Method;
  1430. while (!WrittenVirtual->isVirtualAsWritten())
  1431. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1432. if (WrittenVirtual != Method)
  1433. Diag(WrittenVirtual->getLocation(),
  1434. diag::note_overridden_virtual_function);
  1435. return false;
  1436. }
  1437. // - its return type shall be a literal type;
  1438. QualType RT = NewFD->getReturnType();
  1439. if (!RT->isDependentType() &&
  1440. RequireLiteralType(NewFD->getLocation(), RT,
  1441. diag::err_constexpr_non_literal_return))
  1442. return false;
  1443. }
  1444. // - each of its parameter types shall be a literal type;
  1445. if (!CheckConstexprParameterTypes(*this, NewFD))
  1446. return false;
  1447. return true;
  1448. }
  1449. /// Check the given declaration statement is legal within a constexpr function
  1450. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1451. ///
  1452. /// \return true if the body is OK (maybe only as an extension), false if we
  1453. /// have diagnosed a problem.
  1454. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1455. DeclStmt *DS, SourceLocation &Cxx1yLoc) {
  1456. // C++11 [dcl.constexpr]p3 and p4:
  1457. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1458. // contain only
  1459. for (const auto *DclIt : DS->decls()) {
  1460. switch (DclIt->getKind()) {
  1461. case Decl::StaticAssert:
  1462. case Decl::Using:
  1463. case Decl::UsingShadow:
  1464. case Decl::UsingDirective:
  1465. case Decl::UnresolvedUsingTypename:
  1466. case Decl::UnresolvedUsingValue:
  1467. // - static_assert-declarations
  1468. // - using-declarations,
  1469. // - using-directives,
  1470. continue;
  1471. case Decl::Typedef:
  1472. case Decl::TypeAlias: {
  1473. // - typedef declarations and alias-declarations that do not define
  1474. // classes or enumerations,
  1475. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1476. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1477. // Don't allow variably-modified types in constexpr functions.
  1478. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1479. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1480. << TL.getSourceRange() << TL.getType()
  1481. << isa<CXXConstructorDecl>(Dcl);
  1482. return false;
  1483. }
  1484. continue;
  1485. }
  1486. case Decl::Enum:
  1487. case Decl::CXXRecord:
  1488. // C++1y allows types to be defined, not just declared.
  1489. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
  1490. SemaRef.Diag(DS->getLocStart(),
  1491. SemaRef.getLangOpts().CPlusPlus14
  1492. ? diag::warn_cxx11_compat_constexpr_type_definition
  1493. : diag::ext_constexpr_type_definition)
  1494. << isa<CXXConstructorDecl>(Dcl);
  1495. continue;
  1496. case Decl::EnumConstant:
  1497. case Decl::IndirectField:
  1498. case Decl::ParmVar:
  1499. // These can only appear with other declarations which are banned in
  1500. // C++11 and permitted in C++1y, so ignore them.
  1501. continue;
  1502. case Decl::Var:
  1503. case Decl::Decomposition: {
  1504. // C++1y [dcl.constexpr]p3 allows anything except:
  1505. // a definition of a variable of non-literal type or of static or
  1506. // thread storage duration or for which no initialization is performed.
  1507. const auto *VD = cast<VarDecl>(DclIt);
  1508. if (VD->isThisDeclarationADefinition()) {
  1509. if (VD->isStaticLocal()) {
  1510. SemaRef.Diag(VD->getLocation(),
  1511. diag::err_constexpr_local_var_static)
  1512. << isa<CXXConstructorDecl>(Dcl)
  1513. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1514. return false;
  1515. }
  1516. if (!VD->getType()->isDependentType() &&
  1517. SemaRef.RequireLiteralType(
  1518. VD->getLocation(), VD->getType(),
  1519. diag::err_constexpr_local_var_non_literal_type,
  1520. isa<CXXConstructorDecl>(Dcl)))
  1521. return false;
  1522. if (!VD->getType()->isDependentType() &&
  1523. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1524. SemaRef.Diag(VD->getLocation(),
  1525. diag::err_constexpr_local_var_no_init)
  1526. << isa<CXXConstructorDecl>(Dcl);
  1527. return false;
  1528. }
  1529. }
  1530. SemaRef.Diag(VD->getLocation(),
  1531. SemaRef.getLangOpts().CPlusPlus14
  1532. ? diag::warn_cxx11_compat_constexpr_local_var
  1533. : diag::ext_constexpr_local_var)
  1534. << isa<CXXConstructorDecl>(Dcl);
  1535. continue;
  1536. }
  1537. case Decl::NamespaceAlias:
  1538. case Decl::Function:
  1539. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1540. // everywhere as an extension.
  1541. if (!Cxx1yLoc.isValid())
  1542. Cxx1yLoc = DS->getLocStart();
  1543. continue;
  1544. default:
  1545. SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  1546. << isa<CXXConstructorDecl>(Dcl);
  1547. return false;
  1548. }
  1549. }
  1550. return true;
  1551. }
  1552. /// Check that the given field is initialized within a constexpr constructor.
  1553. ///
  1554. /// \param Dcl The constexpr constructor being checked.
  1555. /// \param Field The field being checked. This may be a member of an anonymous
  1556. /// struct or union nested within the class being checked.
  1557. /// \param Inits All declarations, including anonymous struct/union members and
  1558. /// indirect members, for which any initialization was provided.
  1559. /// \param Diagnosed Set to true if an error is produced.
  1560. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  1561. const FunctionDecl *Dcl,
  1562. FieldDecl *Field,
  1563. llvm::SmallSet<Decl*, 16> &Inits,
  1564. bool &Diagnosed) {
  1565. if (Field->isInvalidDecl())
  1566. return;
  1567. if (Field->isUnnamedBitfield())
  1568. return;
  1569. // Anonymous unions with no variant members and empty anonymous structs do not
  1570. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1571. // indirect fields don't need initializing.
  1572. if (Field->isAnonymousStructOrUnion() &&
  1573. (Field->getType()->isUnionType()
  1574. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1575. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1576. return;
  1577. if (!Inits.count(Field)) {
  1578. if (!Diagnosed) {
  1579. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  1580. Diagnosed = true;
  1581. }
  1582. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  1583. } else if (Field->isAnonymousStructOrUnion()) {
  1584. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1585. for (auto *I : RD->fields())
  1586. // If an anonymous union contains an anonymous struct of which any member
  1587. // is initialized, all members must be initialized.
  1588. if (!RD->isUnion() || Inits.count(I))
  1589. CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
  1590. }
  1591. }
  1592. /// Check the provided statement is allowed in a constexpr function
  1593. /// definition.
  1594. static bool
  1595. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1596. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1597. SourceLocation &Cxx1yLoc) {
  1598. // - its function-body shall be [...] a compound-statement that contains only
  1599. switch (S->getStmtClass()) {
  1600. case Stmt::NullStmtClass:
  1601. // - null statements,
  1602. return true;
  1603. case Stmt::DeclStmtClass:
  1604. // - static_assert-declarations
  1605. // - using-declarations,
  1606. // - using-directives,
  1607. // - typedef declarations and alias-declarations that do not define
  1608. // classes or enumerations,
  1609. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
  1610. return false;
  1611. return true;
  1612. case Stmt::ReturnStmtClass:
  1613. // - and exactly one return statement;
  1614. if (isa<CXXConstructorDecl>(Dcl)) {
  1615. // C++1y allows return statements in constexpr constructors.
  1616. if (!Cxx1yLoc.isValid())
  1617. Cxx1yLoc = S->getLocStart();
  1618. return true;
  1619. }
  1620. ReturnStmts.push_back(S->getLocStart());
  1621. return true;
  1622. case Stmt::CompoundStmtClass: {
  1623. // C++1y allows compound-statements.
  1624. if (!Cxx1yLoc.isValid())
  1625. Cxx1yLoc = S->getLocStart();
  1626. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1627. for (auto *BodyIt : CompStmt->body()) {
  1628. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1629. Cxx1yLoc))
  1630. return false;
  1631. }
  1632. return true;
  1633. }
  1634. case Stmt::AttributedStmtClass:
  1635. if (!Cxx1yLoc.isValid())
  1636. Cxx1yLoc = S->getLocStart();
  1637. return true;
  1638. case Stmt::IfStmtClass: {
  1639. // C++1y allows if-statements.
  1640. if (!Cxx1yLoc.isValid())
  1641. Cxx1yLoc = S->getLocStart();
  1642. IfStmt *If = cast<IfStmt>(S);
  1643. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1644. Cxx1yLoc))
  1645. return false;
  1646. if (If->getElse() &&
  1647. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1648. Cxx1yLoc))
  1649. return false;
  1650. return true;
  1651. }
  1652. case Stmt::WhileStmtClass:
  1653. case Stmt::DoStmtClass:
  1654. case Stmt::ForStmtClass:
  1655. case Stmt::CXXForRangeStmtClass:
  1656. case Stmt::ContinueStmtClass:
  1657. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1658. // because they don't make sense without variable mutation.
  1659. if (!SemaRef.getLangOpts().CPlusPlus14)
  1660. break;
  1661. if (!Cxx1yLoc.isValid())
  1662. Cxx1yLoc = S->getLocStart();
  1663. for (Stmt *SubStmt : S->children())
  1664. if (SubStmt &&
  1665. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1666. Cxx1yLoc))
  1667. return false;
  1668. return true;
  1669. case Stmt::SwitchStmtClass:
  1670. case Stmt::CaseStmtClass:
  1671. case Stmt::DefaultStmtClass:
  1672. case Stmt::BreakStmtClass:
  1673. // C++1y allows switch-statements, and since they don't need variable
  1674. // mutation, we can reasonably allow them in C++11 as an extension.
  1675. if (!Cxx1yLoc.isValid())
  1676. Cxx1yLoc = S->getLocStart();
  1677. for (Stmt *SubStmt : S->children())
  1678. if (SubStmt &&
  1679. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1680. Cxx1yLoc))
  1681. return false;
  1682. return true;
  1683. default:
  1684. if (!isa<Expr>(S))
  1685. break;
  1686. // C++1y allows expression-statements.
  1687. if (!Cxx1yLoc.isValid())
  1688. Cxx1yLoc = S->getLocStart();
  1689. return true;
  1690. }
  1691. SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  1692. << isa<CXXConstructorDecl>(Dcl);
  1693. return false;
  1694. }
  1695. /// Check the body for the given constexpr function declaration only contains
  1696. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1697. ///
  1698. /// \return true if the body is OK, false if we have diagnosed a problem.
  1699. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  1700. if (isa<CXXTryStmt>(Body)) {
  1701. // C++11 [dcl.constexpr]p3:
  1702. // The definition of a constexpr function shall satisfy the following
  1703. // constraints: [...]
  1704. // - its function-body shall be = delete, = default, or a
  1705. // compound-statement
  1706. //
  1707. // C++11 [dcl.constexpr]p4:
  1708. // In the definition of a constexpr constructor, [...]
  1709. // - its function-body shall not be a function-try-block;
  1710. Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
  1711. << isa<CXXConstructorDecl>(Dcl);
  1712. return false;
  1713. }
  1714. SmallVector<SourceLocation, 4> ReturnStmts;
  1715. // - its function-body shall be [...] a compound-statement that contains only
  1716. // [... list of cases ...]
  1717. CompoundStmt *CompBody = cast<CompoundStmt>(Body);
  1718. SourceLocation Cxx1yLoc;
  1719. for (auto *BodyIt : CompBody->body()) {
  1720. if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
  1721. return false;
  1722. }
  1723. if (Cxx1yLoc.isValid())
  1724. Diag(Cxx1yLoc,
  1725. getLangOpts().CPlusPlus14
  1726. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1727. : diag::ext_constexpr_body_invalid_stmt)
  1728. << isa<CXXConstructorDecl>(Dcl);
  1729. if (const CXXConstructorDecl *Constructor
  1730. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1731. const CXXRecordDecl *RD = Constructor->getParent();
  1732. // DR1359:
  1733. // - every non-variant non-static data member and base class sub-object
  1734. // shall be initialized;
  1735. // DR1460:
  1736. // - if the class is a union having variant members, exactly one of them
  1737. // shall be initialized;
  1738. if (RD->isUnion()) {
  1739. if (Constructor->getNumCtorInitializers() == 0 &&
  1740. RD->hasVariantMembers()) {
  1741. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  1742. return false;
  1743. }
  1744. } else if (!Constructor->isDependentContext() &&
  1745. !Constructor->isDelegatingConstructor()) {
  1746. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1747. // Skip detailed checking if we have enough initializers, and we would
  1748. // allow at most one initializer per member.
  1749. bool AnyAnonStructUnionMembers = false;
  1750. unsigned Fields = 0;
  1751. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1752. E = RD->field_end(); I != E; ++I, ++Fields) {
  1753. if (I->isAnonymousStructOrUnion()) {
  1754. AnyAnonStructUnionMembers = true;
  1755. break;
  1756. }
  1757. }
  1758. // DR1460:
  1759. // - if the class is a union-like class, but is not a union, for each of
  1760. // its anonymous union members having variant members, exactly one of
  1761. // them shall be initialized;
  1762. if (AnyAnonStructUnionMembers ||
  1763. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1764. // Check initialization of non-static data members. Base classes are
  1765. // always initialized so do not need to be checked. Dependent bases
  1766. // might not have initializers in the member initializer list.
  1767. llvm::SmallSet<Decl*, 16> Inits;
  1768. for (const auto *I: Constructor->inits()) {
  1769. if (FieldDecl *FD = I->getMember())
  1770. Inits.insert(FD);
  1771. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1772. Inits.insert(ID->chain_begin(), ID->chain_end());
  1773. }
  1774. bool Diagnosed = false;
  1775. for (auto *I : RD->fields())
  1776. CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
  1777. if (Diagnosed)
  1778. return false;
  1779. }
  1780. }
  1781. } else {
  1782. if (ReturnStmts.empty()) {
  1783. // C++1y doesn't require constexpr functions to contain a 'return'
  1784. // statement. We still do, unless the return type might be void, because
  1785. // otherwise if there's no return statement, the function cannot
  1786. // be used in a core constant expression.
  1787. bool OK = getLangOpts().CPlusPlus14 &&
  1788. (Dcl->getReturnType()->isVoidType() ||
  1789. Dcl->getReturnType()->isDependentType());
  1790. Diag(Dcl->getLocation(),
  1791. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1792. : diag::err_constexpr_body_no_return);
  1793. if (!OK)
  1794. return false;
  1795. } else if (ReturnStmts.size() > 1) {
  1796. Diag(ReturnStmts.back(),
  1797. getLangOpts().CPlusPlus14
  1798. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1799. : diag::ext_constexpr_body_multiple_return);
  1800. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1801. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  1802. }
  1803. }
  1804. // C++11 [dcl.constexpr]p5:
  1805. // if no function argument values exist such that the function invocation
  1806. // substitution would produce a constant expression, the program is
  1807. // ill-formed; no diagnostic required.
  1808. // C++11 [dcl.constexpr]p3:
  1809. // - every constructor call and implicit conversion used in initializing the
  1810. // return value shall be one of those allowed in a constant expression.
  1811. // C++11 [dcl.constexpr]p4:
  1812. // - every constructor involved in initializing non-static data members and
  1813. // base class sub-objects shall be a constexpr constructor.
  1814. SmallVector<PartialDiagnosticAt, 8> Diags;
  1815. if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
  1816. Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
  1817. << isa<CXXConstructorDecl>(Dcl);
  1818. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  1819. Diag(Diags[I].first, Diags[I].second);
  1820. // Don't return false here: we allow this for compatibility in
  1821. // system headers.
  1822. }
  1823. return true;
  1824. }
  1825. /// isCurrentClassName - Determine whether the identifier II is the
  1826. /// name of the class type currently being defined. In the case of
  1827. /// nested classes, this will only return true if II is the name of
  1828. /// the innermost class.
  1829. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
  1830. const CXXScopeSpec *SS) {
  1831. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1832. CXXRecordDecl *CurDecl;
  1833. if (SS && SS->isSet() && !SS->isInvalid()) {
  1834. DeclContext *DC = computeDeclContext(*SS, true);
  1835. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1836. } else
  1837. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1838. if (CurDecl && CurDecl->getIdentifier())
  1839. return &II == CurDecl->getIdentifier();
  1840. return false;
  1841. }
  1842. /// \brief Determine whether the identifier II is a typo for the name of
  1843. /// the class type currently being defined. If so, update it to the identifier
  1844. /// that should have been used.
  1845. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  1846. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1847. if (!getLangOpts().SpellChecking)
  1848. return false;
  1849. CXXRecordDecl *CurDecl;
  1850. if (SS && SS->isSet() && !SS->isInvalid()) {
  1851. DeclContext *DC = computeDeclContext(*SS, true);
  1852. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1853. } else
  1854. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1855. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  1856. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  1857. < II->getLength()) {
  1858. II = CurDecl->getIdentifier();
  1859. return true;
  1860. }
  1861. return false;
  1862. }
  1863. /// \brief Determine whether the given class is a base class of the given
  1864. /// class, including looking at dependent bases.
  1865. static bool findCircularInheritance(const CXXRecordDecl *Class,
  1866. const CXXRecordDecl *Current) {
  1867. SmallVector<const CXXRecordDecl*, 8> Queue;
  1868. Class = Class->getCanonicalDecl();
  1869. while (true) {
  1870. for (const auto &I : Current->bases()) {
  1871. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  1872. if (!Base)
  1873. continue;
  1874. Base = Base->getDefinition();
  1875. if (!Base)
  1876. continue;
  1877. if (Base->getCanonicalDecl() == Class)
  1878. return true;
  1879. Queue.push_back(Base);
  1880. }
  1881. if (Queue.empty())
  1882. return false;
  1883. Current = Queue.pop_back_val();
  1884. }
  1885. return false;
  1886. }
  1887. /// \brief Check the validity of a C++ base class specifier.
  1888. ///
  1889. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  1890. /// and returns NULL otherwise.
  1891. CXXBaseSpecifier *
  1892. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  1893. SourceRange SpecifierRange,
  1894. bool Virtual, AccessSpecifier Access,
  1895. TypeSourceInfo *TInfo,
  1896. SourceLocation EllipsisLoc) {
  1897. QualType BaseType = TInfo->getType();
  1898. // C++ [class.union]p1:
  1899. // A union shall not have base classes.
  1900. if (Class->isUnion()) {
  1901. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  1902. << SpecifierRange;
  1903. return nullptr;
  1904. }
  1905. if (EllipsisLoc.isValid() &&
  1906. !TInfo->getType()->containsUnexpandedParameterPack()) {
  1907. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1908. << TInfo->getTypeLoc().getSourceRange();
  1909. EllipsisLoc = SourceLocation();
  1910. }
  1911. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  1912. if (BaseType->isDependentType()) {
  1913. // Make sure that we don't have circular inheritance among our dependent
  1914. // bases. For non-dependent bases, the check for completeness below handles
  1915. // this.
  1916. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  1917. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  1918. ((BaseDecl = BaseDecl->getDefinition()) &&
  1919. findCircularInheritance(Class, BaseDecl))) {
  1920. Diag(BaseLoc, diag::err_circular_inheritance)
  1921. << BaseType << Context.getTypeDeclType(Class);
  1922. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  1923. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  1924. << BaseType;
  1925. return nullptr;
  1926. }
  1927. }
  1928. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1929. Class->getTagKind() == TTK_Class,
  1930. Access, TInfo, EllipsisLoc);
  1931. }
  1932. // Base specifiers must be record types.
  1933. if (!BaseType->isRecordType()) {
  1934. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  1935. return nullptr;
  1936. }
  1937. // C++ [class.union]p1:
  1938. // A union shall not be used as a base class.
  1939. if (BaseType->isUnionType()) {
  1940. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  1941. return nullptr;
  1942. }
  1943. // For the MS ABI, propagate DLL attributes to base class templates.
  1944. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1945. if (Attr *ClassAttr = getDLLAttr(Class)) {
  1946. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  1947. BaseType->getAsCXXRecordDecl())) {
  1948. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  1949. BaseLoc);
  1950. }
  1951. }
  1952. }
  1953. // C++ [class.derived]p2:
  1954. // The class-name in a base-specifier shall not be an incompletely
  1955. // defined class.
  1956. if (RequireCompleteType(BaseLoc, BaseType,
  1957. diag::err_incomplete_base_class, SpecifierRange)) {
  1958. Class->setInvalidDecl();
  1959. return nullptr;
  1960. }
  1961. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  1962. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  1963. assert(BaseDecl && "Record type has no declaration");
  1964. BaseDecl = BaseDecl->getDefinition();
  1965. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  1966. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  1967. assert(CXXBaseDecl && "Base type is not a C++ type");
  1968. // A class which contains a flexible array member is not suitable for use as a
  1969. // base class:
  1970. // - If the layout determines that a base comes before another base,
  1971. // the flexible array member would index into the subsequent base.
  1972. // - If the layout determines that base comes before the derived class,
  1973. // the flexible array member would index into the derived class.
  1974. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  1975. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  1976. << CXXBaseDecl->getDeclName();
  1977. return nullptr;
  1978. }
  1979. // C++ [class]p3:
  1980. // If a class is marked final and it appears as a base-type-specifier in
  1981. // base-clause, the program is ill-formed.
  1982. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  1983. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  1984. << CXXBaseDecl->getDeclName()
  1985. << FA->isSpelledAsSealed();
  1986. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  1987. << CXXBaseDecl->getDeclName() << FA->getRange();
  1988. return nullptr;
  1989. }
  1990. if (BaseDecl->isInvalidDecl())
  1991. Class->setInvalidDecl();
  1992. // Create the base specifier.
  1993. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1994. Class->getTagKind() == TTK_Class,
  1995. Access, TInfo, EllipsisLoc);
  1996. }
  1997. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  1998. /// one entry in the base class list of a class specifier, for
  1999. /// example:
  2000. /// class foo : public bar, virtual private baz {
  2001. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2002. BaseResult
  2003. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2004. ParsedAttributes &Attributes,
  2005. bool Virtual, AccessSpecifier Access,
  2006. ParsedType basetype, SourceLocation BaseLoc,
  2007. SourceLocation EllipsisLoc) {
  2008. if (!classdecl)
  2009. return true;
  2010. AdjustDeclIfTemplate(classdecl);
  2011. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2012. if (!Class)
  2013. return true;
  2014. // We haven't yet attached the base specifiers.
  2015. Class->setIsParsingBaseSpecifiers();
  2016. // We do not support any C++11 attributes on base-specifiers yet.
  2017. // Diagnose any attributes we see.
  2018. if (!Attributes.empty()) {
  2019. for (AttributeList *Attr = Attributes.getList(); Attr;
  2020. Attr = Attr->getNext()) {
  2021. if (Attr->isInvalid() ||
  2022. Attr->getKind() == AttributeList::IgnoredAttribute)
  2023. continue;
  2024. Diag(Attr->getLoc(),
  2025. Attr->getKind() == AttributeList::UnknownAttribute
  2026. ? diag::warn_unknown_attribute_ignored
  2027. : diag::err_base_specifier_attribute)
  2028. << Attr->getName();
  2029. }
  2030. }
  2031. TypeSourceInfo *TInfo = nullptr;
  2032. GetTypeFromParser(basetype, &TInfo);
  2033. if (EllipsisLoc.isInvalid() &&
  2034. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2035. UPPC_BaseType))
  2036. return true;
  2037. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2038. Virtual, Access, TInfo,
  2039. EllipsisLoc))
  2040. return BaseSpec;
  2041. else
  2042. Class->setInvalidDecl();
  2043. return true;
  2044. }
  2045. /// Use small set to collect indirect bases. As this is only used
  2046. /// locally, there's no need to abstract the small size parameter.
  2047. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2048. /// \brief Recursively add the bases of Type. Don't add Type itself.
  2049. static void
  2050. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2051. const QualType &Type)
  2052. {
  2053. // Even though the incoming type is a base, it might not be
  2054. // a class -- it could be a template parm, for instance.
  2055. if (auto Rec = Type->getAs<RecordType>()) {
  2056. auto Decl = Rec->getAsCXXRecordDecl();
  2057. // Iterate over its bases.
  2058. for (const auto &BaseSpec : Decl->bases()) {
  2059. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2060. .getUnqualifiedType();
  2061. if (Set.insert(Base).second)
  2062. // If we've not already seen it, recurse.
  2063. NoteIndirectBases(Context, Set, Base);
  2064. }
  2065. }
  2066. }
  2067. /// \brief Performs the actual work of attaching the given base class
  2068. /// specifiers to a C++ class.
  2069. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2070. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2071. if (Bases.empty())
  2072. return false;
  2073. // Used to keep track of which base types we have already seen, so
  2074. // that we can properly diagnose redundant direct base types. Note
  2075. // that the key is always the unqualified canonical type of the base
  2076. // class.
  2077. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2078. // Used to track indirect bases so we can see if a direct base is
  2079. // ambiguous.
  2080. IndirectBaseSet IndirectBaseTypes;
  2081. // Copy non-redundant base specifiers into permanent storage.
  2082. unsigned NumGoodBases = 0;
  2083. bool Invalid = false;
  2084. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2085. QualType NewBaseType
  2086. = Context.getCanonicalType(Bases[idx]->getType());
  2087. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2088. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2089. if (KnownBase) {
  2090. // C++ [class.mi]p3:
  2091. // A class shall not be specified as a direct base class of a
  2092. // derived class more than once.
  2093. Diag(Bases[idx]->getLocStart(),
  2094. diag::err_duplicate_base_class)
  2095. << KnownBase->getType()
  2096. << Bases[idx]->getSourceRange();
  2097. // Delete the duplicate base class specifier; we're going to
  2098. // overwrite its pointer later.
  2099. Context.Deallocate(Bases[idx]);
  2100. Invalid = true;
  2101. } else {
  2102. // Okay, add this new base class.
  2103. KnownBase = Bases[idx];
  2104. Bases[NumGoodBases++] = Bases[idx];
  2105. // Note this base's direct & indirect bases, if there could be ambiguity.
  2106. if (Bases.size() > 1)
  2107. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2108. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2109. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2110. if (Class->isInterface() &&
  2111. (!RD->isInterface() ||
  2112. KnownBase->getAccessSpecifier() != AS_public)) {
  2113. // The Microsoft extension __interface does not permit bases that
  2114. // are not themselves public interfaces.
  2115. Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
  2116. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
  2117. << RD->getSourceRange();
  2118. Invalid = true;
  2119. }
  2120. if (RD->hasAttr<WeakAttr>())
  2121. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2122. }
  2123. }
  2124. }
  2125. // Attach the remaining base class specifiers to the derived class.
  2126. Class->setBases(Bases.data(), NumGoodBases);
  2127. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2128. // Check whether this direct base is inaccessible due to ambiguity.
  2129. QualType BaseType = Bases[idx]->getType();
  2130. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2131. .getUnqualifiedType();
  2132. if (IndirectBaseTypes.count(CanonicalBase)) {
  2133. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2134. /*DetectVirtual=*/true);
  2135. bool found
  2136. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2137. assert(found);
  2138. (void)found;
  2139. if (Paths.isAmbiguous(CanonicalBase))
  2140. Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
  2141. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2142. << Bases[idx]->getSourceRange();
  2143. else
  2144. assert(Bases[idx]->isVirtual());
  2145. }
  2146. // Delete the base class specifier, since its data has been copied
  2147. // into the CXXRecordDecl.
  2148. Context.Deallocate(Bases[idx]);
  2149. }
  2150. return Invalid;
  2151. }
  2152. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2153. /// class, after checking whether there are any duplicate base
  2154. /// classes.
  2155. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2156. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2157. if (!ClassDecl || Bases.empty())
  2158. return;
  2159. AdjustDeclIfTemplate(ClassDecl);
  2160. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2161. }
  2162. /// \brief Determine whether the type \p Derived is a C++ class that is
  2163. /// derived from the type \p Base.
  2164. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2165. if (!getLangOpts().CPlusPlus)
  2166. return false;
  2167. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2168. if (!DerivedRD)
  2169. return false;
  2170. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2171. if (!BaseRD)
  2172. return false;
  2173. // If either the base or the derived type is invalid, don't try to
  2174. // check whether one is derived from the other.
  2175. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2176. return false;
  2177. // FIXME: In a modules build, do we need the entire path to be visible for us
  2178. // to be able to use the inheritance relationship?
  2179. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2180. return false;
  2181. return DerivedRD->isDerivedFrom(BaseRD);
  2182. }
  2183. /// \brief Determine whether the type \p Derived is a C++ class that is
  2184. /// derived from the type \p Base.
  2185. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2186. CXXBasePaths &Paths) {
  2187. if (!getLangOpts().CPlusPlus)
  2188. return false;
  2189. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2190. if (!DerivedRD)
  2191. return false;
  2192. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2193. if (!BaseRD)
  2194. return false;
  2195. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2196. return false;
  2197. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2198. }
  2199. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2200. CXXCastPath &BasePathArray) {
  2201. assert(BasePathArray.empty() && "Base path array must be empty!");
  2202. assert(Paths.isRecordingPaths() && "Must record paths!");
  2203. const CXXBasePath &Path = Paths.front();
  2204. // We first go backward and check if we have a virtual base.
  2205. // FIXME: It would be better if CXXBasePath had the base specifier for
  2206. // the nearest virtual base.
  2207. unsigned Start = 0;
  2208. for (unsigned I = Path.size(); I != 0; --I) {
  2209. if (Path[I - 1].Base->isVirtual()) {
  2210. Start = I - 1;
  2211. break;
  2212. }
  2213. }
  2214. // Now add all bases.
  2215. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2216. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2217. }
  2218. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2219. /// conversion (where Derived and Base are class types) is
  2220. /// well-formed, meaning that the conversion is unambiguous (and
  2221. /// that all of the base classes are accessible). Returns true
  2222. /// and emits a diagnostic if the code is ill-formed, returns false
  2223. /// otherwise. Loc is the location where this routine should point to
  2224. /// if there is an error, and Range is the source range to highlight
  2225. /// if there is an error.
  2226. ///
  2227. /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
  2228. /// diagnostic for the respective type of error will be suppressed, but the
  2229. /// check for ill-formed code will still be performed.
  2230. bool
  2231. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2232. unsigned InaccessibleBaseID,
  2233. unsigned AmbigiousBaseConvID,
  2234. SourceLocation Loc, SourceRange Range,
  2235. DeclarationName Name,
  2236. CXXCastPath *BasePath,
  2237. bool IgnoreAccess) {
  2238. // First, determine whether the path from Derived to Base is
  2239. // ambiguous. This is slightly more expensive than checking whether
  2240. // the Derived to Base conversion exists, because here we need to
  2241. // explore multiple paths to determine if there is an ambiguity.
  2242. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2243. /*DetectVirtual=*/false);
  2244. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2245. assert(DerivationOkay &&
  2246. "Can only be used with a derived-to-base conversion");
  2247. (void)DerivationOkay;
  2248. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
  2249. if (!IgnoreAccess) {
  2250. // Check that the base class can be accessed.
  2251. switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
  2252. InaccessibleBaseID)) {
  2253. case AR_inaccessible:
  2254. return true;
  2255. case AR_accessible:
  2256. case AR_dependent:
  2257. case AR_delayed:
  2258. break;
  2259. }
  2260. }
  2261. // Build a base path if necessary.
  2262. if (BasePath)
  2263. BuildBasePathArray(Paths, *BasePath);
  2264. return false;
  2265. }
  2266. if (AmbigiousBaseConvID) {
  2267. // We know that the derived-to-base conversion is ambiguous, and
  2268. // we're going to produce a diagnostic. Perform the derived-to-base
  2269. // search just one more time to compute all of the possible paths so
  2270. // that we can print them out. This is more expensive than any of
  2271. // the previous derived-to-base checks we've done, but at this point
  2272. // performance isn't as much of an issue.
  2273. Paths.clear();
  2274. Paths.setRecordingPaths(true);
  2275. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2276. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2277. (void)StillOkay;
  2278. // Build up a textual representation of the ambiguous paths, e.g.,
  2279. // D -> B -> A, that will be used to illustrate the ambiguous
  2280. // conversions in the diagnostic. We only print one of the paths
  2281. // to each base class subobject.
  2282. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2283. Diag(Loc, AmbigiousBaseConvID)
  2284. << Derived << Base << PathDisplayStr << Range << Name;
  2285. }
  2286. return true;
  2287. }
  2288. bool
  2289. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2290. SourceLocation Loc, SourceRange Range,
  2291. CXXCastPath *BasePath,
  2292. bool IgnoreAccess) {
  2293. return CheckDerivedToBaseConversion(
  2294. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2295. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2296. BasePath, IgnoreAccess);
  2297. }
  2298. /// @brief Builds a string representing ambiguous paths from a
  2299. /// specific derived class to different subobjects of the same base
  2300. /// class.
  2301. ///
  2302. /// This function builds a string that can be used in error messages
  2303. /// to show the different paths that one can take through the
  2304. /// inheritance hierarchy to go from the derived class to different
  2305. /// subobjects of a base class. The result looks something like this:
  2306. /// @code
  2307. /// struct D -> struct B -> struct A
  2308. /// struct D -> struct C -> struct A
  2309. /// @endcode
  2310. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2311. std::string PathDisplayStr;
  2312. std::set<unsigned> DisplayedPaths;
  2313. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2314. Path != Paths.end(); ++Path) {
  2315. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2316. // We haven't displayed a path to this particular base
  2317. // class subobject yet.
  2318. PathDisplayStr += "\n ";
  2319. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2320. for (CXXBasePath::const_iterator Element = Path->begin();
  2321. Element != Path->end(); ++Element)
  2322. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2323. }
  2324. }
  2325. return PathDisplayStr;
  2326. }
  2327. //===----------------------------------------------------------------------===//
  2328. // C++ class member Handling
  2329. //===----------------------------------------------------------------------===//
  2330. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2331. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
  2332. SourceLocation ASLoc,
  2333. SourceLocation ColonLoc,
  2334. AttributeList *Attrs) {
  2335. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2336. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2337. ASLoc, ColonLoc);
  2338. CurContext->addHiddenDecl(ASDecl);
  2339. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2340. }
  2341. /// CheckOverrideControl - Check C++11 override control semantics.
  2342. void Sema::CheckOverrideControl(NamedDecl *D) {
  2343. if (D->isInvalidDecl())
  2344. return;
  2345. // We only care about "override" and "final" declarations.
  2346. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2347. return;
  2348. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2349. // We can't check dependent instance methods.
  2350. if (MD && MD->isInstance() &&
  2351. (MD->getParent()->hasAnyDependentBases() ||
  2352. MD->getType()->isDependentType()))
  2353. return;
  2354. if (MD && !MD->isVirtual()) {
  2355. // If we have a non-virtual method, check if if hides a virtual method.
  2356. // (In that case, it's most likely the method has the wrong type.)
  2357. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2358. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2359. if (!OverloadedMethods.empty()) {
  2360. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2361. Diag(OA->getLocation(),
  2362. diag::override_keyword_hides_virtual_member_function)
  2363. << "override" << (OverloadedMethods.size() > 1);
  2364. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2365. Diag(FA->getLocation(),
  2366. diag::override_keyword_hides_virtual_member_function)
  2367. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2368. << (OverloadedMethods.size() > 1);
  2369. }
  2370. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2371. MD->setInvalidDecl();
  2372. return;
  2373. }
  2374. // Fall through into the general case diagnostic.
  2375. // FIXME: We might want to attempt typo correction here.
  2376. }
  2377. if (!MD || !MD->isVirtual()) {
  2378. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2379. Diag(OA->getLocation(),
  2380. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2381. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2382. D->dropAttr<OverrideAttr>();
  2383. }
  2384. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2385. Diag(FA->getLocation(),
  2386. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2387. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2388. << FixItHint::CreateRemoval(FA->getLocation());
  2389. D->dropAttr<FinalAttr>();
  2390. }
  2391. return;
  2392. }
  2393. // C++11 [class.virtual]p5:
  2394. // If a function is marked with the virt-specifier override and
  2395. // does not override a member function of a base class, the program is
  2396. // ill-formed.
  2397. bool HasOverriddenMethods =
  2398. MD->begin_overridden_methods() != MD->end_overridden_methods();
  2399. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2400. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2401. << MD->getDeclName();
  2402. }
  2403. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  2404. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2405. return;
  2406. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2407. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
  2408. isa<CXXDestructorDecl>(MD))
  2409. return;
  2410. SourceLocation Loc = MD->getLocation();
  2411. SourceLocation SpellingLoc = Loc;
  2412. if (getSourceManager().isMacroArgExpansion(Loc))
  2413. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
  2414. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2415. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2416. return;
  2417. if (MD->size_overridden_methods() > 0) {
  2418. Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
  2419. << MD->getDeclName();
  2420. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2421. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2422. }
  2423. }
  2424. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2425. /// function overrides a virtual member function marked 'final', according to
  2426. /// C++11 [class.virtual]p4.
  2427. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2428. const CXXMethodDecl *Old) {
  2429. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2430. if (!FA)
  2431. return false;
  2432. Diag(New->getLocation(), diag::err_final_function_overridden)
  2433. << New->getDeclName()
  2434. << FA->isSpelledAsSealed();
  2435. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2436. return true;
  2437. }
  2438. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2439. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2440. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2441. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2442. return !RD->isCompleteDefinition() ||
  2443. !RD->hasTrivialDefaultConstructor() ||
  2444. !RD->hasTrivialDestructor();
  2445. return false;
  2446. }
  2447. static AttributeList *getMSPropertyAttr(AttributeList *list) {
  2448. for (AttributeList *it = list; it != nullptr; it = it->getNext())
  2449. if (it->isDeclspecPropertyAttribute())
  2450. return it;
  2451. return nullptr;
  2452. }
  2453. // Check if there is a field shadowing.
  2454. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2455. DeclarationName FieldName,
  2456. const CXXRecordDecl *RD) {
  2457. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2458. return;
  2459. // To record a shadowed field in a base
  2460. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2461. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2462. CXXBasePath &Path) {
  2463. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2464. // Record an ambiguous path directly
  2465. if (Bases.find(Base) != Bases.end())
  2466. return true;
  2467. for (const auto Field : Base->lookup(FieldName)) {
  2468. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2469. Field->getAccess() != AS_private) {
  2470. assert(Field->getAccess() != AS_none);
  2471. assert(Bases.find(Base) == Bases.end());
  2472. Bases[Base] = Field;
  2473. return true;
  2474. }
  2475. }
  2476. return false;
  2477. };
  2478. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2479. /*DetectVirtual=*/true);
  2480. if (!RD->lookupInBases(FieldShadowed, Paths))
  2481. return;
  2482. for (const auto &P : Paths) {
  2483. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2484. auto It = Bases.find(Base);
  2485. // Skip duplicated bases
  2486. if (It == Bases.end())
  2487. continue;
  2488. auto BaseField = It->second;
  2489. assert(BaseField->getAccess() != AS_private);
  2490. if (AS_none !=
  2491. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2492. Diag(Loc, diag::warn_shadow_field)
  2493. << FieldName.getAsString() << RD->getName() << Base->getName();
  2494. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2495. Bases.erase(It);
  2496. }
  2497. }
  2498. }
  2499. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2500. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2501. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2502. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2503. /// present (but parsing it has been deferred).
  2504. NamedDecl *
  2505. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2506. MultiTemplateParamsArg TemplateParameterLists,
  2507. Expr *BW, const VirtSpecifiers &VS,
  2508. InClassInitStyle InitStyle) {
  2509. const DeclSpec &DS = D.getDeclSpec();
  2510. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2511. DeclarationName Name = NameInfo.getName();
  2512. SourceLocation Loc = NameInfo.getLoc();
  2513. // For anonymous bitfields, the location should point to the type.
  2514. if (Loc.isInvalid())
  2515. Loc = D.getLocStart();
  2516. Expr *BitWidth = static_cast<Expr*>(BW);
  2517. assert(isa<CXXRecordDecl>(CurContext));
  2518. assert(!DS.isFriendSpecified());
  2519. bool isFunc = D.isDeclarationOfFunction();
  2520. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2521. // The Microsoft extension __interface only permits public member functions
  2522. // and prohibits constructors, destructors, operators, non-public member
  2523. // functions, static methods and data members.
  2524. unsigned InvalidDecl;
  2525. bool ShowDeclName = true;
  2526. if (!isFunc)
  2527. InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
  2528. else if (AS != AS_public)
  2529. InvalidDecl = 2;
  2530. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2531. InvalidDecl = 3;
  2532. else switch (Name.getNameKind()) {
  2533. case DeclarationName::CXXConstructorName:
  2534. InvalidDecl = 4;
  2535. ShowDeclName = false;
  2536. break;
  2537. case DeclarationName::CXXDestructorName:
  2538. InvalidDecl = 5;
  2539. ShowDeclName = false;
  2540. break;
  2541. case DeclarationName::CXXOperatorName:
  2542. case DeclarationName::CXXConversionFunctionName:
  2543. InvalidDecl = 6;
  2544. break;
  2545. default:
  2546. InvalidDecl = 0;
  2547. break;
  2548. }
  2549. if (InvalidDecl) {
  2550. if (ShowDeclName)
  2551. Diag(Loc, diag::err_invalid_member_in_interface)
  2552. << (InvalidDecl-1) << Name;
  2553. else
  2554. Diag(Loc, diag::err_invalid_member_in_interface)
  2555. << (InvalidDecl-1) << "";
  2556. return nullptr;
  2557. }
  2558. }
  2559. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2560. // duration (auto, register) or with the extern storage-class-specifier.
  2561. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2562. // data members and cannot be applied to names declared const or static,
  2563. // and cannot be applied to reference members.
  2564. switch (DS.getStorageClassSpec()) {
  2565. case DeclSpec::SCS_unspecified:
  2566. case DeclSpec::SCS_typedef:
  2567. case DeclSpec::SCS_static:
  2568. break;
  2569. case DeclSpec::SCS_mutable:
  2570. if (isFunc) {
  2571. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2572. // FIXME: It would be nicer if the keyword was ignored only for this
  2573. // declarator. Otherwise we could get follow-up errors.
  2574. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2575. }
  2576. break;
  2577. default:
  2578. Diag(DS.getStorageClassSpecLoc(),
  2579. diag::err_storageclass_invalid_for_member);
  2580. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2581. break;
  2582. }
  2583. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2584. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2585. !isFunc);
  2586. if (DS.isConstexprSpecified() && isInstField) {
  2587. SemaDiagnosticBuilder B =
  2588. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2589. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2590. if (InitStyle == ICIS_NoInit) {
  2591. B << 0 << 0;
  2592. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2593. B << FixItHint::CreateRemoval(ConstexprLoc);
  2594. else {
  2595. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2596. D.getMutableDeclSpec().ClearConstexprSpec();
  2597. const char *PrevSpec;
  2598. unsigned DiagID;
  2599. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2600. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2601. (void)Failed;
  2602. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2603. }
  2604. } else {
  2605. B << 1;
  2606. const char *PrevSpec;
  2607. unsigned DiagID;
  2608. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2609. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2610. Context.getPrintingPolicy())) {
  2611. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2612. "This is the only DeclSpec that should fail to be applied");
  2613. B << 1;
  2614. } else {
  2615. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2616. isInstField = false;
  2617. }
  2618. }
  2619. }
  2620. NamedDecl *Member;
  2621. if (isInstField) {
  2622. CXXScopeSpec &SS = D.getCXXScopeSpec();
  2623. // Data members must have identifiers for names.
  2624. if (!Name.isIdentifier()) {
  2625. Diag(Loc, diag::err_bad_variable_name)
  2626. << Name;
  2627. return nullptr;
  2628. }
  2629. IdentifierInfo *II = Name.getAsIdentifierInfo();
  2630. // Member field could not be with "template" keyword.
  2631. // So TemplateParameterLists should be empty in this case.
  2632. if (TemplateParameterLists.size()) {
  2633. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  2634. if (TemplateParams->size()) {
  2635. // There is no such thing as a member field template.
  2636. Diag(D.getIdentifierLoc(), diag::err_template_member)
  2637. << II
  2638. << SourceRange(TemplateParams->getTemplateLoc(),
  2639. TemplateParams->getRAngleLoc());
  2640. } else {
  2641. // There is an extraneous 'template<>' for this member.
  2642. Diag(TemplateParams->getTemplateLoc(),
  2643. diag::err_template_member_noparams)
  2644. << II
  2645. << SourceRange(TemplateParams->getTemplateLoc(),
  2646. TemplateParams->getRAngleLoc());
  2647. }
  2648. return nullptr;
  2649. }
  2650. if (SS.isSet() && !SS.isInvalid()) {
  2651. // The user provided a superfluous scope specifier inside a class
  2652. // definition:
  2653. //
  2654. // class X {
  2655. // int X::member;
  2656. // };
  2657. if (DeclContext *DC = computeDeclContext(SS, false))
  2658. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
  2659. else
  2660. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  2661. << Name << SS.getRange();
  2662. SS.clear();
  2663. }
  2664. AttributeList *MSPropertyAttr =
  2665. getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
  2666. if (MSPropertyAttr) {
  2667. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2668. BitWidth, InitStyle, AS, MSPropertyAttr);
  2669. if (!Member)
  2670. return nullptr;
  2671. isInstField = false;
  2672. } else {
  2673. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  2674. BitWidth, InitStyle, AS);
  2675. if (!Member)
  2676. return nullptr;
  2677. }
  2678. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  2679. } else {
  2680. Member = HandleDeclarator(S, D, TemplateParameterLists);
  2681. if (!Member)
  2682. return nullptr;
  2683. // Non-instance-fields can't have a bitfield.
  2684. if (BitWidth) {
  2685. if (Member->isInvalidDecl()) {
  2686. // don't emit another diagnostic.
  2687. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  2688. // C++ 9.6p3: A bit-field shall not be a static member.
  2689. // "static member 'A' cannot be a bit-field"
  2690. Diag(Loc, diag::err_static_not_bitfield)
  2691. << Name << BitWidth->getSourceRange();
  2692. } else if (isa<TypedefDecl>(Member)) {
  2693. // "typedef member 'x' cannot be a bit-field"
  2694. Diag(Loc, diag::err_typedef_not_bitfield)
  2695. << Name << BitWidth->getSourceRange();
  2696. } else {
  2697. // A function typedef ("typedef int f(); f a;").
  2698. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  2699. Diag(Loc, diag::err_not_integral_type_bitfield)
  2700. << Name << cast<ValueDecl>(Member)->getType()
  2701. << BitWidth->getSourceRange();
  2702. }
  2703. BitWidth = nullptr;
  2704. Member->setInvalidDecl();
  2705. }
  2706. Member->setAccess(AS);
  2707. // If we have declared a member function template or static data member
  2708. // template, set the access of the templated declaration as well.
  2709. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2710. FunTmpl->getTemplatedDecl()->setAccess(AS);
  2711. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2712. VarTmpl->getTemplatedDecl()->setAccess(AS);
  2713. }
  2714. if (VS.isOverrideSpecified())
  2715. Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
  2716. if (VS.isFinalSpecified())
  2717. Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
  2718. VS.isFinalSpelledSealed()));
  2719. if (VS.getLastLocation().isValid()) {
  2720. // Update the end location of a method that has a virt-specifiers.
  2721. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2722. MD->setRangeEnd(VS.getLastLocation());
  2723. }
  2724. CheckOverrideControl(Member);
  2725. assert((Name || isInstField) && "No identifier for non-field ?");
  2726. if (isInstField) {
  2727. FieldDecl *FD = cast<FieldDecl>(Member);
  2728. FieldCollector->Add(FD);
  2729. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2730. // Remember all explicit private FieldDecls that have a name, no side
  2731. // effects and are not part of a dependent type declaration.
  2732. if (!FD->isImplicit() && FD->getDeclName() &&
  2733. FD->getAccess() == AS_private &&
  2734. !FD->hasAttr<UnusedAttr>() &&
  2735. !FD->getParent()->isDependentContext() &&
  2736. !InitializationHasSideEffects(*FD))
  2737. UnusedPrivateFields.insert(FD);
  2738. }
  2739. }
  2740. return Member;
  2741. }
  2742. namespace {
  2743. class UninitializedFieldVisitor
  2744. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  2745. Sema &S;
  2746. // List of Decls to generate a warning on. Also remove Decls that become
  2747. // initialized.
  2748. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  2749. // List of base classes of the record. Classes are removed after their
  2750. // initializers.
  2751. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  2752. // Vector of decls to be removed from the Decl set prior to visiting the
  2753. // nodes. These Decls may have been initialized in the prior initializer.
  2754. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  2755. // If non-null, add a note to the warning pointing back to the constructor.
  2756. const CXXConstructorDecl *Constructor;
  2757. // Variables to hold state when processing an initializer list. When
  2758. // InitList is true, special case initialization of FieldDecls matching
  2759. // InitListFieldDecl.
  2760. bool InitList;
  2761. FieldDecl *InitListFieldDecl;
  2762. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  2763. public:
  2764. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  2765. UninitializedFieldVisitor(Sema &S,
  2766. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  2767. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  2768. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  2769. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  2770. // Returns true if the use of ME is not an uninitialized use.
  2771. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  2772. bool CheckReferenceOnly) {
  2773. llvm::SmallVector<FieldDecl*, 4> Fields;
  2774. bool ReferenceField = false;
  2775. while (ME) {
  2776. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  2777. if (!FD)
  2778. return false;
  2779. Fields.push_back(FD);
  2780. if (FD->getType()->isReferenceType())
  2781. ReferenceField = true;
  2782. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  2783. }
  2784. // Binding a reference to an unintialized field is not an
  2785. // uninitialized use.
  2786. if (CheckReferenceOnly && !ReferenceField)
  2787. return true;
  2788. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  2789. // Discard the first field since it is the field decl that is being
  2790. // initialized.
  2791. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  2792. UsedFieldIndex.push_back((*I)->getFieldIndex());
  2793. }
  2794. for (auto UsedIter = UsedFieldIndex.begin(),
  2795. UsedEnd = UsedFieldIndex.end(),
  2796. OrigIter = InitFieldIndex.begin(),
  2797. OrigEnd = InitFieldIndex.end();
  2798. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  2799. if (*UsedIter < *OrigIter)
  2800. return true;
  2801. if (*UsedIter > *OrigIter)
  2802. break;
  2803. }
  2804. return false;
  2805. }
  2806. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  2807. bool AddressOf) {
  2808. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  2809. return;
  2810. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  2811. // or union.
  2812. MemberExpr *FieldME = ME;
  2813. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  2814. Expr *Base = ME;
  2815. while (MemberExpr *SubME =
  2816. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  2817. if (isa<VarDecl>(SubME->getMemberDecl()))
  2818. return;
  2819. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  2820. if (!FD->isAnonymousStructOrUnion())
  2821. FieldME = SubME;
  2822. if (!FieldME->getType().isPODType(S.Context))
  2823. AllPODFields = false;
  2824. Base = SubME->getBase();
  2825. }
  2826. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  2827. return;
  2828. if (AddressOf && AllPODFields)
  2829. return;
  2830. ValueDecl* FoundVD = FieldME->getMemberDecl();
  2831. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  2832. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  2833. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  2834. }
  2835. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  2836. QualType T = BaseCast->getType();
  2837. if (T->isPointerType() &&
  2838. BaseClasses.count(T->getPointeeType())) {
  2839. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  2840. << T->getPointeeType() << FoundVD;
  2841. }
  2842. }
  2843. }
  2844. if (!Decls.count(FoundVD))
  2845. return;
  2846. const bool IsReference = FoundVD->getType()->isReferenceType();
  2847. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  2848. // Special checking for initializer lists.
  2849. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  2850. return;
  2851. }
  2852. } else {
  2853. // Prevent double warnings on use of unbounded references.
  2854. if (CheckReferenceOnly && !IsReference)
  2855. return;
  2856. }
  2857. unsigned diag = IsReference
  2858. ? diag::warn_reference_field_is_uninit
  2859. : diag::warn_field_is_uninit;
  2860. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  2861. if (Constructor)
  2862. S.Diag(Constructor->getLocation(),
  2863. diag::note_uninit_in_this_constructor)
  2864. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  2865. }
  2866. void HandleValue(Expr *E, bool AddressOf) {
  2867. E = E->IgnoreParens();
  2868. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  2869. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  2870. AddressOf /*AddressOf*/);
  2871. return;
  2872. }
  2873. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2874. Visit(CO->getCond());
  2875. HandleValue(CO->getTrueExpr(), AddressOf);
  2876. HandleValue(CO->getFalseExpr(), AddressOf);
  2877. return;
  2878. }
  2879. if (BinaryConditionalOperator *BCO =
  2880. dyn_cast<BinaryConditionalOperator>(E)) {
  2881. Visit(BCO->getCond());
  2882. HandleValue(BCO->getFalseExpr(), AddressOf);
  2883. return;
  2884. }
  2885. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  2886. HandleValue(OVE->getSourceExpr(), AddressOf);
  2887. return;
  2888. }
  2889. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2890. switch (BO->getOpcode()) {
  2891. default:
  2892. break;
  2893. case(BO_PtrMemD):
  2894. case(BO_PtrMemI):
  2895. HandleValue(BO->getLHS(), AddressOf);
  2896. Visit(BO->getRHS());
  2897. return;
  2898. case(BO_Comma):
  2899. Visit(BO->getLHS());
  2900. HandleValue(BO->getRHS(), AddressOf);
  2901. return;
  2902. }
  2903. }
  2904. Visit(E);
  2905. }
  2906. void CheckInitListExpr(InitListExpr *ILE) {
  2907. InitFieldIndex.push_back(0);
  2908. for (auto Child : ILE->children()) {
  2909. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  2910. CheckInitListExpr(SubList);
  2911. } else {
  2912. Visit(Child);
  2913. }
  2914. ++InitFieldIndex.back();
  2915. }
  2916. InitFieldIndex.pop_back();
  2917. }
  2918. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  2919. FieldDecl *Field, const Type *BaseClass) {
  2920. // Remove Decls that may have been initialized in the previous
  2921. // initializer.
  2922. for (ValueDecl* VD : DeclsToRemove)
  2923. Decls.erase(VD);
  2924. DeclsToRemove.clear();
  2925. Constructor = FieldConstructor;
  2926. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  2927. if (ILE && Field) {
  2928. InitList = true;
  2929. InitListFieldDecl = Field;
  2930. InitFieldIndex.clear();
  2931. CheckInitListExpr(ILE);
  2932. } else {
  2933. InitList = false;
  2934. Visit(E);
  2935. }
  2936. if (Field)
  2937. Decls.erase(Field);
  2938. if (BaseClass)
  2939. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  2940. }
  2941. void VisitMemberExpr(MemberExpr *ME) {
  2942. // All uses of unbounded reference fields will warn.
  2943. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  2944. }
  2945. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  2946. if (E->getCastKind() == CK_LValueToRValue) {
  2947. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  2948. return;
  2949. }
  2950. Inherited::VisitImplicitCastExpr(E);
  2951. }
  2952. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  2953. if (E->getConstructor()->isCopyConstructor()) {
  2954. Expr *ArgExpr = E->getArg(0);
  2955. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  2956. if (ILE->getNumInits() == 1)
  2957. ArgExpr = ILE->getInit(0);
  2958. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  2959. if (ICE->getCastKind() == CK_NoOp)
  2960. ArgExpr = ICE->getSubExpr();
  2961. HandleValue(ArgExpr, false /*AddressOf*/);
  2962. return;
  2963. }
  2964. Inherited::VisitCXXConstructExpr(E);
  2965. }
  2966. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2967. Expr *Callee = E->getCallee();
  2968. if (isa<MemberExpr>(Callee)) {
  2969. HandleValue(Callee, false /*AddressOf*/);
  2970. for (auto Arg : E->arguments())
  2971. Visit(Arg);
  2972. return;
  2973. }
  2974. Inherited::VisitCXXMemberCallExpr(E);
  2975. }
  2976. void VisitCallExpr(CallExpr *E) {
  2977. // Treat std::move as a use.
  2978. if (E->getNumArgs() == 1) {
  2979. if (FunctionDecl *FD = E->getDirectCallee()) {
  2980. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  2981. FD->getIdentifier()->isStr("move")) {
  2982. HandleValue(E->getArg(0), false /*AddressOf*/);
  2983. return;
  2984. }
  2985. }
  2986. }
  2987. Inherited::VisitCallExpr(E);
  2988. }
  2989. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  2990. Expr *Callee = E->getCallee();
  2991. if (isa<UnresolvedLookupExpr>(Callee))
  2992. return Inherited::VisitCXXOperatorCallExpr(E);
  2993. Visit(Callee);
  2994. for (auto Arg : E->arguments())
  2995. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  2996. }
  2997. void VisitBinaryOperator(BinaryOperator *E) {
  2998. // If a field assignment is detected, remove the field from the
  2999. // uninitiailized field set.
  3000. if (E->getOpcode() == BO_Assign)
  3001. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3002. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3003. if (!FD->getType()->isReferenceType())
  3004. DeclsToRemove.push_back(FD);
  3005. if (E->isCompoundAssignmentOp()) {
  3006. HandleValue(E->getLHS(), false /*AddressOf*/);
  3007. Visit(E->getRHS());
  3008. return;
  3009. }
  3010. Inherited::VisitBinaryOperator(E);
  3011. }
  3012. void VisitUnaryOperator(UnaryOperator *E) {
  3013. if (E->isIncrementDecrementOp()) {
  3014. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3015. return;
  3016. }
  3017. if (E->getOpcode() == UO_AddrOf) {
  3018. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3019. HandleValue(ME->getBase(), true /*AddressOf*/);
  3020. return;
  3021. }
  3022. }
  3023. Inherited::VisitUnaryOperator(E);
  3024. }
  3025. };
  3026. // Diagnose value-uses of fields to initialize themselves, e.g.
  3027. // foo(foo)
  3028. // where foo is not also a parameter to the constructor.
  3029. // Also diagnose across field uninitialized use such as
  3030. // x(y), y(x)
  3031. // TODO: implement -Wuninitialized and fold this into that framework.
  3032. static void DiagnoseUninitializedFields(
  3033. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3034. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3035. Constructor->getLocation())) {
  3036. return;
  3037. }
  3038. if (Constructor->isInvalidDecl())
  3039. return;
  3040. const CXXRecordDecl *RD = Constructor->getParent();
  3041. if (RD->getDescribedClassTemplate())
  3042. return;
  3043. // Holds fields that are uninitialized.
  3044. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3045. // At the beginning, all fields are uninitialized.
  3046. for (auto *I : RD->decls()) {
  3047. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3048. UninitializedFields.insert(FD);
  3049. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3050. UninitializedFields.insert(IFD->getAnonField());
  3051. }
  3052. }
  3053. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3054. for (auto I : RD->bases())
  3055. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3056. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3057. return;
  3058. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3059. UninitializedFields,
  3060. UninitializedBaseClasses);
  3061. for (const auto *FieldInit : Constructor->inits()) {
  3062. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3063. break;
  3064. Expr *InitExpr = FieldInit->getInit();
  3065. if (!InitExpr)
  3066. continue;
  3067. if (CXXDefaultInitExpr *Default =
  3068. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3069. InitExpr = Default->getExpr();
  3070. if (!InitExpr)
  3071. continue;
  3072. // In class initializers will point to the constructor.
  3073. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3074. FieldInit->getAnyMember(),
  3075. FieldInit->getBaseClass());
  3076. } else {
  3077. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3078. FieldInit->getAnyMember(),
  3079. FieldInit->getBaseClass());
  3080. }
  3081. }
  3082. }
  3083. } // namespace
  3084. /// \brief Enter a new C++ default initializer scope. After calling this, the
  3085. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3086. /// parsing or instantiating the initializer failed.
  3087. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3088. // Create a synthetic function scope to represent the call to the constructor
  3089. // that notionally surrounds a use of this initializer.
  3090. PushFunctionScope();
  3091. }
  3092. /// \brief This is invoked after parsing an in-class initializer for a
  3093. /// non-static C++ class member, and after instantiating an in-class initializer
  3094. /// in a class template. Such actions are deferred until the class is complete.
  3095. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3096. SourceLocation InitLoc,
  3097. Expr *InitExpr) {
  3098. // Pop the notional constructor scope we created earlier.
  3099. PopFunctionScopeInfo(nullptr, D);
  3100. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3101. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3102. "must set init style when field is created");
  3103. if (!InitExpr) {
  3104. D->setInvalidDecl();
  3105. if (FD)
  3106. FD->removeInClassInitializer();
  3107. return;
  3108. }
  3109. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3110. FD->setInvalidDecl();
  3111. FD->removeInClassInitializer();
  3112. return;
  3113. }
  3114. ExprResult Init = InitExpr;
  3115. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3116. InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
  3117. InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
  3118. ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
  3119. : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
  3120. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3121. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3122. if (Init.isInvalid()) {
  3123. FD->setInvalidDecl();
  3124. return;
  3125. }
  3126. }
  3127. // C++11 [class.base.init]p7:
  3128. // The initialization of each base and member constitutes a
  3129. // full-expression.
  3130. Init = ActOnFinishFullExpr(Init.get(), InitLoc);
  3131. if (Init.isInvalid()) {
  3132. FD->setInvalidDecl();
  3133. return;
  3134. }
  3135. InitExpr = Init.get();
  3136. FD->setInClassInitializer(InitExpr);
  3137. }
  3138. /// \brief Find the direct and/or virtual base specifiers that
  3139. /// correspond to the given base type, for use in base initialization
  3140. /// within a constructor.
  3141. static bool FindBaseInitializer(Sema &SemaRef,
  3142. CXXRecordDecl *ClassDecl,
  3143. QualType BaseType,
  3144. const CXXBaseSpecifier *&DirectBaseSpec,
  3145. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3146. // First, check for a direct base class.
  3147. DirectBaseSpec = nullptr;
  3148. for (const auto &Base : ClassDecl->bases()) {
  3149. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3150. // We found a direct base of this type. That's what we're
  3151. // initializing.
  3152. DirectBaseSpec = &Base;
  3153. break;
  3154. }
  3155. }
  3156. // Check for a virtual base class.
  3157. // FIXME: We might be able to short-circuit this if we know in advance that
  3158. // there are no virtual bases.
  3159. VirtualBaseSpec = nullptr;
  3160. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3161. // We haven't found a base yet; search the class hierarchy for a
  3162. // virtual base class.
  3163. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3164. /*DetectVirtual=*/false);
  3165. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3166. SemaRef.Context.getTypeDeclType(ClassDecl),
  3167. BaseType, Paths)) {
  3168. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3169. Path != Paths.end(); ++Path) {
  3170. if (Path->back().Base->isVirtual()) {
  3171. VirtualBaseSpec = Path->back().Base;
  3172. break;
  3173. }
  3174. }
  3175. }
  3176. }
  3177. return DirectBaseSpec || VirtualBaseSpec;
  3178. }
  3179. /// \brief Handle a C++ member initializer using braced-init-list syntax.
  3180. MemInitResult
  3181. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3182. Scope *S,
  3183. CXXScopeSpec &SS,
  3184. IdentifierInfo *MemberOrBase,
  3185. ParsedType TemplateTypeTy,
  3186. const DeclSpec &DS,
  3187. SourceLocation IdLoc,
  3188. Expr *InitList,
  3189. SourceLocation EllipsisLoc) {
  3190. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3191. DS, IdLoc, InitList,
  3192. EllipsisLoc);
  3193. }
  3194. /// \brief Handle a C++ member initializer using parentheses syntax.
  3195. MemInitResult
  3196. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3197. Scope *S,
  3198. CXXScopeSpec &SS,
  3199. IdentifierInfo *MemberOrBase,
  3200. ParsedType TemplateTypeTy,
  3201. const DeclSpec &DS,
  3202. SourceLocation IdLoc,
  3203. SourceLocation LParenLoc,
  3204. ArrayRef<Expr *> Args,
  3205. SourceLocation RParenLoc,
  3206. SourceLocation EllipsisLoc) {
  3207. Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
  3208. Args, RParenLoc);
  3209. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3210. DS, IdLoc, List, EllipsisLoc);
  3211. }
  3212. namespace {
  3213. // Callback to only accept typo corrections that can be a valid C++ member
  3214. // intializer: either a non-static field member or a base class.
  3215. class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
  3216. public:
  3217. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3218. : ClassDecl(ClassDecl) {}
  3219. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3220. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3221. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3222. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3223. return isa<TypeDecl>(ND);
  3224. }
  3225. return false;
  3226. }
  3227. private:
  3228. CXXRecordDecl *ClassDecl;
  3229. };
  3230. }
  3231. /// \brief Handle a C++ member initializer.
  3232. MemInitResult
  3233. Sema::BuildMemInitializer(Decl *ConstructorD,
  3234. Scope *S,
  3235. CXXScopeSpec &SS,
  3236. IdentifierInfo *MemberOrBase,
  3237. ParsedType TemplateTypeTy,
  3238. const DeclSpec &DS,
  3239. SourceLocation IdLoc,
  3240. Expr *Init,
  3241. SourceLocation EllipsisLoc) {
  3242. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  3243. if (!Res.isUsable())
  3244. return true;
  3245. Init = Res.get();
  3246. if (!ConstructorD)
  3247. return true;
  3248. AdjustDeclIfTemplate(ConstructorD);
  3249. CXXConstructorDecl *Constructor
  3250. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3251. if (!Constructor) {
  3252. // The user wrote a constructor initializer on a function that is
  3253. // not a C++ constructor. Ignore the error for now, because we may
  3254. // have more member initializers coming; we'll diagnose it just
  3255. // once in ActOnMemInitializers.
  3256. return true;
  3257. }
  3258. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3259. // C++ [class.base.init]p2:
  3260. // Names in a mem-initializer-id are looked up in the scope of the
  3261. // constructor's class and, if not found in that scope, are looked
  3262. // up in the scope containing the constructor's definition.
  3263. // [Note: if the constructor's class contains a member with the
  3264. // same name as a direct or virtual base class of the class, a
  3265. // mem-initializer-id naming the member or base class and composed
  3266. // of a single identifier refers to the class member. A
  3267. // mem-initializer-id for the hidden base class may be specified
  3268. // using a qualified name. ]
  3269. if (!SS.getScopeRep() && !TemplateTypeTy) {
  3270. // Look for a member, first.
  3271. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  3272. if (!Result.empty()) {
  3273. ValueDecl *Member;
  3274. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  3275. (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
  3276. if (EllipsisLoc.isValid())
  3277. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3278. << MemberOrBase
  3279. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3280. return BuildMemberInitializer(Member, Init, IdLoc);
  3281. }
  3282. }
  3283. }
  3284. // It didn't name a member, so see if it names a class.
  3285. QualType BaseType;
  3286. TypeSourceInfo *TInfo = nullptr;
  3287. if (TemplateTypeTy) {
  3288. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3289. } else if (DS.getTypeSpecType() == TST_decltype) {
  3290. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  3291. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3292. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3293. return true;
  3294. } else {
  3295. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3296. LookupParsedName(R, S, &SS);
  3297. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3298. if (!TyD) {
  3299. if (R.isAmbiguous()) return true;
  3300. // We don't want access-control diagnostics here.
  3301. R.suppressDiagnostics();
  3302. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3303. bool NotUnknownSpecialization = false;
  3304. DeclContext *DC = computeDeclContext(SS, false);
  3305. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3306. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3307. if (!NotUnknownSpecialization) {
  3308. // When the scope specifier can refer to a member of an unknown
  3309. // specialization, we take it as a type name.
  3310. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3311. SS.getWithLocInContext(Context),
  3312. *MemberOrBase, IdLoc);
  3313. if (BaseType.isNull())
  3314. return true;
  3315. R.clear();
  3316. R.setLookupName(MemberOrBase);
  3317. }
  3318. }
  3319. // If no results were found, try to correct typos.
  3320. TypoCorrection Corr;
  3321. if (R.empty() && BaseType.isNull() &&
  3322. (Corr = CorrectTypo(
  3323. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3324. llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
  3325. CTK_ErrorRecovery, ClassDecl))) {
  3326. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3327. // We have found a non-static data member with a similar
  3328. // name to what was typed; complain and initialize that
  3329. // member.
  3330. diagnoseTypo(Corr,
  3331. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3332. << MemberOrBase << true);
  3333. return BuildMemberInitializer(Member, Init, IdLoc);
  3334. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3335. const CXXBaseSpecifier *DirectBaseSpec;
  3336. const CXXBaseSpecifier *VirtualBaseSpec;
  3337. if (FindBaseInitializer(*this, ClassDecl,
  3338. Context.getTypeDeclType(Type),
  3339. DirectBaseSpec, VirtualBaseSpec)) {
  3340. // We have found a direct or virtual base class with a
  3341. // similar name to what was typed; complain and initialize
  3342. // that base class.
  3343. diagnoseTypo(Corr,
  3344. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3345. << MemberOrBase << false,
  3346. PDiag() /*Suppress note, we provide our own.*/);
  3347. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3348. : VirtualBaseSpec;
  3349. Diag(BaseSpec->getLocStart(),
  3350. diag::note_base_class_specified_here)
  3351. << BaseSpec->getType()
  3352. << BaseSpec->getSourceRange();
  3353. TyD = Type;
  3354. }
  3355. }
  3356. }
  3357. if (!TyD && BaseType.isNull()) {
  3358. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3359. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3360. return true;
  3361. }
  3362. }
  3363. if (BaseType.isNull()) {
  3364. BaseType = Context.getTypeDeclType(TyD);
  3365. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3366. if (SS.isSet()) {
  3367. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3368. BaseType);
  3369. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3370. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3371. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3372. TL.setElaboratedKeywordLoc(SourceLocation());
  3373. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3374. }
  3375. }
  3376. }
  3377. if (!TInfo)
  3378. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3379. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3380. }
  3381. /// Checks a member initializer expression for cases where reference (or
  3382. /// pointer) members are bound to by-value parameters (or their addresses).
  3383. static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
  3384. Expr *Init,
  3385. SourceLocation IdLoc) {
  3386. QualType MemberTy = Member->getType();
  3387. // We only handle pointers and references currently.
  3388. // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
  3389. if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
  3390. return;
  3391. const bool IsPointer = MemberTy->isPointerType();
  3392. if (IsPointer) {
  3393. if (const UnaryOperator *Op
  3394. = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
  3395. // The only case we're worried about with pointers requires taking the
  3396. // address.
  3397. if (Op->getOpcode() != UO_AddrOf)
  3398. return;
  3399. Init = Op->getSubExpr();
  3400. } else {
  3401. // We only handle address-of expression initializers for pointers.
  3402. return;
  3403. }
  3404. }
  3405. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
  3406. // We only warn when referring to a non-reference parameter declaration.
  3407. const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
  3408. if (!Parameter || Parameter->getType()->isReferenceType())
  3409. return;
  3410. S.Diag(Init->getExprLoc(),
  3411. IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  3412. : diag::warn_bind_ref_member_to_parameter)
  3413. << Member << Parameter << Init->getSourceRange();
  3414. } else {
  3415. // Other initializers are fine.
  3416. return;
  3417. }
  3418. S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
  3419. << (unsigned)IsPointer;
  3420. }
  3421. MemInitResult
  3422. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3423. SourceLocation IdLoc) {
  3424. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3425. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3426. assert((DirectMember || IndirectMember) &&
  3427. "Member must be a FieldDecl or IndirectFieldDecl");
  3428. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3429. return true;
  3430. if (Member->isInvalidDecl())
  3431. return true;
  3432. MultiExprArg Args;
  3433. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3434. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3435. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3436. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3437. } else {
  3438. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3439. Args = Init;
  3440. }
  3441. SourceRange InitRange = Init->getSourceRange();
  3442. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3443. // Can't check initialization for a member of dependent type or when
  3444. // any of the arguments are type-dependent expressions.
  3445. DiscardCleanupsInEvaluationContext();
  3446. } else {
  3447. bool InitList = false;
  3448. if (isa<InitListExpr>(Init)) {
  3449. InitList = true;
  3450. Args = Init;
  3451. }
  3452. // Initialize the member.
  3453. InitializedEntity MemberEntity =
  3454. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3455. : InitializedEntity::InitializeMember(IndirectMember,
  3456. nullptr);
  3457. InitializationKind Kind =
  3458. InitList ? InitializationKind::CreateDirectList(IdLoc)
  3459. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3460. InitRange.getEnd());
  3461. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3462. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3463. nullptr);
  3464. if (MemberInit.isInvalid())
  3465. return true;
  3466. CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
  3467. // C++11 [class.base.init]p7:
  3468. // The initialization of each base and member constitutes a
  3469. // full-expression.
  3470. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
  3471. if (MemberInit.isInvalid())
  3472. return true;
  3473. Init = MemberInit.get();
  3474. }
  3475. if (DirectMember) {
  3476. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3477. InitRange.getBegin(), Init,
  3478. InitRange.getEnd());
  3479. } else {
  3480. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3481. InitRange.getBegin(), Init,
  3482. InitRange.getEnd());
  3483. }
  3484. }
  3485. MemInitResult
  3486. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3487. CXXRecordDecl *ClassDecl) {
  3488. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3489. if (!LangOpts.CPlusPlus11)
  3490. return Diag(NameLoc, diag::err_delegating_ctor)
  3491. << TInfo->getTypeLoc().getLocalSourceRange();
  3492. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3493. bool InitList = true;
  3494. MultiExprArg Args = Init;
  3495. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3496. InitList = false;
  3497. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3498. }
  3499. SourceRange InitRange = Init->getSourceRange();
  3500. // Initialize the object.
  3501. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3502. QualType(ClassDecl->getTypeForDecl(), 0));
  3503. InitializationKind Kind =
  3504. InitList ? InitializationKind::CreateDirectList(NameLoc)
  3505. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3506. InitRange.getEnd());
  3507. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3508. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3509. Args, nullptr);
  3510. if (DelegationInit.isInvalid())
  3511. return true;
  3512. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  3513. "Delegating constructor with no target?");
  3514. // C++11 [class.base.init]p7:
  3515. // The initialization of each base and member constitutes a
  3516. // full-expression.
  3517. DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
  3518. InitRange.getBegin());
  3519. if (DelegationInit.isInvalid())
  3520. return true;
  3521. // If we are in a dependent context, template instantiation will
  3522. // perform this type-checking again. Just save the arguments that we
  3523. // received in a ParenListExpr.
  3524. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3525. // of the information that we have about the base
  3526. // initializer. However, deconstructing the ASTs is a dicey process,
  3527. // and this approach is far more likely to get the corner cases right.
  3528. if (CurContext->isDependentContext())
  3529. DelegationInit = Init;
  3530. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3531. DelegationInit.getAs<Expr>(),
  3532. InitRange.getEnd());
  3533. }
  3534. MemInitResult
  3535. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3536. Expr *Init, CXXRecordDecl *ClassDecl,
  3537. SourceLocation EllipsisLoc) {
  3538. SourceLocation BaseLoc
  3539. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3540. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3541. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3542. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3543. // C++ [class.base.init]p2:
  3544. // [...] Unless the mem-initializer-id names a nonstatic data
  3545. // member of the constructor's class or a direct or virtual base
  3546. // of that class, the mem-initializer is ill-formed. A
  3547. // mem-initializer-list can initialize a base class using any
  3548. // name that denotes that base class type.
  3549. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  3550. SourceRange InitRange = Init->getSourceRange();
  3551. if (EllipsisLoc.isValid()) {
  3552. // This is a pack expansion.
  3553. if (!BaseType->containsUnexpandedParameterPack()) {
  3554. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3555. << SourceRange(BaseLoc, InitRange.getEnd());
  3556. EllipsisLoc = SourceLocation();
  3557. }
  3558. } else {
  3559. // Check for any unexpanded parameter packs.
  3560. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3561. return true;
  3562. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3563. return true;
  3564. }
  3565. // Check for direct and virtual base classes.
  3566. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3567. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3568. if (!Dependent) {
  3569. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3570. BaseType))
  3571. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  3572. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  3573. VirtualBaseSpec);
  3574. // C++ [base.class.init]p2:
  3575. // Unless the mem-initializer-id names a nonstatic data member of the
  3576. // constructor's class or a direct or virtual base of that class, the
  3577. // mem-initializer is ill-formed.
  3578. if (!DirectBaseSpec && !VirtualBaseSpec) {
  3579. // If the class has any dependent bases, then it's possible that
  3580. // one of those types will resolve to the same type as
  3581. // BaseType. Therefore, just treat this as a dependent base
  3582. // class initialization. FIXME: Should we try to check the
  3583. // initialization anyway? It seems odd.
  3584. if (ClassDecl->hasAnyDependentBases())
  3585. Dependent = true;
  3586. else
  3587. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  3588. << BaseType << Context.getTypeDeclType(ClassDecl)
  3589. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3590. }
  3591. }
  3592. if (Dependent) {
  3593. DiscardCleanupsInEvaluationContext();
  3594. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3595. /*IsVirtual=*/false,
  3596. InitRange.getBegin(), Init,
  3597. InitRange.getEnd(), EllipsisLoc);
  3598. }
  3599. // C++ [base.class.init]p2:
  3600. // If a mem-initializer-id is ambiguous because it designates both
  3601. // a direct non-virtual base class and an inherited virtual base
  3602. // class, the mem-initializer is ill-formed.
  3603. if (DirectBaseSpec && VirtualBaseSpec)
  3604. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  3605. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3606. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  3607. if (!BaseSpec)
  3608. BaseSpec = VirtualBaseSpec;
  3609. // Initialize the base.
  3610. bool InitList = true;
  3611. MultiExprArg Args = Init;
  3612. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3613. InitList = false;
  3614. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3615. }
  3616. InitializedEntity BaseEntity =
  3617. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  3618. InitializationKind Kind =
  3619. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  3620. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  3621. InitRange.getEnd());
  3622. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  3623. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  3624. if (BaseInit.isInvalid())
  3625. return true;
  3626. // C++11 [class.base.init]p7:
  3627. // The initialization of each base and member constitutes a
  3628. // full-expression.
  3629. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
  3630. if (BaseInit.isInvalid())
  3631. return true;
  3632. // If we are in a dependent context, template instantiation will
  3633. // perform this type-checking again. Just save the arguments that we
  3634. // received in a ParenListExpr.
  3635. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3636. // of the information that we have about the base
  3637. // initializer. However, deconstructing the ASTs is a dicey process,
  3638. // and this approach is far more likely to get the corner cases right.
  3639. if (CurContext->isDependentContext())
  3640. BaseInit = Init;
  3641. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  3642. BaseSpec->isVirtual(),
  3643. InitRange.getBegin(),
  3644. BaseInit.getAs<Expr>(),
  3645. InitRange.getEnd(), EllipsisLoc);
  3646. }
  3647. // Create a static_cast\<T&&>(expr).
  3648. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  3649. if (T.isNull()) T = E->getType();
  3650. QualType TargetType = SemaRef.BuildReferenceType(
  3651. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  3652. SourceLocation ExprLoc = E->getLocStart();
  3653. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  3654. TargetType, ExprLoc);
  3655. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  3656. SourceRange(ExprLoc, ExprLoc),
  3657. E->getSourceRange()).get();
  3658. }
  3659. /// ImplicitInitializerKind - How an implicit base or member initializer should
  3660. /// initialize its base or member.
  3661. enum ImplicitInitializerKind {
  3662. IIK_Default,
  3663. IIK_Copy,
  3664. IIK_Move,
  3665. IIK_Inherit
  3666. };
  3667. static bool
  3668. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3669. ImplicitInitializerKind ImplicitInitKind,
  3670. CXXBaseSpecifier *BaseSpec,
  3671. bool IsInheritedVirtualBase,
  3672. CXXCtorInitializer *&CXXBaseInit) {
  3673. InitializedEntity InitEntity
  3674. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  3675. IsInheritedVirtualBase);
  3676. ExprResult BaseInit;
  3677. switch (ImplicitInitKind) {
  3678. case IIK_Inherit:
  3679. case IIK_Default: {
  3680. InitializationKind InitKind
  3681. = InitializationKind::CreateDefault(Constructor->getLocation());
  3682. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3683. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3684. break;
  3685. }
  3686. case IIK_Move:
  3687. case IIK_Copy: {
  3688. bool Moving = ImplicitInitKind == IIK_Move;
  3689. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3690. QualType ParamType = Param->getType().getNonReferenceType();
  3691. Expr *CopyCtorArg =
  3692. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3693. SourceLocation(), Param, false,
  3694. Constructor->getLocation(), ParamType,
  3695. VK_LValue, nullptr);
  3696. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3697. // Cast to the base class to avoid ambiguities.
  3698. QualType ArgTy =
  3699. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3700. ParamType.getQualifiers());
  3701. if (Moving) {
  3702. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3703. }
  3704. CXXCastPath BasePath;
  3705. BasePath.push_back(BaseSpec);
  3706. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3707. CK_UncheckedDerivedToBase,
  3708. Moving ? VK_XValue : VK_LValue,
  3709. &BasePath).get();
  3710. InitializationKind InitKind
  3711. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3712. SourceLocation(), SourceLocation());
  3713. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3714. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3715. break;
  3716. }
  3717. }
  3718. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3719. if (BaseInit.isInvalid())
  3720. return true;
  3721. CXXBaseInit =
  3722. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3723. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3724. SourceLocation()),
  3725. BaseSpec->isVirtual(),
  3726. SourceLocation(),
  3727. BaseInit.getAs<Expr>(),
  3728. SourceLocation(),
  3729. SourceLocation());
  3730. return false;
  3731. }
  3732. static bool RefersToRValueRef(Expr *MemRef) {
  3733. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3734. return Referenced->getType()->isRValueReferenceType();
  3735. }
  3736. static bool
  3737. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3738. ImplicitInitializerKind ImplicitInitKind,
  3739. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3740. CXXCtorInitializer *&CXXMemberInit) {
  3741. if (Field->isInvalidDecl())
  3742. return true;
  3743. SourceLocation Loc = Constructor->getLocation();
  3744. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3745. bool Moving = ImplicitInitKind == IIK_Move;
  3746. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3747. QualType ParamType = Param->getType().getNonReferenceType();
  3748. // Suppress copying zero-width bitfields.
  3749. if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
  3750. return false;
  3751. Expr *MemberExprBase =
  3752. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3753. SourceLocation(), Param, false,
  3754. Loc, ParamType, VK_LValue, nullptr);
  3755. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  3756. if (Moving) {
  3757. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  3758. }
  3759. // Build a reference to this field within the parameter.
  3760. CXXScopeSpec SS;
  3761. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  3762. Sema::LookupMemberName);
  3763. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  3764. : cast<ValueDecl>(Field), AS_public);
  3765. MemberLookup.resolveKind();
  3766. ExprResult CtorArg
  3767. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  3768. ParamType, Loc,
  3769. /*IsArrow=*/false,
  3770. SS,
  3771. /*TemplateKWLoc=*/SourceLocation(),
  3772. /*FirstQualifierInScope=*/nullptr,
  3773. MemberLookup,
  3774. /*TemplateArgs=*/nullptr,
  3775. /*S*/nullptr);
  3776. if (CtorArg.isInvalid())
  3777. return true;
  3778. // C++11 [class.copy]p15:
  3779. // - if a member m has rvalue reference type T&&, it is direct-initialized
  3780. // with static_cast<T&&>(x.m);
  3781. if (RefersToRValueRef(CtorArg.get())) {
  3782. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3783. }
  3784. InitializedEntity Entity =
  3785. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3786. /*Implicit*/ true)
  3787. : InitializedEntity::InitializeMember(Field, nullptr,
  3788. /*Implicit*/ true);
  3789. // Direct-initialize to use the copy constructor.
  3790. InitializationKind InitKind =
  3791. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  3792. Expr *CtorArgE = CtorArg.getAs<Expr>();
  3793. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  3794. ExprResult MemberInit =
  3795. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  3796. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3797. if (MemberInit.isInvalid())
  3798. return true;
  3799. if (Indirect)
  3800. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3801. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3802. else
  3803. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  3804. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  3805. return false;
  3806. }
  3807. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  3808. "Unhandled implicit init kind!");
  3809. QualType FieldBaseElementType =
  3810. SemaRef.Context.getBaseElementType(Field->getType());
  3811. if (FieldBaseElementType->isRecordType()) {
  3812. InitializedEntity InitEntity =
  3813. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  3814. /*Implicit*/ true)
  3815. : InitializedEntity::InitializeMember(Field, nullptr,
  3816. /*Implicit*/ true);
  3817. InitializationKind InitKind =
  3818. InitializationKind::CreateDefault(Loc);
  3819. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3820. ExprResult MemberInit =
  3821. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3822. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3823. if (MemberInit.isInvalid())
  3824. return true;
  3825. if (Indirect)
  3826. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3827. Indirect, Loc,
  3828. Loc,
  3829. MemberInit.get(),
  3830. Loc);
  3831. else
  3832. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3833. Field, Loc, Loc,
  3834. MemberInit.get(),
  3835. Loc);
  3836. return false;
  3837. }
  3838. if (!Field->getParent()->isUnion()) {
  3839. if (FieldBaseElementType->isReferenceType()) {
  3840. SemaRef.Diag(Constructor->getLocation(),
  3841. diag::err_uninitialized_member_in_ctor)
  3842. << (int)Constructor->isImplicit()
  3843. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3844. << 0 << Field->getDeclName();
  3845. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3846. return true;
  3847. }
  3848. if (FieldBaseElementType.isConstQualified()) {
  3849. SemaRef.Diag(Constructor->getLocation(),
  3850. diag::err_uninitialized_member_in_ctor)
  3851. << (int)Constructor->isImplicit()
  3852. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3853. << 1 << Field->getDeclName();
  3854. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3855. return true;
  3856. }
  3857. }
  3858. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  3859. FieldBaseElementType->isObjCRetainableType() &&
  3860. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
  3861. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
  3862. // ARC:
  3863. // Default-initialize Objective-C pointers to NULL.
  3864. CXXMemberInit
  3865. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  3866. Loc, Loc,
  3867. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  3868. Loc);
  3869. return false;
  3870. }
  3871. // Nothing to initialize.
  3872. CXXMemberInit = nullptr;
  3873. return false;
  3874. }
  3875. namespace {
  3876. struct BaseAndFieldInfo {
  3877. Sema &S;
  3878. CXXConstructorDecl *Ctor;
  3879. bool AnyErrorsInInits;
  3880. ImplicitInitializerKind IIK;
  3881. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  3882. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  3883. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  3884. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  3885. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  3886. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  3887. if (Ctor->getInheritedConstructor())
  3888. IIK = IIK_Inherit;
  3889. else if (Generated && Ctor->isCopyConstructor())
  3890. IIK = IIK_Copy;
  3891. else if (Generated && Ctor->isMoveConstructor())
  3892. IIK = IIK_Move;
  3893. else
  3894. IIK = IIK_Default;
  3895. }
  3896. bool isImplicitCopyOrMove() const {
  3897. switch (IIK) {
  3898. case IIK_Copy:
  3899. case IIK_Move:
  3900. return true;
  3901. case IIK_Default:
  3902. case IIK_Inherit:
  3903. return false;
  3904. }
  3905. llvm_unreachable("Invalid ImplicitInitializerKind!");
  3906. }
  3907. bool addFieldInitializer(CXXCtorInitializer *Init) {
  3908. AllToInit.push_back(Init);
  3909. // Check whether this initializer makes the field "used".
  3910. if (Init->getInit()->HasSideEffects(S.Context))
  3911. S.UnusedPrivateFields.remove(Init->getAnyMember());
  3912. return false;
  3913. }
  3914. bool isInactiveUnionMember(FieldDecl *Field) {
  3915. RecordDecl *Record = Field->getParent();
  3916. if (!Record->isUnion())
  3917. return false;
  3918. if (FieldDecl *Active =
  3919. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  3920. return Active != Field->getCanonicalDecl();
  3921. // In an implicit copy or move constructor, ignore any in-class initializer.
  3922. if (isImplicitCopyOrMove())
  3923. return true;
  3924. // If there's no explicit initialization, the field is active only if it
  3925. // has an in-class initializer...
  3926. if (Field->hasInClassInitializer())
  3927. return false;
  3928. // ... or it's an anonymous struct or union whose class has an in-class
  3929. // initializer.
  3930. if (!Field->isAnonymousStructOrUnion())
  3931. return true;
  3932. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  3933. return !FieldRD->hasInClassInitializer();
  3934. }
  3935. /// \brief Determine whether the given field is, or is within, a union member
  3936. /// that is inactive (because there was an initializer given for a different
  3937. /// member of the union, or because the union was not initialized at all).
  3938. bool isWithinInactiveUnionMember(FieldDecl *Field,
  3939. IndirectFieldDecl *Indirect) {
  3940. if (!Indirect)
  3941. return isInactiveUnionMember(Field);
  3942. for (auto *C : Indirect->chain()) {
  3943. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  3944. if (Field && isInactiveUnionMember(Field))
  3945. return true;
  3946. }
  3947. return false;
  3948. }
  3949. };
  3950. }
  3951. /// \brief Determine whether the given type is an incomplete or zero-lenfgth
  3952. /// array type.
  3953. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  3954. if (T->isIncompleteArrayType())
  3955. return true;
  3956. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  3957. if (!ArrayT->getSize())
  3958. return true;
  3959. T = ArrayT->getElementType();
  3960. }
  3961. return false;
  3962. }
  3963. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  3964. FieldDecl *Field,
  3965. IndirectFieldDecl *Indirect = nullptr) {
  3966. if (Field->isInvalidDecl())
  3967. return false;
  3968. // Overwhelmingly common case: we have a direct initializer for this field.
  3969. if (CXXCtorInitializer *Init =
  3970. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  3971. return Info.addFieldInitializer(Init);
  3972. // C++11 [class.base.init]p8:
  3973. // if the entity is a non-static data member that has a
  3974. // brace-or-equal-initializer and either
  3975. // -- the constructor's class is a union and no other variant member of that
  3976. // union is designated by a mem-initializer-id or
  3977. // -- the constructor's class is not a union, and, if the entity is a member
  3978. // of an anonymous union, no other member of that union is designated by
  3979. // a mem-initializer-id,
  3980. // the entity is initialized as specified in [dcl.init].
  3981. //
  3982. // We also apply the same rules to handle anonymous structs within anonymous
  3983. // unions.
  3984. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  3985. return false;
  3986. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  3987. ExprResult DIE =
  3988. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  3989. if (DIE.isInvalid())
  3990. return true;
  3991. CXXCtorInitializer *Init;
  3992. if (Indirect)
  3993. Init = new (SemaRef.Context)
  3994. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  3995. SourceLocation(), DIE.get(), SourceLocation());
  3996. else
  3997. Init = new (SemaRef.Context)
  3998. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  3999. SourceLocation(), DIE.get(), SourceLocation());
  4000. return Info.addFieldInitializer(Init);
  4001. }
  4002. // Don't initialize incomplete or zero-length arrays.
  4003. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4004. return false;
  4005. // Don't try to build an implicit initializer if there were semantic
  4006. // errors in any of the initializers (and therefore we might be
  4007. // missing some that the user actually wrote).
  4008. if (Info.AnyErrorsInInits)
  4009. return false;
  4010. CXXCtorInitializer *Init = nullptr;
  4011. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4012. Indirect, Init))
  4013. return true;
  4014. if (!Init)
  4015. return false;
  4016. return Info.addFieldInitializer(Init);
  4017. }
  4018. bool
  4019. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4020. CXXCtorInitializer *Initializer) {
  4021. assert(Initializer->isDelegatingInitializer());
  4022. Constructor->setNumCtorInitializers(1);
  4023. CXXCtorInitializer **initializer =
  4024. new (Context) CXXCtorInitializer*[1];
  4025. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4026. Constructor->setCtorInitializers(initializer);
  4027. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4028. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4029. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4030. }
  4031. DelegatingCtorDecls.push_back(Constructor);
  4032. DiagnoseUninitializedFields(*this, Constructor);
  4033. return false;
  4034. }
  4035. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4036. ArrayRef<CXXCtorInitializer *> Initializers) {
  4037. if (Constructor->isDependentContext()) {
  4038. // Just store the initializers as written, they will be checked during
  4039. // instantiation.
  4040. if (!Initializers.empty()) {
  4041. Constructor->setNumCtorInitializers(Initializers.size());
  4042. CXXCtorInitializer **baseOrMemberInitializers =
  4043. new (Context) CXXCtorInitializer*[Initializers.size()];
  4044. memcpy(baseOrMemberInitializers, Initializers.data(),
  4045. Initializers.size() * sizeof(CXXCtorInitializer*));
  4046. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4047. }
  4048. // Let template instantiation know whether we had errors.
  4049. if (AnyErrors)
  4050. Constructor->setInvalidDecl();
  4051. return false;
  4052. }
  4053. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4054. // We need to build the initializer AST according to order of construction
  4055. // and not what user specified in the Initializers list.
  4056. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4057. if (!ClassDecl)
  4058. return true;
  4059. bool HadError = false;
  4060. for (unsigned i = 0; i < Initializers.size(); i++) {
  4061. CXXCtorInitializer *Member = Initializers[i];
  4062. if (Member->isBaseInitializer())
  4063. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4064. else {
  4065. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4066. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4067. for (auto *C : F->chain()) {
  4068. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4069. if (FD && FD->getParent()->isUnion())
  4070. Info.ActiveUnionMember.insert(std::make_pair(
  4071. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4072. }
  4073. } else if (FieldDecl *FD = Member->getMember()) {
  4074. if (FD->getParent()->isUnion())
  4075. Info.ActiveUnionMember.insert(std::make_pair(
  4076. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4077. }
  4078. }
  4079. }
  4080. // Keep track of the direct virtual bases.
  4081. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4082. for (auto &I : ClassDecl->bases()) {
  4083. if (I.isVirtual())
  4084. DirectVBases.insert(&I);
  4085. }
  4086. // Push virtual bases before others.
  4087. for (auto &VBase : ClassDecl->vbases()) {
  4088. if (CXXCtorInitializer *Value
  4089. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4090. // [class.base.init]p7, per DR257:
  4091. // A mem-initializer where the mem-initializer-id names a virtual base
  4092. // class is ignored during execution of a constructor of any class that
  4093. // is not the most derived class.
  4094. if (ClassDecl->isAbstract()) {
  4095. // FIXME: Provide a fixit to remove the base specifier. This requires
  4096. // tracking the location of the associated comma for a base specifier.
  4097. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4098. << VBase.getType() << ClassDecl;
  4099. DiagnoseAbstractType(ClassDecl);
  4100. }
  4101. Info.AllToInit.push_back(Value);
  4102. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4103. // [class.base.init]p8, per DR257:
  4104. // If a given [...] base class is not named by a mem-initializer-id
  4105. // [...] and the entity is not a virtual base class of an abstract
  4106. // class, then [...] the entity is default-initialized.
  4107. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4108. CXXCtorInitializer *CXXBaseInit;
  4109. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4110. &VBase, IsInheritedVirtualBase,
  4111. CXXBaseInit)) {
  4112. HadError = true;
  4113. continue;
  4114. }
  4115. Info.AllToInit.push_back(CXXBaseInit);
  4116. }
  4117. }
  4118. // Non-virtual bases.
  4119. for (auto &Base : ClassDecl->bases()) {
  4120. // Virtuals are in the virtual base list and already constructed.
  4121. if (Base.isVirtual())
  4122. continue;
  4123. if (CXXCtorInitializer *Value
  4124. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4125. Info.AllToInit.push_back(Value);
  4126. } else if (!AnyErrors) {
  4127. CXXCtorInitializer *CXXBaseInit;
  4128. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4129. &Base, /*IsInheritedVirtualBase=*/false,
  4130. CXXBaseInit)) {
  4131. HadError = true;
  4132. continue;
  4133. }
  4134. Info.AllToInit.push_back(CXXBaseInit);
  4135. }
  4136. }
  4137. // Fields.
  4138. for (auto *Mem : ClassDecl->decls()) {
  4139. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4140. // C++ [class.bit]p2:
  4141. // A declaration for a bit-field that omits the identifier declares an
  4142. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4143. // initialized.
  4144. if (F->isUnnamedBitfield())
  4145. continue;
  4146. // If we're not generating the implicit copy/move constructor, then we'll
  4147. // handle anonymous struct/union fields based on their individual
  4148. // indirect fields.
  4149. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4150. continue;
  4151. if (CollectFieldInitializer(*this, Info, F))
  4152. HadError = true;
  4153. continue;
  4154. }
  4155. // Beyond this point, we only consider default initialization.
  4156. if (Info.isImplicitCopyOrMove())
  4157. continue;
  4158. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4159. if (F->getType()->isIncompleteArrayType()) {
  4160. assert(ClassDecl->hasFlexibleArrayMember() &&
  4161. "Incomplete array type is not valid");
  4162. continue;
  4163. }
  4164. // Initialize each field of an anonymous struct individually.
  4165. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4166. HadError = true;
  4167. continue;
  4168. }
  4169. }
  4170. unsigned NumInitializers = Info.AllToInit.size();
  4171. if (NumInitializers > 0) {
  4172. Constructor->setNumCtorInitializers(NumInitializers);
  4173. CXXCtorInitializer **baseOrMemberInitializers =
  4174. new (Context) CXXCtorInitializer*[NumInitializers];
  4175. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4176. NumInitializers * sizeof(CXXCtorInitializer*));
  4177. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4178. // Constructors implicitly reference the base and member
  4179. // destructors.
  4180. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4181. Constructor->getParent());
  4182. }
  4183. return HadError;
  4184. }
  4185. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4186. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4187. const RecordDecl *RD = RT->getDecl();
  4188. if (RD->isAnonymousStructOrUnion()) {
  4189. for (auto *Field : RD->fields())
  4190. PopulateKeysForFields(Field, IdealInits);
  4191. return;
  4192. }
  4193. }
  4194. IdealInits.push_back(Field->getCanonicalDecl());
  4195. }
  4196. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4197. return Context.getCanonicalType(BaseType).getTypePtr();
  4198. }
  4199. static const void *GetKeyForMember(ASTContext &Context,
  4200. CXXCtorInitializer *Member) {
  4201. if (!Member->isAnyMemberInitializer())
  4202. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4203. return Member->getAnyMember()->getCanonicalDecl();
  4204. }
  4205. static void DiagnoseBaseOrMemInitializerOrder(
  4206. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4207. ArrayRef<CXXCtorInitializer *> Inits) {
  4208. if (Constructor->getDeclContext()->isDependentContext())
  4209. return;
  4210. // Don't check initializers order unless the warning is enabled at the
  4211. // location of at least one initializer.
  4212. bool ShouldCheckOrder = false;
  4213. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4214. CXXCtorInitializer *Init = Inits[InitIndex];
  4215. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4216. Init->getSourceLocation())) {
  4217. ShouldCheckOrder = true;
  4218. break;
  4219. }
  4220. }
  4221. if (!ShouldCheckOrder)
  4222. return;
  4223. // Build the list of bases and members in the order that they'll
  4224. // actually be initialized. The explicit initializers should be in
  4225. // this same order but may be missing things.
  4226. SmallVector<const void*, 32> IdealInitKeys;
  4227. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4228. // 1. Virtual bases.
  4229. for (const auto &VBase : ClassDecl->vbases())
  4230. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4231. // 2. Non-virtual bases.
  4232. for (const auto &Base : ClassDecl->bases()) {
  4233. if (Base.isVirtual())
  4234. continue;
  4235. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4236. }
  4237. // 3. Direct fields.
  4238. for (auto *Field : ClassDecl->fields()) {
  4239. if (Field->isUnnamedBitfield())
  4240. continue;
  4241. PopulateKeysForFields(Field, IdealInitKeys);
  4242. }
  4243. unsigned NumIdealInits = IdealInitKeys.size();
  4244. unsigned IdealIndex = 0;
  4245. CXXCtorInitializer *PrevInit = nullptr;
  4246. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4247. CXXCtorInitializer *Init = Inits[InitIndex];
  4248. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  4249. // Scan forward to try to find this initializer in the idealized
  4250. // initializers list.
  4251. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4252. if (InitKey == IdealInitKeys[IdealIndex])
  4253. break;
  4254. // If we didn't find this initializer, it must be because we
  4255. // scanned past it on a previous iteration. That can only
  4256. // happen if we're out of order; emit a warning.
  4257. if (IdealIndex == NumIdealInits && PrevInit) {
  4258. Sema::SemaDiagnosticBuilder D =
  4259. SemaRef.Diag(PrevInit->getSourceLocation(),
  4260. diag::warn_initializer_out_of_order);
  4261. if (PrevInit->isAnyMemberInitializer())
  4262. D << 0 << PrevInit->getAnyMember()->getDeclName();
  4263. else
  4264. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  4265. if (Init->isAnyMemberInitializer())
  4266. D << 0 << Init->getAnyMember()->getDeclName();
  4267. else
  4268. D << 1 << Init->getTypeSourceInfo()->getType();
  4269. // Move back to the initializer's location in the ideal list.
  4270. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4271. if (InitKey == IdealInitKeys[IdealIndex])
  4272. break;
  4273. assert(IdealIndex < NumIdealInits &&
  4274. "initializer not found in initializer list");
  4275. }
  4276. PrevInit = Init;
  4277. }
  4278. }
  4279. namespace {
  4280. bool CheckRedundantInit(Sema &S,
  4281. CXXCtorInitializer *Init,
  4282. CXXCtorInitializer *&PrevInit) {
  4283. if (!PrevInit) {
  4284. PrevInit = Init;
  4285. return false;
  4286. }
  4287. if (FieldDecl *Field = Init->getAnyMember())
  4288. S.Diag(Init->getSourceLocation(),
  4289. diag::err_multiple_mem_initialization)
  4290. << Field->getDeclName()
  4291. << Init->getSourceRange();
  4292. else {
  4293. const Type *BaseClass = Init->getBaseClass();
  4294. assert(BaseClass && "neither field nor base");
  4295. S.Diag(Init->getSourceLocation(),
  4296. diag::err_multiple_base_initialization)
  4297. << QualType(BaseClass, 0)
  4298. << Init->getSourceRange();
  4299. }
  4300. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4301. << 0 << PrevInit->getSourceRange();
  4302. return true;
  4303. }
  4304. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4305. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4306. bool CheckRedundantUnionInit(Sema &S,
  4307. CXXCtorInitializer *Init,
  4308. RedundantUnionMap &Unions) {
  4309. FieldDecl *Field = Init->getAnyMember();
  4310. RecordDecl *Parent = Field->getParent();
  4311. NamedDecl *Child = Field;
  4312. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4313. if (Parent->isUnion()) {
  4314. UnionEntry &En = Unions[Parent];
  4315. if (En.first && En.first != Child) {
  4316. S.Diag(Init->getSourceLocation(),
  4317. diag::err_multiple_mem_union_initialization)
  4318. << Field->getDeclName()
  4319. << Init->getSourceRange();
  4320. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4321. << 0 << En.second->getSourceRange();
  4322. return true;
  4323. }
  4324. if (!En.first) {
  4325. En.first = Child;
  4326. En.second = Init;
  4327. }
  4328. if (!Parent->isAnonymousStructOrUnion())
  4329. return false;
  4330. }
  4331. Child = Parent;
  4332. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4333. }
  4334. return false;
  4335. }
  4336. }
  4337. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4338. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4339. SourceLocation ColonLoc,
  4340. ArrayRef<CXXCtorInitializer*> MemInits,
  4341. bool AnyErrors) {
  4342. if (!ConstructorDecl)
  4343. return;
  4344. AdjustDeclIfTemplate(ConstructorDecl);
  4345. CXXConstructorDecl *Constructor
  4346. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4347. if (!Constructor) {
  4348. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4349. return;
  4350. }
  4351. // Mapping for the duplicate initializers check.
  4352. // For member initializers, this is keyed with a FieldDecl*.
  4353. // For base initializers, this is keyed with a Type*.
  4354. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4355. // Mapping for the inconsistent anonymous-union initializers check.
  4356. RedundantUnionMap MemberUnions;
  4357. bool HadError = false;
  4358. for (unsigned i = 0; i < MemInits.size(); i++) {
  4359. CXXCtorInitializer *Init = MemInits[i];
  4360. // Set the source order index.
  4361. Init->setSourceOrder(i);
  4362. if (Init->isAnyMemberInitializer()) {
  4363. const void *Key = GetKeyForMember(Context, Init);
  4364. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4365. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4366. HadError = true;
  4367. } else if (Init->isBaseInitializer()) {
  4368. const void *Key = GetKeyForMember(Context, Init);
  4369. if (CheckRedundantInit(*this, Init, Members[Key]))
  4370. HadError = true;
  4371. } else {
  4372. assert(Init->isDelegatingInitializer());
  4373. // This must be the only initializer
  4374. if (MemInits.size() != 1) {
  4375. Diag(Init->getSourceLocation(),
  4376. diag::err_delegating_initializer_alone)
  4377. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4378. // We will treat this as being the only initializer.
  4379. }
  4380. SetDelegatingInitializer(Constructor, MemInits[i]);
  4381. // Return immediately as the initializer is set.
  4382. return;
  4383. }
  4384. }
  4385. if (HadError)
  4386. return;
  4387. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4388. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4389. DiagnoseUninitializedFields(*this, Constructor);
  4390. }
  4391. void
  4392. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4393. CXXRecordDecl *ClassDecl) {
  4394. // Ignore dependent contexts. Also ignore unions, since their members never
  4395. // have destructors implicitly called.
  4396. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4397. return;
  4398. // FIXME: all the access-control diagnostics are positioned on the
  4399. // field/base declaration. That's probably good; that said, the
  4400. // user might reasonably want to know why the destructor is being
  4401. // emitted, and we currently don't say.
  4402. // Non-static data members.
  4403. for (auto *Field : ClassDecl->fields()) {
  4404. if (Field->isInvalidDecl())
  4405. continue;
  4406. // Don't destroy incomplete or zero-length arrays.
  4407. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4408. continue;
  4409. QualType FieldType = Context.getBaseElementType(Field->getType());
  4410. const RecordType* RT = FieldType->getAs<RecordType>();
  4411. if (!RT)
  4412. continue;
  4413. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4414. if (FieldClassDecl->isInvalidDecl())
  4415. continue;
  4416. if (FieldClassDecl->hasIrrelevantDestructor())
  4417. continue;
  4418. // The destructor for an implicit anonymous union member is never invoked.
  4419. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4420. continue;
  4421. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4422. assert(Dtor && "No dtor found for FieldClassDecl!");
  4423. CheckDestructorAccess(Field->getLocation(), Dtor,
  4424. PDiag(diag::err_access_dtor_field)
  4425. << Field->getDeclName()
  4426. << FieldType);
  4427. MarkFunctionReferenced(Location, Dtor);
  4428. DiagnoseUseOfDecl(Dtor, Location);
  4429. }
  4430. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4431. // Bases.
  4432. for (const auto &Base : ClassDecl->bases()) {
  4433. // Bases are always records in a well-formed non-dependent class.
  4434. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4435. // Remember direct virtual bases.
  4436. if (Base.isVirtual())
  4437. DirectVirtualBases.insert(RT);
  4438. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4439. // If our base class is invalid, we probably can't get its dtor anyway.
  4440. if (BaseClassDecl->isInvalidDecl())
  4441. continue;
  4442. if (BaseClassDecl->hasIrrelevantDestructor())
  4443. continue;
  4444. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4445. assert(Dtor && "No dtor found for BaseClassDecl!");
  4446. // FIXME: caret should be on the start of the class name
  4447. CheckDestructorAccess(Base.getLocStart(), Dtor,
  4448. PDiag(diag::err_access_dtor_base)
  4449. << Base.getType()
  4450. << Base.getSourceRange(),
  4451. Context.getTypeDeclType(ClassDecl));
  4452. MarkFunctionReferenced(Location, Dtor);
  4453. DiagnoseUseOfDecl(Dtor, Location);
  4454. }
  4455. // Virtual bases.
  4456. for (const auto &VBase : ClassDecl->vbases()) {
  4457. // Bases are always records in a well-formed non-dependent class.
  4458. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4459. // Ignore direct virtual bases.
  4460. if (DirectVirtualBases.count(RT))
  4461. continue;
  4462. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4463. // If our base class is invalid, we probably can't get its dtor anyway.
  4464. if (BaseClassDecl->isInvalidDecl())
  4465. continue;
  4466. if (BaseClassDecl->hasIrrelevantDestructor())
  4467. continue;
  4468. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4469. assert(Dtor && "No dtor found for BaseClassDecl!");
  4470. if (CheckDestructorAccess(
  4471. ClassDecl->getLocation(), Dtor,
  4472. PDiag(diag::err_access_dtor_vbase)
  4473. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4474. Context.getTypeDeclType(ClassDecl)) ==
  4475. AR_accessible) {
  4476. CheckDerivedToBaseConversion(
  4477. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4478. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4479. SourceRange(), DeclarationName(), nullptr);
  4480. }
  4481. MarkFunctionReferenced(Location, Dtor);
  4482. DiagnoseUseOfDecl(Dtor, Location);
  4483. }
  4484. }
  4485. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4486. if (!CDtorDecl)
  4487. return;
  4488. if (CXXConstructorDecl *Constructor
  4489. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4490. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4491. DiagnoseUninitializedFields(*this, Constructor);
  4492. }
  4493. }
  4494. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4495. if (!getLangOpts().CPlusPlus)
  4496. return false;
  4497. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  4498. if (!RD)
  4499. return false;
  4500. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  4501. // class template specialization here, but doing so breaks a lot of code.
  4502. // We can't answer whether something is abstract until it has a
  4503. // definition. If it's currently being defined, we'll walk back
  4504. // over all the declarations when we have a full definition.
  4505. const CXXRecordDecl *Def = RD->getDefinition();
  4506. if (!Def || Def->isBeingDefined())
  4507. return false;
  4508. return RD->isAbstract();
  4509. }
  4510. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  4511. TypeDiagnoser &Diagnoser) {
  4512. if (!isAbstractType(Loc, T))
  4513. return false;
  4514. T = Context.getBaseElementType(T);
  4515. Diagnoser.diagnose(*this, Loc, T);
  4516. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  4517. return true;
  4518. }
  4519. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  4520. // Check if we've already emitted the list of pure virtual functions
  4521. // for this class.
  4522. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  4523. return;
  4524. // If the diagnostic is suppressed, don't emit the notes. We're only
  4525. // going to emit them once, so try to attach them to a diagnostic we're
  4526. // actually going to show.
  4527. if (Diags.isLastDiagnosticIgnored())
  4528. return;
  4529. CXXFinalOverriderMap FinalOverriders;
  4530. RD->getFinalOverriders(FinalOverriders);
  4531. // Keep a set of seen pure methods so we won't diagnose the same method
  4532. // more than once.
  4533. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  4534. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  4535. MEnd = FinalOverriders.end();
  4536. M != MEnd;
  4537. ++M) {
  4538. for (OverridingMethods::iterator SO = M->second.begin(),
  4539. SOEnd = M->second.end();
  4540. SO != SOEnd; ++SO) {
  4541. // C++ [class.abstract]p4:
  4542. // A class is abstract if it contains or inherits at least one
  4543. // pure virtual function for which the final overrider is pure
  4544. // virtual.
  4545. //
  4546. if (SO->second.size() != 1)
  4547. continue;
  4548. if (!SO->second.front().Method->isPure())
  4549. continue;
  4550. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  4551. continue;
  4552. Diag(SO->second.front().Method->getLocation(),
  4553. diag::note_pure_virtual_function)
  4554. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  4555. }
  4556. }
  4557. if (!PureVirtualClassDiagSet)
  4558. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  4559. PureVirtualClassDiagSet->insert(RD);
  4560. }
  4561. namespace {
  4562. struct AbstractUsageInfo {
  4563. Sema &S;
  4564. CXXRecordDecl *Record;
  4565. CanQualType AbstractType;
  4566. bool Invalid;
  4567. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  4568. : S(S), Record(Record),
  4569. AbstractType(S.Context.getCanonicalType(
  4570. S.Context.getTypeDeclType(Record))),
  4571. Invalid(false) {}
  4572. void DiagnoseAbstractType() {
  4573. if (Invalid) return;
  4574. S.DiagnoseAbstractType(Record);
  4575. Invalid = true;
  4576. }
  4577. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  4578. };
  4579. struct CheckAbstractUsage {
  4580. AbstractUsageInfo &Info;
  4581. const NamedDecl *Ctx;
  4582. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  4583. : Info(Info), Ctx(Ctx) {}
  4584. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4585. switch (TL.getTypeLocClass()) {
  4586. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4587. #define TYPELOC(CLASS, PARENT) \
  4588. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  4589. #include "clang/AST/TypeLocNodes.def"
  4590. }
  4591. }
  4592. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4593. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  4594. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  4595. if (!TL.getParam(I))
  4596. continue;
  4597. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  4598. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  4599. }
  4600. }
  4601. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4602. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  4603. }
  4604. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4605. // Visit the type parameters from a permissive context.
  4606. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4607. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4608. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4609. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4610. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4611. // TODO: other template argument types?
  4612. }
  4613. }
  4614. // Visit pointee types from a permissive context.
  4615. #define CheckPolymorphic(Type) \
  4616. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4617. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4618. }
  4619. CheckPolymorphic(PointerTypeLoc)
  4620. CheckPolymorphic(ReferenceTypeLoc)
  4621. CheckPolymorphic(MemberPointerTypeLoc)
  4622. CheckPolymorphic(BlockPointerTypeLoc)
  4623. CheckPolymorphic(AtomicTypeLoc)
  4624. /// Handle all the types we haven't given a more specific
  4625. /// implementation for above.
  4626. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4627. // Every other kind of type that we haven't called out already
  4628. // that has an inner type is either (1) sugar or (2) contains that
  4629. // inner type in some way as a subobject.
  4630. if (TypeLoc Next = TL.getNextTypeLoc())
  4631. return Visit(Next, Sel);
  4632. // If there's no inner type and we're in a permissive context,
  4633. // don't diagnose.
  4634. if (Sel == Sema::AbstractNone) return;
  4635. // Check whether the type matches the abstract type.
  4636. QualType T = TL.getType();
  4637. if (T->isArrayType()) {
  4638. Sel = Sema::AbstractArrayType;
  4639. T = Info.S.Context.getBaseElementType(T);
  4640. }
  4641. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4642. if (CT != Info.AbstractType) return;
  4643. // It matched; do some magic.
  4644. if (Sel == Sema::AbstractArrayType) {
  4645. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4646. << T << TL.getSourceRange();
  4647. } else {
  4648. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4649. << Sel << T << TL.getSourceRange();
  4650. }
  4651. Info.DiagnoseAbstractType();
  4652. }
  4653. };
  4654. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4655. Sema::AbstractDiagSelID Sel) {
  4656. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4657. }
  4658. }
  4659. /// Check for invalid uses of an abstract type in a method declaration.
  4660. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4661. CXXMethodDecl *MD) {
  4662. // No need to do the check on definitions, which require that
  4663. // the return/param types be complete.
  4664. if (MD->doesThisDeclarationHaveABody())
  4665. return;
  4666. // For safety's sake, just ignore it if we don't have type source
  4667. // information. This should never happen for non-implicit methods,
  4668. // but...
  4669. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4670. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4671. }
  4672. /// Check for invalid uses of an abstract type within a class definition.
  4673. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4674. CXXRecordDecl *RD) {
  4675. for (auto *D : RD->decls()) {
  4676. if (D->isImplicit()) continue;
  4677. // Methods and method templates.
  4678. if (isa<CXXMethodDecl>(D)) {
  4679. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4680. } else if (isa<FunctionTemplateDecl>(D)) {
  4681. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4682. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4683. // Fields and static variables.
  4684. } else if (isa<FieldDecl>(D)) {
  4685. FieldDecl *FD = cast<FieldDecl>(D);
  4686. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4687. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4688. } else if (isa<VarDecl>(D)) {
  4689. VarDecl *VD = cast<VarDecl>(D);
  4690. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4691. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4692. // Nested classes and class templates.
  4693. } else if (isa<CXXRecordDecl>(D)) {
  4694. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4695. } else if (isa<ClassTemplateDecl>(D)) {
  4696. CheckAbstractClassUsage(Info,
  4697. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4698. }
  4699. }
  4700. }
  4701. static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
  4702. Attr *ClassAttr = getDLLAttr(Class);
  4703. if (!ClassAttr)
  4704. return;
  4705. assert(ClassAttr->getKind() == attr::DLLExport);
  4706. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4707. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4708. // Don't go any further if this is just an explicit instantiation
  4709. // declaration.
  4710. return;
  4711. for (Decl *Member : Class->decls()) {
  4712. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  4713. if (!MD)
  4714. continue;
  4715. if (Member->getAttr<DLLExportAttr>()) {
  4716. if (MD->isUserProvided()) {
  4717. // Instantiate non-default class member functions ...
  4718. // .. except for certain kinds of template specializations.
  4719. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4720. continue;
  4721. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4722. // The function will be passed to the consumer when its definition is
  4723. // encountered.
  4724. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4725. MD->isCopyAssignmentOperator() ||
  4726. MD->isMoveAssignmentOperator()) {
  4727. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4728. // defaulted methods, and the copy and move assignment operators. The
  4729. // latter are exported even if they are trivial, because the address of
  4730. // an operator can be taken and should compare equal accross libraries.
  4731. DiagnosticErrorTrap Trap(S.Diags);
  4732. S.MarkFunctionReferenced(Class->getLocation(), MD);
  4733. if (Trap.hasErrorOccurred()) {
  4734. S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4735. << Class->getName() << !S.getLangOpts().CPlusPlus11;
  4736. break;
  4737. }
  4738. // There is no later point when we will see the definition of this
  4739. // function, so pass it to the consumer now.
  4740. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  4741. }
  4742. }
  4743. }
  4744. }
  4745. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  4746. CXXRecordDecl *Class) {
  4747. // Only the MS ABI has default constructor closures, so we don't need to do
  4748. // this semantic checking anywhere else.
  4749. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  4750. return;
  4751. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  4752. for (Decl *Member : Class->decls()) {
  4753. // Look for exported default constructors.
  4754. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  4755. if (!CD || !CD->isDefaultConstructor())
  4756. continue;
  4757. auto *Attr = CD->getAttr<DLLExportAttr>();
  4758. if (!Attr)
  4759. continue;
  4760. // If the class is non-dependent, mark the default arguments as ODR-used so
  4761. // that we can properly codegen the constructor closure.
  4762. if (!Class->isDependentContext()) {
  4763. for (ParmVarDecl *PD : CD->parameters()) {
  4764. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  4765. S.DiscardCleanupsInEvaluationContext();
  4766. }
  4767. }
  4768. if (LastExportedDefaultCtor) {
  4769. S.Diag(LastExportedDefaultCtor->getLocation(),
  4770. diag::err_attribute_dll_ambiguous_default_ctor)
  4771. << Class;
  4772. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  4773. << CD->getDeclName();
  4774. return;
  4775. }
  4776. LastExportedDefaultCtor = CD;
  4777. }
  4778. }
  4779. /// \brief Check class-level dllimport/dllexport attribute.
  4780. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  4781. Attr *ClassAttr = getDLLAttr(Class);
  4782. // MSVC inherits DLL attributes to partial class template specializations.
  4783. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  4784. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  4785. if (Attr *TemplateAttr =
  4786. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  4787. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  4788. A->setInherited(true);
  4789. ClassAttr = A;
  4790. }
  4791. }
  4792. }
  4793. if (!ClassAttr)
  4794. return;
  4795. if (!Class->isExternallyVisible()) {
  4796. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  4797. << Class << ClassAttr;
  4798. return;
  4799. }
  4800. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4801. !ClassAttr->isInherited()) {
  4802. // Diagnose dll attributes on members of class with dll attribute.
  4803. for (Decl *Member : Class->decls()) {
  4804. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  4805. continue;
  4806. InheritableAttr *MemberAttr = getDLLAttr(Member);
  4807. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  4808. continue;
  4809. Diag(MemberAttr->getLocation(),
  4810. diag::err_attribute_dll_member_of_dll_class)
  4811. << MemberAttr << ClassAttr;
  4812. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  4813. Member->setInvalidDecl();
  4814. }
  4815. }
  4816. if (Class->getDescribedClassTemplate())
  4817. // Don't inherit dll attribute until the template is instantiated.
  4818. return;
  4819. // The class is either imported or exported.
  4820. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  4821. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4822. // Ignore explicit dllexport on explicit class template instantiation declarations.
  4823. if (ClassExported && !ClassAttr->isInherited() &&
  4824. TSK == TSK_ExplicitInstantiationDeclaration) {
  4825. Class->dropAttr<DLLExportAttr>();
  4826. return;
  4827. }
  4828. // Force declaration of implicit members so they can inherit the attribute.
  4829. ForceDeclarationOfImplicitMembers(Class);
  4830. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  4831. // seem to be true in practice?
  4832. for (Decl *Member : Class->decls()) {
  4833. VarDecl *VD = dyn_cast<VarDecl>(Member);
  4834. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  4835. // Only methods and static fields inherit the attributes.
  4836. if (!VD && !MD)
  4837. continue;
  4838. if (MD) {
  4839. // Don't process deleted methods.
  4840. if (MD->isDeleted())
  4841. continue;
  4842. if (MD->isInlined()) {
  4843. // MinGW does not import or export inline methods.
  4844. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4845. !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
  4846. continue;
  4847. // MSVC versions before 2015 don't export the move assignment operators
  4848. // and move constructor, so don't attempt to import/export them if
  4849. // we have a definition.
  4850. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  4851. if ((MD->isMoveAssignmentOperator() ||
  4852. (Ctor && Ctor->isMoveConstructor())) &&
  4853. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  4854. continue;
  4855. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  4856. // operator is exported anyway.
  4857. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  4858. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  4859. continue;
  4860. }
  4861. }
  4862. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  4863. continue;
  4864. if (!getDLLAttr(Member)) {
  4865. auto *NewAttr =
  4866. cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4867. NewAttr->setInherited(true);
  4868. Member->addAttr(NewAttr);
  4869. }
  4870. }
  4871. if (ClassExported)
  4872. DelayedDllExportClasses.push_back(Class);
  4873. }
  4874. /// \brief Perform propagation of DLL attributes from a derived class to a
  4875. /// templated base class for MS compatibility.
  4876. void Sema::propagateDLLAttrToBaseClassTemplate(
  4877. CXXRecordDecl *Class, Attr *ClassAttr,
  4878. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  4879. if (getDLLAttr(
  4880. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  4881. // If the base class template has a DLL attribute, don't try to change it.
  4882. return;
  4883. }
  4884. auto TSK = BaseTemplateSpec->getSpecializationKind();
  4885. if (!getDLLAttr(BaseTemplateSpec) &&
  4886. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  4887. TSK == TSK_ImplicitInstantiation)) {
  4888. // The template hasn't been instantiated yet (or it has, but only as an
  4889. // explicit instantiation declaration or implicit instantiation, which means
  4890. // we haven't codegenned any members yet), so propagate the attribute.
  4891. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4892. NewAttr->setInherited(true);
  4893. BaseTemplateSpec->addAttr(NewAttr);
  4894. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  4895. // needs to be run again to work see the new attribute. Otherwise this will
  4896. // get run whenever the template is instantiated.
  4897. if (TSK != TSK_Undeclared)
  4898. checkClassLevelDLLAttribute(BaseTemplateSpec);
  4899. return;
  4900. }
  4901. if (getDLLAttr(BaseTemplateSpec)) {
  4902. // The template has already been specialized or instantiated with an
  4903. // attribute, explicitly or through propagation. We should not try to change
  4904. // it.
  4905. return;
  4906. }
  4907. // The template was previously instantiated or explicitly specialized without
  4908. // a dll attribute, It's too late for us to add an attribute, so warn that
  4909. // this is unsupported.
  4910. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  4911. << BaseTemplateSpec->isExplicitSpecialization();
  4912. Diag(ClassAttr->getLocation(), diag::note_attribute);
  4913. if (BaseTemplateSpec->isExplicitSpecialization()) {
  4914. Diag(BaseTemplateSpec->getLocation(),
  4915. diag::note_template_class_explicit_specialization_was_here)
  4916. << BaseTemplateSpec;
  4917. } else {
  4918. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  4919. diag::note_template_class_instantiation_was_here)
  4920. << BaseTemplateSpec;
  4921. }
  4922. }
  4923. static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
  4924. SourceLocation DefaultLoc) {
  4925. switch (S.getSpecialMember(MD)) {
  4926. case Sema::CXXDefaultConstructor:
  4927. S.DefineImplicitDefaultConstructor(DefaultLoc,
  4928. cast<CXXConstructorDecl>(MD));
  4929. break;
  4930. case Sema::CXXCopyConstructor:
  4931. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  4932. break;
  4933. case Sema::CXXCopyAssignment:
  4934. S.DefineImplicitCopyAssignment(DefaultLoc, MD);
  4935. break;
  4936. case Sema::CXXDestructor:
  4937. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  4938. break;
  4939. case Sema::CXXMoveConstructor:
  4940. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  4941. break;
  4942. case Sema::CXXMoveAssignment:
  4943. S.DefineImplicitMoveAssignment(DefaultLoc, MD);
  4944. break;
  4945. case Sema::CXXInvalid:
  4946. llvm_unreachable("Invalid special member.");
  4947. }
  4948. }
  4949. /// \brief Perform semantic checks on a class definition that has been
  4950. /// completing, introducing implicitly-declared members, checking for
  4951. /// abstract types, etc.
  4952. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  4953. if (!Record)
  4954. return;
  4955. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  4956. AbstractUsageInfo Info(*this, Record);
  4957. CheckAbstractClassUsage(Info, Record);
  4958. }
  4959. // If this is not an aggregate type and has no user-declared constructor,
  4960. // complain about any non-static data members of reference or const scalar
  4961. // type, since they will never get initializers.
  4962. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  4963. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  4964. !Record->isLambda()) {
  4965. bool Complained = false;
  4966. for (const auto *F : Record->fields()) {
  4967. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  4968. continue;
  4969. if (F->getType()->isReferenceType() ||
  4970. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  4971. if (!Complained) {
  4972. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  4973. << Record->getTagKind() << Record;
  4974. Complained = true;
  4975. }
  4976. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  4977. << F->getType()->isReferenceType()
  4978. << F->getDeclName();
  4979. }
  4980. }
  4981. }
  4982. if (Record->getIdentifier()) {
  4983. // C++ [class.mem]p13:
  4984. // If T is the name of a class, then each of the following shall have a
  4985. // name different from T:
  4986. // - every member of every anonymous union that is a member of class T.
  4987. //
  4988. // C++ [class.mem]p14:
  4989. // In addition, if class T has a user-declared constructor (12.1), every
  4990. // non-static data member of class T shall have a name different from T.
  4991. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  4992. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  4993. ++I) {
  4994. NamedDecl *D = *I;
  4995. if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
  4996. isa<IndirectFieldDecl>(D)) {
  4997. Diag(D->getLocation(), diag::err_member_name_of_class)
  4998. << D->getDeclName();
  4999. break;
  5000. }
  5001. }
  5002. }
  5003. // Warn if the class has virtual methods but non-virtual public destructor.
  5004. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5005. CXXDestructorDecl *dtor = Record->getDestructor();
  5006. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5007. !Record->hasAttr<FinalAttr>())
  5008. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5009. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5010. }
  5011. if (Record->isAbstract()) {
  5012. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5013. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5014. << FA->isSpelledAsSealed();
  5015. DiagnoseAbstractType(Record);
  5016. }
  5017. }
  5018. bool HasMethodWithOverrideControl = false,
  5019. HasOverridingMethodWithoutOverrideControl = false;
  5020. if (!Record->isDependentType()) {
  5021. for (auto *M : Record->methods()) {
  5022. // See if a method overloads virtual methods in a base
  5023. // class without overriding any.
  5024. if (!M->isStatic())
  5025. DiagnoseHiddenVirtualMethods(M);
  5026. if (M->hasAttr<OverrideAttr>())
  5027. HasMethodWithOverrideControl = true;
  5028. else if (M->size_overridden_methods() > 0)
  5029. HasOverridingMethodWithoutOverrideControl = true;
  5030. // Check whether the explicitly-defaulted special members are valid.
  5031. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  5032. CheckExplicitlyDefaultedSpecialMember(M);
  5033. // For an explicitly defaulted or deleted special member, we defer
  5034. // determining triviality until the class is complete. That time is now!
  5035. CXXSpecialMember CSM = getSpecialMember(M);
  5036. if (!M->isImplicit() && !M->isUserProvided()) {
  5037. if (CSM != CXXInvalid) {
  5038. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5039. // Inform the class that we've finished declaring this member.
  5040. Record->finishedDefaultedOrDeletedMember(M);
  5041. }
  5042. }
  5043. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  5044. M->hasAttr<DLLExportAttr>()) {
  5045. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5046. M->isTrivial() &&
  5047. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  5048. CSM == CXXDestructor))
  5049. M->dropAttr<DLLExportAttr>();
  5050. if (M->hasAttr<DLLExportAttr>()) {
  5051. DefineImplicitSpecialMember(*this, M, M->getLocation());
  5052. ActOnFinishInlineFunctionDef(M);
  5053. }
  5054. }
  5055. }
  5056. }
  5057. if (HasMethodWithOverrideControl &&
  5058. HasOverridingMethodWithoutOverrideControl) {
  5059. // At least one method has the 'override' control declared.
  5060. // Diagnose all other overridden methods which do not have 'override' specified on them.
  5061. for (auto *M : Record->methods())
  5062. DiagnoseAbsenceOfOverrideControl(M);
  5063. }
  5064. // ms_struct is a request to use the same ABI rules as MSVC. Check
  5065. // whether this class uses any C++ features that are implemented
  5066. // completely differently in MSVC, and if so, emit a diagnostic.
  5067. // That diagnostic defaults to an error, but we allow projects to
  5068. // map it down to a warning (or ignore it). It's a fairly common
  5069. // practice among users of the ms_struct pragma to mass-annotate
  5070. // headers, sweeping up a bunch of types that the project doesn't
  5071. // really rely on MSVC-compatible layout for. We must therefore
  5072. // support "ms_struct except for C++ stuff" as a secondary ABI.
  5073. if (Record->isMsStruct(Context) &&
  5074. (Record->isPolymorphic() || Record->getNumBases())) {
  5075. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  5076. }
  5077. checkClassLevelDLLAttribute(Record);
  5078. }
  5079. /// Look up the special member function that would be called by a special
  5080. /// member function for a subobject of class type.
  5081. ///
  5082. /// \param Class The class type of the subobject.
  5083. /// \param CSM The kind of special member function.
  5084. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  5085. /// \param ConstRHS True if this is a copy operation with a const object
  5086. /// on its RHS, that is, if the argument to the outer special member
  5087. /// function is 'const' and this is not a field marked 'mutable'.
  5088. static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
  5089. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  5090. unsigned FieldQuals, bool ConstRHS) {
  5091. unsigned LHSQuals = 0;
  5092. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  5093. LHSQuals = FieldQuals;
  5094. unsigned RHSQuals = FieldQuals;
  5095. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  5096. RHSQuals = 0;
  5097. else if (ConstRHS)
  5098. RHSQuals |= Qualifiers::Const;
  5099. return S.LookupSpecialMember(Class, CSM,
  5100. RHSQuals & Qualifiers::Const,
  5101. RHSQuals & Qualifiers::Volatile,
  5102. false,
  5103. LHSQuals & Qualifiers::Const,
  5104. LHSQuals & Qualifiers::Volatile);
  5105. }
  5106. class Sema::InheritedConstructorInfo {
  5107. Sema &S;
  5108. SourceLocation UseLoc;
  5109. /// A mapping from the base classes through which the constructor was
  5110. /// inherited to the using shadow declaration in that base class (or a null
  5111. /// pointer if the constructor was declared in that base class).
  5112. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  5113. InheritedFromBases;
  5114. public:
  5115. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  5116. ConstructorUsingShadowDecl *Shadow)
  5117. : S(S), UseLoc(UseLoc) {
  5118. bool DiagnosedMultipleConstructedBases = false;
  5119. CXXRecordDecl *ConstructedBase = nullptr;
  5120. UsingDecl *ConstructedBaseUsing = nullptr;
  5121. // Find the set of such base class subobjects and check that there's a
  5122. // unique constructed subobject.
  5123. for (auto *D : Shadow->redecls()) {
  5124. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  5125. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  5126. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  5127. InheritedFromBases.insert(
  5128. std::make_pair(DNominatedBase->getCanonicalDecl(),
  5129. DShadow->getNominatedBaseClassShadowDecl()));
  5130. if (DShadow->constructsVirtualBase())
  5131. InheritedFromBases.insert(
  5132. std::make_pair(DConstructedBase->getCanonicalDecl(),
  5133. DShadow->getConstructedBaseClassShadowDecl()));
  5134. else
  5135. assert(DNominatedBase == DConstructedBase);
  5136. // [class.inhctor.init]p2:
  5137. // If the constructor was inherited from multiple base class subobjects
  5138. // of type B, the program is ill-formed.
  5139. if (!ConstructedBase) {
  5140. ConstructedBase = DConstructedBase;
  5141. ConstructedBaseUsing = D->getUsingDecl();
  5142. } else if (ConstructedBase != DConstructedBase &&
  5143. !Shadow->isInvalidDecl()) {
  5144. if (!DiagnosedMultipleConstructedBases) {
  5145. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  5146. << Shadow->getTargetDecl();
  5147. S.Diag(ConstructedBaseUsing->getLocation(),
  5148. diag::note_ambiguous_inherited_constructor_using)
  5149. << ConstructedBase;
  5150. DiagnosedMultipleConstructedBases = true;
  5151. }
  5152. S.Diag(D->getUsingDecl()->getLocation(),
  5153. diag::note_ambiguous_inherited_constructor_using)
  5154. << DConstructedBase;
  5155. }
  5156. }
  5157. if (DiagnosedMultipleConstructedBases)
  5158. Shadow->setInvalidDecl();
  5159. }
  5160. /// Find the constructor to use for inherited construction of a base class,
  5161. /// and whether that base class constructor inherits the constructor from a
  5162. /// virtual base class (in which case it won't actually invoke it).
  5163. std::pair<CXXConstructorDecl *, bool>
  5164. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  5165. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  5166. if (It == InheritedFromBases.end())
  5167. return std::make_pair(nullptr, false);
  5168. // This is an intermediary class.
  5169. if (It->second)
  5170. return std::make_pair(
  5171. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  5172. It->second->constructsVirtualBase());
  5173. // This is the base class from which the constructor was inherited.
  5174. return std::make_pair(Ctor, false);
  5175. }
  5176. };
  5177. /// Is the special member function which would be selected to perform the
  5178. /// specified operation on the specified class type a constexpr constructor?
  5179. static bool
  5180. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  5181. Sema::CXXSpecialMember CSM, unsigned Quals,
  5182. bool ConstRHS,
  5183. CXXConstructorDecl *InheritedCtor = nullptr,
  5184. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5185. // If we're inheriting a constructor, see if we need to call it for this base
  5186. // class.
  5187. if (InheritedCtor) {
  5188. assert(CSM == Sema::CXXDefaultConstructor);
  5189. auto BaseCtor =
  5190. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  5191. if (BaseCtor)
  5192. return BaseCtor->isConstexpr();
  5193. }
  5194. if (CSM == Sema::CXXDefaultConstructor)
  5195. return ClassDecl->hasConstexprDefaultConstructor();
  5196. Sema::SpecialMemberOverloadResult *SMOR =
  5197. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  5198. if (!SMOR || !SMOR->getMethod())
  5199. // A constructor we wouldn't select can't be "involved in initializing"
  5200. // anything.
  5201. return true;
  5202. return SMOR->getMethod()->isConstexpr();
  5203. }
  5204. /// Determine whether the specified special member function would be constexpr
  5205. /// if it were implicitly defined.
  5206. static bool defaultedSpecialMemberIsConstexpr(
  5207. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  5208. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  5209. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  5210. if (!S.getLangOpts().CPlusPlus11)
  5211. return false;
  5212. // C++11 [dcl.constexpr]p4:
  5213. // In the definition of a constexpr constructor [...]
  5214. bool Ctor = true;
  5215. switch (CSM) {
  5216. case Sema::CXXDefaultConstructor:
  5217. if (Inherited)
  5218. break;
  5219. // Since default constructor lookup is essentially trivial (and cannot
  5220. // involve, for instance, template instantiation), we compute whether a
  5221. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  5222. //
  5223. // This is important for performance; we need to know whether the default
  5224. // constructor is constexpr to determine whether the type is a literal type.
  5225. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  5226. case Sema::CXXCopyConstructor:
  5227. case Sema::CXXMoveConstructor:
  5228. // For copy or move constructors, we need to perform overload resolution.
  5229. break;
  5230. case Sema::CXXCopyAssignment:
  5231. case Sema::CXXMoveAssignment:
  5232. if (!S.getLangOpts().CPlusPlus14)
  5233. return false;
  5234. // In C++1y, we need to perform overload resolution.
  5235. Ctor = false;
  5236. break;
  5237. case Sema::CXXDestructor:
  5238. case Sema::CXXInvalid:
  5239. return false;
  5240. }
  5241. // -- if the class is a non-empty union, or for each non-empty anonymous
  5242. // union member of a non-union class, exactly one non-static data member
  5243. // shall be initialized; [DR1359]
  5244. //
  5245. // If we squint, this is guaranteed, since exactly one non-static data member
  5246. // will be initialized (if the constructor isn't deleted), we just don't know
  5247. // which one.
  5248. if (Ctor && ClassDecl->isUnion())
  5249. return CSM == Sema::CXXDefaultConstructor
  5250. ? ClassDecl->hasInClassInitializer() ||
  5251. !ClassDecl->hasVariantMembers()
  5252. : true;
  5253. // -- the class shall not have any virtual base classes;
  5254. if (Ctor && ClassDecl->getNumVBases())
  5255. return false;
  5256. // C++1y [class.copy]p26:
  5257. // -- [the class] is a literal type, and
  5258. if (!Ctor && !ClassDecl->isLiteral())
  5259. return false;
  5260. // -- every constructor involved in initializing [...] base class
  5261. // sub-objects shall be a constexpr constructor;
  5262. // -- the assignment operator selected to copy/move each direct base
  5263. // class is a constexpr function, and
  5264. for (const auto &B : ClassDecl->bases()) {
  5265. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  5266. if (!BaseType) continue;
  5267. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  5268. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  5269. InheritedCtor, Inherited))
  5270. return false;
  5271. }
  5272. // -- every constructor involved in initializing non-static data members
  5273. // [...] shall be a constexpr constructor;
  5274. // -- every non-static data member and base class sub-object shall be
  5275. // initialized
  5276. // -- for each non-static data member of X that is of class type (or array
  5277. // thereof), the assignment operator selected to copy/move that member is
  5278. // a constexpr function
  5279. for (const auto *F : ClassDecl->fields()) {
  5280. if (F->isInvalidDecl())
  5281. continue;
  5282. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  5283. continue;
  5284. QualType BaseType = S.Context.getBaseElementType(F->getType());
  5285. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  5286. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  5287. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  5288. BaseType.getCVRQualifiers(),
  5289. ConstArg && !F->isMutable()))
  5290. return false;
  5291. } else if (CSM == Sema::CXXDefaultConstructor) {
  5292. return false;
  5293. }
  5294. }
  5295. // All OK, it's constexpr!
  5296. return true;
  5297. }
  5298. static Sema::ImplicitExceptionSpecification
  5299. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  5300. switch (S.getSpecialMember(MD)) {
  5301. case Sema::CXXDefaultConstructor:
  5302. return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
  5303. case Sema::CXXCopyConstructor:
  5304. return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
  5305. case Sema::CXXCopyAssignment:
  5306. return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
  5307. case Sema::CXXMoveConstructor:
  5308. return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
  5309. case Sema::CXXMoveAssignment:
  5310. return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
  5311. case Sema::CXXDestructor:
  5312. return S.ComputeDefaultedDtorExceptionSpec(MD);
  5313. case Sema::CXXInvalid:
  5314. break;
  5315. }
  5316. assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
  5317. "only special members have implicit exception specs");
  5318. return S.ComputeInheritingCtorExceptionSpec(Loc,
  5319. cast<CXXConstructorDecl>(MD));
  5320. }
  5321. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  5322. CXXMethodDecl *MD) {
  5323. FunctionProtoType::ExtProtoInfo EPI;
  5324. // Build an exception specification pointing back at this member.
  5325. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5326. EPI.ExceptionSpec.SourceDecl = MD;
  5327. // Set the calling convention to the default for C++ instance methods.
  5328. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  5329. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5330. /*IsCXXMethod=*/true));
  5331. return EPI;
  5332. }
  5333. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  5334. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  5335. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  5336. return;
  5337. // Evaluate the exception specification.
  5338. auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
  5339. auto ESI = IES.getExceptionSpec();
  5340. // Update the type of the special member to use it.
  5341. UpdateExceptionSpec(MD, ESI);
  5342. // A user-provided destructor can be defined outside the class. When that
  5343. // happens, be sure to update the exception specification on both
  5344. // declarations.
  5345. const FunctionProtoType *CanonicalFPT =
  5346. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  5347. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  5348. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  5349. }
  5350. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  5351. CXXRecordDecl *RD = MD->getParent();
  5352. CXXSpecialMember CSM = getSpecialMember(MD);
  5353. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  5354. "not an explicitly-defaulted special member");
  5355. // Whether this was the first-declared instance of the constructor.
  5356. // This affects whether we implicitly add an exception spec and constexpr.
  5357. bool First = MD == MD->getCanonicalDecl();
  5358. bool HadError = false;
  5359. // C++11 [dcl.fct.def.default]p1:
  5360. // A function that is explicitly defaulted shall
  5361. // -- be a special member function (checked elsewhere),
  5362. // -- have the same type (except for ref-qualifiers, and except that a
  5363. // copy operation can take a non-const reference) as an implicit
  5364. // declaration, and
  5365. // -- not have default arguments.
  5366. unsigned ExpectedParams = 1;
  5367. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  5368. ExpectedParams = 0;
  5369. if (MD->getNumParams() != ExpectedParams) {
  5370. // This also checks for default arguments: a copy or move constructor with a
  5371. // default argument is classified as a default constructor, and assignment
  5372. // operations and destructors can't have default arguments.
  5373. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  5374. << CSM << MD->getSourceRange();
  5375. HadError = true;
  5376. } else if (MD->isVariadic()) {
  5377. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  5378. << CSM << MD->getSourceRange();
  5379. HadError = true;
  5380. }
  5381. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  5382. bool CanHaveConstParam = false;
  5383. if (CSM == CXXCopyConstructor)
  5384. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  5385. else if (CSM == CXXCopyAssignment)
  5386. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  5387. QualType ReturnType = Context.VoidTy;
  5388. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  5389. // Check for return type matching.
  5390. ReturnType = Type->getReturnType();
  5391. QualType ExpectedReturnType =
  5392. Context.getLValueReferenceType(Context.getTypeDeclType(RD));
  5393. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  5394. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  5395. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  5396. HadError = true;
  5397. }
  5398. // A defaulted special member cannot have cv-qualifiers.
  5399. if (Type->getTypeQuals()) {
  5400. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  5401. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  5402. HadError = true;
  5403. }
  5404. }
  5405. // Check for parameter type matching.
  5406. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  5407. bool HasConstParam = false;
  5408. if (ExpectedParams && ArgType->isReferenceType()) {
  5409. // Argument must be reference to possibly-const T.
  5410. QualType ReferentType = ArgType->getPointeeType();
  5411. HasConstParam = ReferentType.isConstQualified();
  5412. if (ReferentType.isVolatileQualified()) {
  5413. Diag(MD->getLocation(),
  5414. diag::err_defaulted_special_member_volatile_param) << CSM;
  5415. HadError = true;
  5416. }
  5417. if (HasConstParam && !CanHaveConstParam) {
  5418. if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  5419. Diag(MD->getLocation(),
  5420. diag::err_defaulted_special_member_copy_const_param)
  5421. << (CSM == CXXCopyAssignment);
  5422. // FIXME: Explain why this special member can't be const.
  5423. } else {
  5424. Diag(MD->getLocation(),
  5425. diag::err_defaulted_special_member_move_const_param)
  5426. << (CSM == CXXMoveAssignment);
  5427. }
  5428. HadError = true;
  5429. }
  5430. } else if (ExpectedParams) {
  5431. // A copy assignment operator can take its argument by value, but a
  5432. // defaulted one cannot.
  5433. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  5434. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  5435. HadError = true;
  5436. }
  5437. // C++11 [dcl.fct.def.default]p2:
  5438. // An explicitly-defaulted function may be declared constexpr only if it
  5439. // would have been implicitly declared as constexpr,
  5440. // Do not apply this rule to members of class templates, since core issue 1358
  5441. // makes such functions always instantiate to constexpr functions. For
  5442. // functions which cannot be constexpr (for non-constructors in C++11 and for
  5443. // destructors in C++1y), this is checked elsewhere.
  5444. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  5445. HasConstParam);
  5446. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  5447. : isa<CXXConstructorDecl>(MD)) &&
  5448. MD->isConstexpr() && !Constexpr &&
  5449. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  5450. Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
  5451. // FIXME: Explain why the special member can't be constexpr.
  5452. HadError = true;
  5453. }
  5454. // and may have an explicit exception-specification only if it is compatible
  5455. // with the exception-specification on the implicit declaration.
  5456. if (Type->hasExceptionSpec()) {
  5457. // Delay the check if this is the first declaration of the special member,
  5458. // since we may not have parsed some necessary in-class initializers yet.
  5459. if (First) {
  5460. // If the exception specification needs to be instantiated, do so now,
  5461. // before we clobber it with an EST_Unevaluated specification below.
  5462. if (Type->getExceptionSpecType() == EST_Uninstantiated) {
  5463. InstantiateExceptionSpec(MD->getLocStart(), MD);
  5464. Type = MD->getType()->getAs<FunctionProtoType>();
  5465. }
  5466. DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
  5467. } else
  5468. CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
  5469. }
  5470. // If a function is explicitly defaulted on its first declaration,
  5471. if (First) {
  5472. // -- it is implicitly considered to be constexpr if the implicit
  5473. // definition would be,
  5474. MD->setConstexpr(Constexpr);
  5475. // -- it is implicitly considered to have the same exception-specification
  5476. // as if it had been implicitly declared,
  5477. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  5478. EPI.ExceptionSpec.Type = EST_Unevaluated;
  5479. EPI.ExceptionSpec.SourceDecl = MD;
  5480. MD->setType(Context.getFunctionType(ReturnType,
  5481. llvm::makeArrayRef(&ArgType,
  5482. ExpectedParams),
  5483. EPI));
  5484. }
  5485. if (ShouldDeleteSpecialMember(MD, CSM)) {
  5486. if (First) {
  5487. SetDeclDeleted(MD, MD->getLocation());
  5488. } else {
  5489. // C++11 [dcl.fct.def.default]p4:
  5490. // [For a] user-provided explicitly-defaulted function [...] if such a
  5491. // function is implicitly defined as deleted, the program is ill-formed.
  5492. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  5493. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  5494. HadError = true;
  5495. }
  5496. }
  5497. if (HadError)
  5498. MD->setInvalidDecl();
  5499. }
  5500. /// Check whether the exception specification provided for an
  5501. /// explicitly-defaulted special member matches the exception specification
  5502. /// that would have been generated for an implicit special member, per
  5503. /// C++11 [dcl.fct.def.default]p2.
  5504. void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
  5505. CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
  5506. // If the exception specification was explicitly specified but hadn't been
  5507. // parsed when the method was defaulted, grab it now.
  5508. if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
  5509. SpecifiedType =
  5510. MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  5511. // Compute the implicit exception specification.
  5512. CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  5513. /*IsCXXMethod=*/true);
  5514. FunctionProtoType::ExtProtoInfo EPI(CC);
  5515. auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
  5516. EPI.ExceptionSpec = IES.getExceptionSpec();
  5517. const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
  5518. Context.getFunctionType(Context.VoidTy, None, EPI));
  5519. // Ensure that it matches.
  5520. CheckEquivalentExceptionSpec(
  5521. PDiag(diag::err_incorrect_defaulted_exception_spec)
  5522. << getSpecialMember(MD), PDiag(),
  5523. ImplicitType, SourceLocation(),
  5524. SpecifiedType, MD->getLocation());
  5525. }
  5526. void Sema::CheckDelayedMemberExceptionSpecs() {
  5527. decltype(DelayedExceptionSpecChecks) Checks;
  5528. decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
  5529. std::swap(Checks, DelayedExceptionSpecChecks);
  5530. std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
  5531. // Perform any deferred checking of exception specifications for virtual
  5532. // destructors.
  5533. for (auto &Check : Checks)
  5534. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  5535. // Check that any explicitly-defaulted methods have exception specifications
  5536. // compatible with their implicit exception specifications.
  5537. for (auto &Spec : Specs)
  5538. CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
  5539. }
  5540. namespace {
  5541. struct SpecialMemberDeletionInfo {
  5542. Sema &S;
  5543. CXXMethodDecl *MD;
  5544. Sema::CXXSpecialMember CSM;
  5545. Sema::InheritedConstructorInfo *ICI;
  5546. bool Diagnose;
  5547. // Properties of the special member, computed for convenience.
  5548. bool IsConstructor, IsAssignment, IsMove, ConstArg;
  5549. SourceLocation Loc;
  5550. bool AllFieldsAreConst;
  5551. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  5552. Sema::CXXSpecialMember CSM,
  5553. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  5554. : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
  5555. IsConstructor(false), IsAssignment(false), IsMove(false),
  5556. ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
  5557. switch (CSM) {
  5558. case Sema::CXXDefaultConstructor:
  5559. case Sema::CXXCopyConstructor:
  5560. IsConstructor = true;
  5561. break;
  5562. case Sema::CXXMoveConstructor:
  5563. IsConstructor = true;
  5564. IsMove = true;
  5565. break;
  5566. case Sema::CXXCopyAssignment:
  5567. IsAssignment = true;
  5568. break;
  5569. case Sema::CXXMoveAssignment:
  5570. IsAssignment = true;
  5571. IsMove = true;
  5572. break;
  5573. case Sema::CXXDestructor:
  5574. break;
  5575. case Sema::CXXInvalid:
  5576. llvm_unreachable("invalid special member kind");
  5577. }
  5578. if (MD->getNumParams()) {
  5579. if (const ReferenceType *RT =
  5580. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  5581. ConstArg = RT->getPointeeType().isConstQualified();
  5582. }
  5583. }
  5584. bool inUnion() const { return MD->getParent()->isUnion(); }
  5585. Sema::CXXSpecialMember getEffectiveCSM() {
  5586. return ICI ? Sema::CXXInvalid : CSM;
  5587. }
  5588. /// Look up the corresponding special member in the given class.
  5589. Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
  5590. unsigned Quals, bool IsMutable) {
  5591. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  5592. ConstArg && !IsMutable);
  5593. }
  5594. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  5595. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  5596. bool shouldDeleteForField(FieldDecl *FD);
  5597. bool shouldDeleteForAllConstMembers();
  5598. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  5599. unsigned Quals);
  5600. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  5601. Sema::SpecialMemberOverloadResult *SMOR,
  5602. bool IsDtorCallInCtor);
  5603. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  5604. };
  5605. }
  5606. /// Is the given special member inaccessible when used on the given
  5607. /// sub-object.
  5608. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  5609. CXXMethodDecl *target) {
  5610. /// If we're operating on a base class, the object type is the
  5611. /// type of this special member.
  5612. QualType objectTy;
  5613. AccessSpecifier access = target->getAccess();
  5614. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  5615. objectTy = S.Context.getTypeDeclType(MD->getParent());
  5616. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  5617. // If we're operating on a field, the object type is the type of the field.
  5618. } else {
  5619. objectTy = S.Context.getTypeDeclType(target->getParent());
  5620. }
  5621. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  5622. }
  5623. /// Check whether we should delete a special member due to the implicit
  5624. /// definition containing a call to a special member of a subobject.
  5625. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  5626. Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
  5627. bool IsDtorCallInCtor) {
  5628. CXXMethodDecl *Decl = SMOR->getMethod();
  5629. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  5630. int DiagKind = -1;
  5631. if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  5632. DiagKind = !Decl ? 0 : 1;
  5633. else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  5634. DiagKind = 2;
  5635. else if (!isAccessible(Subobj, Decl))
  5636. DiagKind = 3;
  5637. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  5638. !Decl->isTrivial()) {
  5639. // A member of a union must have a trivial corresponding special member.
  5640. // As a weird special case, a destructor call from a union's constructor
  5641. // must be accessible and non-deleted, but need not be trivial. Such a
  5642. // destructor is never actually called, but is semantically checked as
  5643. // if it were.
  5644. DiagKind = 4;
  5645. }
  5646. if (DiagKind == -1)
  5647. return false;
  5648. if (Diagnose) {
  5649. if (Field) {
  5650. S.Diag(Field->getLocation(),
  5651. diag::note_deleted_special_member_class_subobject)
  5652. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  5653. << Field << DiagKind << IsDtorCallInCtor;
  5654. } else {
  5655. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  5656. S.Diag(Base->getLocStart(),
  5657. diag::note_deleted_special_member_class_subobject)
  5658. << getEffectiveCSM() << MD->getParent() << /*IsField*/false
  5659. << Base->getType() << DiagKind << IsDtorCallInCtor;
  5660. }
  5661. if (DiagKind == 1)
  5662. S.NoteDeletedFunction(Decl);
  5663. // FIXME: Explain inaccessibility if DiagKind == 3.
  5664. }
  5665. return true;
  5666. }
  5667. /// Check whether we should delete a special member function due to having a
  5668. /// direct or virtual base class or non-static data member of class type M.
  5669. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  5670. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  5671. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  5672. bool IsMutable = Field && Field->isMutable();
  5673. // C++11 [class.ctor]p5:
  5674. // -- any direct or virtual base class, or non-static data member with no
  5675. // brace-or-equal-initializer, has class type M (or array thereof) and
  5676. // either M has no default constructor or overload resolution as applied
  5677. // to M's default constructor results in an ambiguity or in a function
  5678. // that is deleted or inaccessible
  5679. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  5680. // -- a direct or virtual base class B that cannot be copied/moved because
  5681. // overload resolution, as applied to B's corresponding special member,
  5682. // results in an ambiguity or a function that is deleted or inaccessible
  5683. // from the defaulted special member
  5684. // C++11 [class.dtor]p5:
  5685. // -- any direct or virtual base class [...] has a type with a destructor
  5686. // that is deleted or inaccessible
  5687. if (!(CSM == Sema::CXXDefaultConstructor &&
  5688. Field && Field->hasInClassInitializer()) &&
  5689. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  5690. false))
  5691. return true;
  5692. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  5693. // -- any direct or virtual base class or non-static data member has a
  5694. // type with a destructor that is deleted or inaccessible
  5695. if (IsConstructor) {
  5696. Sema::SpecialMemberOverloadResult *SMOR =
  5697. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  5698. false, false, false, false, false);
  5699. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  5700. return true;
  5701. }
  5702. return false;
  5703. }
  5704. /// Check whether we should delete a special member function due to the class
  5705. /// having a particular direct or virtual base class.
  5706. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  5707. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  5708. // If program is correct, BaseClass cannot be null, but if it is, the error
  5709. // must be reported elsewhere.
  5710. if (!BaseClass)
  5711. return false;
  5712. // If we have an inheriting constructor, check whether we're calling an
  5713. // inherited constructor instead of a default constructor.
  5714. if (ICI) {
  5715. assert(CSM == Sema::CXXDefaultConstructor);
  5716. auto *BaseCtor =
  5717. ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
  5718. ->getInheritedConstructor()
  5719. .getConstructor())
  5720. .first;
  5721. if (BaseCtor) {
  5722. if (BaseCtor->isDeleted() && Diagnose) {
  5723. S.Diag(Base->getLocStart(),
  5724. diag::note_deleted_special_member_class_subobject)
  5725. << getEffectiveCSM() << MD->getParent() << /*IsField*/false
  5726. << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
  5727. S.NoteDeletedFunction(BaseCtor);
  5728. }
  5729. return BaseCtor->isDeleted();
  5730. }
  5731. }
  5732. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  5733. }
  5734. /// Check whether we should delete a special member function due to the class
  5735. /// having a particular non-static data member.
  5736. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  5737. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  5738. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  5739. if (CSM == Sema::CXXDefaultConstructor) {
  5740. // For a default constructor, all references must be initialized in-class
  5741. // and, if a union, it must have a non-const member.
  5742. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  5743. if (Diagnose)
  5744. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  5745. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  5746. return true;
  5747. }
  5748. // C++11 [class.ctor]p5: any non-variant non-static data member of
  5749. // const-qualified type (or array thereof) with no
  5750. // brace-or-equal-initializer does not have a user-provided default
  5751. // constructor.
  5752. if (!inUnion() && FieldType.isConstQualified() &&
  5753. !FD->hasInClassInitializer() &&
  5754. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  5755. if (Diagnose)
  5756. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  5757. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  5758. return true;
  5759. }
  5760. if (inUnion() && !FieldType.isConstQualified())
  5761. AllFieldsAreConst = false;
  5762. } else if (CSM == Sema::CXXCopyConstructor) {
  5763. // For a copy constructor, data members must not be of rvalue reference
  5764. // type.
  5765. if (FieldType->isRValueReferenceType()) {
  5766. if (Diagnose)
  5767. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  5768. << MD->getParent() << FD << FieldType;
  5769. return true;
  5770. }
  5771. } else if (IsAssignment) {
  5772. // For an assignment operator, data members must not be of reference type.
  5773. if (FieldType->isReferenceType()) {
  5774. if (Diagnose)
  5775. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  5776. << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
  5777. return true;
  5778. }
  5779. if (!FieldRecord && FieldType.isConstQualified()) {
  5780. // C++11 [class.copy]p23:
  5781. // -- a non-static data member of const non-class type (or array thereof)
  5782. if (Diagnose)
  5783. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  5784. << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
  5785. return true;
  5786. }
  5787. }
  5788. if (FieldRecord) {
  5789. // Some additional restrictions exist on the variant members.
  5790. if (!inUnion() && FieldRecord->isUnion() &&
  5791. FieldRecord->isAnonymousStructOrUnion()) {
  5792. bool AllVariantFieldsAreConst = true;
  5793. // FIXME: Handle anonymous unions declared within anonymous unions.
  5794. for (auto *UI : FieldRecord->fields()) {
  5795. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  5796. if (!UnionFieldType.isConstQualified())
  5797. AllVariantFieldsAreConst = false;
  5798. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  5799. if (UnionFieldRecord &&
  5800. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  5801. UnionFieldType.getCVRQualifiers()))
  5802. return true;
  5803. }
  5804. // At least one member in each anonymous union must be non-const
  5805. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  5806. !FieldRecord->field_empty()) {
  5807. if (Diagnose)
  5808. S.Diag(FieldRecord->getLocation(),
  5809. diag::note_deleted_default_ctor_all_const)
  5810. << !!ICI << MD->getParent() << /*anonymous union*/1;
  5811. return true;
  5812. }
  5813. // Don't check the implicit member of the anonymous union type.
  5814. // This is technically non-conformant, but sanity demands it.
  5815. return false;
  5816. }
  5817. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  5818. FieldType.getCVRQualifiers()))
  5819. return true;
  5820. }
  5821. return false;
  5822. }
  5823. /// C++11 [class.ctor] p5:
  5824. /// A defaulted default constructor for a class X is defined as deleted if
  5825. /// X is a union and all of its variant members are of const-qualified type.
  5826. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  5827. // This is a silly definition, because it gives an empty union a deleted
  5828. // default constructor. Don't do that.
  5829. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  5830. bool AnyFields = false;
  5831. for (auto *F : MD->getParent()->fields())
  5832. if ((AnyFields = !F->isUnnamedBitfield()))
  5833. break;
  5834. if (!AnyFields)
  5835. return false;
  5836. if (Diagnose)
  5837. S.Diag(MD->getParent()->getLocation(),
  5838. diag::note_deleted_default_ctor_all_const)
  5839. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  5840. return true;
  5841. }
  5842. return false;
  5843. }
  5844. /// Determine whether a defaulted special member function should be defined as
  5845. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  5846. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  5847. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  5848. InheritedConstructorInfo *ICI,
  5849. bool Diagnose) {
  5850. if (MD->isInvalidDecl())
  5851. return false;
  5852. CXXRecordDecl *RD = MD->getParent();
  5853. assert(!RD->isDependentType() && "do deletion after instantiation");
  5854. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  5855. return false;
  5856. // C++11 [expr.lambda.prim]p19:
  5857. // The closure type associated with a lambda-expression has a
  5858. // deleted (8.4.3) default constructor and a deleted copy
  5859. // assignment operator.
  5860. if (RD->isLambda() &&
  5861. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  5862. if (Diagnose)
  5863. Diag(RD->getLocation(), diag::note_lambda_decl);
  5864. return true;
  5865. }
  5866. // For an anonymous struct or union, the copy and assignment special members
  5867. // will never be used, so skip the check. For an anonymous union declared at
  5868. // namespace scope, the constructor and destructor are used.
  5869. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  5870. RD->isAnonymousStructOrUnion())
  5871. return false;
  5872. // C++11 [class.copy]p7, p18:
  5873. // If the class definition declares a move constructor or move assignment
  5874. // operator, an implicitly declared copy constructor or copy assignment
  5875. // operator is defined as deleted.
  5876. if (MD->isImplicit() &&
  5877. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  5878. CXXMethodDecl *UserDeclaredMove = nullptr;
  5879. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  5880. // deletion of the corresponding copy operation, not both copy operations.
  5881. // MSVC 2015 has adopted the standards conforming behavior.
  5882. bool DeletesOnlyMatchingCopy =
  5883. getLangOpts().MSVCCompat &&
  5884. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  5885. if (RD->hasUserDeclaredMoveConstructor() &&
  5886. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  5887. if (!Diagnose) return true;
  5888. // Find any user-declared move constructor.
  5889. for (auto *I : RD->ctors()) {
  5890. if (I->isMoveConstructor()) {
  5891. UserDeclaredMove = I;
  5892. break;
  5893. }
  5894. }
  5895. assert(UserDeclaredMove);
  5896. } else if (RD->hasUserDeclaredMoveAssignment() &&
  5897. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  5898. if (!Diagnose) return true;
  5899. // Find any user-declared move assignment operator.
  5900. for (auto *I : RD->methods()) {
  5901. if (I->isMoveAssignmentOperator()) {
  5902. UserDeclaredMove = I;
  5903. break;
  5904. }
  5905. }
  5906. assert(UserDeclaredMove);
  5907. }
  5908. if (UserDeclaredMove) {
  5909. Diag(UserDeclaredMove->getLocation(),
  5910. diag::note_deleted_copy_user_declared_move)
  5911. << (CSM == CXXCopyAssignment) << RD
  5912. << UserDeclaredMove->isMoveAssignmentOperator();
  5913. return true;
  5914. }
  5915. }
  5916. // Do access control from the special member function
  5917. ContextRAII MethodContext(*this, MD);
  5918. // C++11 [class.dtor]p5:
  5919. // -- for a virtual destructor, lookup of the non-array deallocation function
  5920. // results in an ambiguity or in a function that is deleted or inaccessible
  5921. if (CSM == CXXDestructor && MD->isVirtual()) {
  5922. FunctionDecl *OperatorDelete = nullptr;
  5923. DeclarationName Name =
  5924. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  5925. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  5926. OperatorDelete, /*Diagnose*/false)) {
  5927. if (Diagnose)
  5928. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  5929. return true;
  5930. }
  5931. }
  5932. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  5933. for (auto &BI : RD->bases())
  5934. if ((SMI.IsAssignment || !BI.isVirtual()) &&
  5935. SMI.shouldDeleteForBase(&BI))
  5936. return true;
  5937. // Per DR1611, do not consider virtual bases of constructors of abstract
  5938. // classes, since we are not going to construct them. For assignment
  5939. // operators, we only assign (and thus only consider) direct bases.
  5940. if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
  5941. for (auto &BI : RD->vbases())
  5942. if (SMI.shouldDeleteForBase(&BI))
  5943. return true;
  5944. }
  5945. for (auto *FI : RD->fields())
  5946. if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
  5947. SMI.shouldDeleteForField(FI))
  5948. return true;
  5949. if (SMI.shouldDeleteForAllConstMembers())
  5950. return true;
  5951. if (getLangOpts().CUDA) {
  5952. // We should delete the special member in CUDA mode if target inference
  5953. // failed.
  5954. return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
  5955. Diagnose);
  5956. }
  5957. return false;
  5958. }
  5959. /// Perform lookup for a special member of the specified kind, and determine
  5960. /// whether it is trivial. If the triviality can be determined without the
  5961. /// lookup, skip it. This is intended for use when determining whether a
  5962. /// special member of a containing object is trivial, and thus does not ever
  5963. /// perform overload resolution for default constructors.
  5964. ///
  5965. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  5966. /// member that was most likely to be intended to be trivial, if any.
  5967. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  5968. Sema::CXXSpecialMember CSM, unsigned Quals,
  5969. bool ConstRHS, CXXMethodDecl **Selected) {
  5970. if (Selected)
  5971. *Selected = nullptr;
  5972. switch (CSM) {
  5973. case Sema::CXXInvalid:
  5974. llvm_unreachable("not a special member");
  5975. case Sema::CXXDefaultConstructor:
  5976. // C++11 [class.ctor]p5:
  5977. // A default constructor is trivial if:
  5978. // - all the [direct subobjects] have trivial default constructors
  5979. //
  5980. // Note, no overload resolution is performed in this case.
  5981. if (RD->hasTrivialDefaultConstructor())
  5982. return true;
  5983. if (Selected) {
  5984. // If there's a default constructor which could have been trivial, dig it
  5985. // out. Otherwise, if there's any user-provided default constructor, point
  5986. // to that as an example of why there's not a trivial one.
  5987. CXXConstructorDecl *DefCtor = nullptr;
  5988. if (RD->needsImplicitDefaultConstructor())
  5989. S.DeclareImplicitDefaultConstructor(RD);
  5990. for (auto *CI : RD->ctors()) {
  5991. if (!CI->isDefaultConstructor())
  5992. continue;
  5993. DefCtor = CI;
  5994. if (!DefCtor->isUserProvided())
  5995. break;
  5996. }
  5997. *Selected = DefCtor;
  5998. }
  5999. return false;
  6000. case Sema::CXXDestructor:
  6001. // C++11 [class.dtor]p5:
  6002. // A destructor is trivial if:
  6003. // - all the direct [subobjects] have trivial destructors
  6004. if (RD->hasTrivialDestructor())
  6005. return true;
  6006. if (Selected) {
  6007. if (RD->needsImplicitDestructor())
  6008. S.DeclareImplicitDestructor(RD);
  6009. *Selected = RD->getDestructor();
  6010. }
  6011. return false;
  6012. case Sema::CXXCopyConstructor:
  6013. // C++11 [class.copy]p12:
  6014. // A copy constructor is trivial if:
  6015. // - the constructor selected to copy each direct [subobject] is trivial
  6016. if (RD->hasTrivialCopyConstructor()) {
  6017. if (Quals == Qualifiers::Const)
  6018. // We must either select the trivial copy constructor or reach an
  6019. // ambiguity; no need to actually perform overload resolution.
  6020. return true;
  6021. } else if (!Selected) {
  6022. return false;
  6023. }
  6024. // In C++98, we are not supposed to perform overload resolution here, but we
  6025. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  6026. // cases like B as having a non-trivial copy constructor:
  6027. // struct A { template<typename T> A(T&); };
  6028. // struct B { mutable A a; };
  6029. goto NeedOverloadResolution;
  6030. case Sema::CXXCopyAssignment:
  6031. // C++11 [class.copy]p25:
  6032. // A copy assignment operator is trivial if:
  6033. // - the assignment operator selected to copy each direct [subobject] is
  6034. // trivial
  6035. if (RD->hasTrivialCopyAssignment()) {
  6036. if (Quals == Qualifiers::Const)
  6037. return true;
  6038. } else if (!Selected) {
  6039. return false;
  6040. }
  6041. // In C++98, we are not supposed to perform overload resolution here, but we
  6042. // treat that as a language defect.
  6043. goto NeedOverloadResolution;
  6044. case Sema::CXXMoveConstructor:
  6045. case Sema::CXXMoveAssignment:
  6046. NeedOverloadResolution:
  6047. Sema::SpecialMemberOverloadResult *SMOR =
  6048. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  6049. // The standard doesn't describe how to behave if the lookup is ambiguous.
  6050. // We treat it as not making the member non-trivial, just like the standard
  6051. // mandates for the default constructor. This should rarely matter, because
  6052. // the member will also be deleted.
  6053. if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  6054. return true;
  6055. if (!SMOR->getMethod()) {
  6056. assert(SMOR->getKind() ==
  6057. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  6058. return false;
  6059. }
  6060. // We deliberately don't check if we found a deleted special member. We're
  6061. // not supposed to!
  6062. if (Selected)
  6063. *Selected = SMOR->getMethod();
  6064. return SMOR->getMethod()->isTrivial();
  6065. }
  6066. llvm_unreachable("unknown special method kind");
  6067. }
  6068. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  6069. for (auto *CI : RD->ctors())
  6070. if (!CI->isImplicit())
  6071. return CI;
  6072. // Look for constructor templates.
  6073. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  6074. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  6075. if (CXXConstructorDecl *CD =
  6076. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  6077. return CD;
  6078. }
  6079. return nullptr;
  6080. }
  6081. /// The kind of subobject we are checking for triviality. The values of this
  6082. /// enumeration are used in diagnostics.
  6083. enum TrivialSubobjectKind {
  6084. /// The subobject is a base class.
  6085. TSK_BaseClass,
  6086. /// The subobject is a non-static data member.
  6087. TSK_Field,
  6088. /// The object is actually the complete object.
  6089. TSK_CompleteObject
  6090. };
  6091. /// Check whether the special member selected for a given type would be trivial.
  6092. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  6093. QualType SubType, bool ConstRHS,
  6094. Sema::CXXSpecialMember CSM,
  6095. TrivialSubobjectKind Kind,
  6096. bool Diagnose) {
  6097. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  6098. if (!SubRD)
  6099. return true;
  6100. CXXMethodDecl *Selected;
  6101. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  6102. ConstRHS, Diagnose ? &Selected : nullptr))
  6103. return true;
  6104. if (Diagnose) {
  6105. if (ConstRHS)
  6106. SubType.addConst();
  6107. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  6108. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  6109. << Kind << SubType.getUnqualifiedType();
  6110. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  6111. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  6112. } else if (!Selected)
  6113. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  6114. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  6115. else if (Selected->isUserProvided()) {
  6116. if (Kind == TSK_CompleteObject)
  6117. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  6118. << Kind << SubType.getUnqualifiedType() << CSM;
  6119. else {
  6120. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  6121. << Kind << SubType.getUnqualifiedType() << CSM;
  6122. S.Diag(Selected->getLocation(), diag::note_declared_at);
  6123. }
  6124. } else {
  6125. if (Kind != TSK_CompleteObject)
  6126. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  6127. << Kind << SubType.getUnqualifiedType() << CSM;
  6128. // Explain why the defaulted or deleted special member isn't trivial.
  6129. S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
  6130. }
  6131. }
  6132. return false;
  6133. }
  6134. /// Check whether the members of a class type allow a special member to be
  6135. /// trivial.
  6136. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  6137. Sema::CXXSpecialMember CSM,
  6138. bool ConstArg, bool Diagnose) {
  6139. for (const auto *FI : RD->fields()) {
  6140. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  6141. continue;
  6142. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  6143. // Pretend anonymous struct or union members are members of this class.
  6144. if (FI->isAnonymousStructOrUnion()) {
  6145. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  6146. CSM, ConstArg, Diagnose))
  6147. return false;
  6148. continue;
  6149. }
  6150. // C++11 [class.ctor]p5:
  6151. // A default constructor is trivial if [...]
  6152. // -- no non-static data member of its class has a
  6153. // brace-or-equal-initializer
  6154. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  6155. if (Diagnose)
  6156. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  6157. return false;
  6158. }
  6159. // Objective C ARC 4.3.5:
  6160. // [...] nontrivally ownership-qualified types are [...] not trivially
  6161. // default constructible, copy constructible, move constructible, copy
  6162. // assignable, move assignable, or destructible [...]
  6163. if (S.getLangOpts().ObjCAutoRefCount &&
  6164. FieldType.hasNonTrivialObjCLifetime()) {
  6165. if (Diagnose)
  6166. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  6167. << RD << FieldType.getObjCLifetime();
  6168. return false;
  6169. }
  6170. bool ConstRHS = ConstArg && !FI->isMutable();
  6171. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  6172. CSM, TSK_Field, Diagnose))
  6173. return false;
  6174. }
  6175. return true;
  6176. }
  6177. /// Diagnose why the specified class does not have a trivial special member of
  6178. /// the given kind.
  6179. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  6180. QualType Ty = Context.getRecordType(RD);
  6181. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  6182. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  6183. TSK_CompleteObject, /*Diagnose*/true);
  6184. }
  6185. /// Determine whether a defaulted or deleted special member function is trivial,
  6186. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  6187. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  6188. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  6189. bool Diagnose) {
  6190. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  6191. CXXRecordDecl *RD = MD->getParent();
  6192. bool ConstArg = false;
  6193. // C++11 [class.copy]p12, p25: [DR1593]
  6194. // A [special member] is trivial if [...] its parameter-type-list is
  6195. // equivalent to the parameter-type-list of an implicit declaration [...]
  6196. switch (CSM) {
  6197. case CXXDefaultConstructor:
  6198. case CXXDestructor:
  6199. // Trivial default constructors and destructors cannot have parameters.
  6200. break;
  6201. case CXXCopyConstructor:
  6202. case CXXCopyAssignment: {
  6203. // Trivial copy operations always have const, non-volatile parameter types.
  6204. ConstArg = true;
  6205. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6206. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  6207. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  6208. if (Diagnose)
  6209. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6210. << Param0->getSourceRange() << Param0->getType()
  6211. << Context.getLValueReferenceType(
  6212. Context.getRecordType(RD).withConst());
  6213. return false;
  6214. }
  6215. break;
  6216. }
  6217. case CXXMoveConstructor:
  6218. case CXXMoveAssignment: {
  6219. // Trivial move operations always have non-cv-qualified parameters.
  6220. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  6221. const RValueReferenceType *RT =
  6222. Param0->getType()->getAs<RValueReferenceType>();
  6223. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  6224. if (Diagnose)
  6225. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  6226. << Param0->getSourceRange() << Param0->getType()
  6227. << Context.getRValueReferenceType(Context.getRecordType(RD));
  6228. return false;
  6229. }
  6230. break;
  6231. }
  6232. case CXXInvalid:
  6233. llvm_unreachable("not a special member");
  6234. }
  6235. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  6236. if (Diagnose)
  6237. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  6238. diag::note_nontrivial_default_arg)
  6239. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  6240. return false;
  6241. }
  6242. if (MD->isVariadic()) {
  6243. if (Diagnose)
  6244. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  6245. return false;
  6246. }
  6247. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6248. // A copy/move [constructor or assignment operator] is trivial if
  6249. // -- the [member] selected to copy/move each direct base class subobject
  6250. // is trivial
  6251. //
  6252. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6253. // A [default constructor or destructor] is trivial if
  6254. // -- all the direct base classes have trivial [default constructors or
  6255. // destructors]
  6256. for (const auto &BI : RD->bases())
  6257. if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
  6258. ConstArg, CSM, TSK_BaseClass, Diagnose))
  6259. return false;
  6260. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  6261. // A copy/move [constructor or assignment operator] for a class X is
  6262. // trivial if
  6263. // -- for each non-static data member of X that is of class type (or array
  6264. // thereof), the constructor selected to copy/move that member is
  6265. // trivial
  6266. //
  6267. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  6268. // A [default constructor or destructor] is trivial if
  6269. // -- for all of the non-static data members of its class that are of class
  6270. // type (or array thereof), each such class has a trivial [default
  6271. // constructor or destructor]
  6272. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
  6273. return false;
  6274. // C++11 [class.dtor]p5:
  6275. // A destructor is trivial if [...]
  6276. // -- the destructor is not virtual
  6277. if (CSM == CXXDestructor && MD->isVirtual()) {
  6278. if (Diagnose)
  6279. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  6280. return false;
  6281. }
  6282. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  6283. // A [special member] for class X is trivial if [...]
  6284. // -- class X has no virtual functions and no virtual base classes
  6285. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  6286. if (!Diagnose)
  6287. return false;
  6288. if (RD->getNumVBases()) {
  6289. // Check for virtual bases. We already know that the corresponding
  6290. // member in all bases is trivial, so vbases must all be direct.
  6291. CXXBaseSpecifier &BS = *RD->vbases_begin();
  6292. assert(BS.isVirtual());
  6293. Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
  6294. return false;
  6295. }
  6296. // Must have a virtual method.
  6297. for (const auto *MI : RD->methods()) {
  6298. if (MI->isVirtual()) {
  6299. SourceLocation MLoc = MI->getLocStart();
  6300. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  6301. return false;
  6302. }
  6303. }
  6304. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  6305. }
  6306. // Looks like it's trivial!
  6307. return true;
  6308. }
  6309. namespace {
  6310. struct FindHiddenVirtualMethod {
  6311. Sema *S;
  6312. CXXMethodDecl *Method;
  6313. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  6314. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6315. private:
  6316. /// Check whether any most overriden method from MD in Methods
  6317. static bool CheckMostOverridenMethods(
  6318. const CXXMethodDecl *MD,
  6319. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  6320. if (MD->size_overridden_methods() == 0)
  6321. return Methods.count(MD->getCanonicalDecl());
  6322. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  6323. E = MD->end_overridden_methods();
  6324. I != E; ++I)
  6325. if (CheckMostOverridenMethods(*I, Methods))
  6326. return true;
  6327. return false;
  6328. }
  6329. public:
  6330. /// Member lookup function that determines whether a given C++
  6331. /// method overloads virtual methods in a base class without overriding any,
  6332. /// to be used with CXXRecordDecl::lookupInBases().
  6333. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6334. RecordDecl *BaseRecord =
  6335. Specifier->getType()->getAs<RecordType>()->getDecl();
  6336. DeclarationName Name = Method->getDeclName();
  6337. assert(Name.getNameKind() == DeclarationName::Identifier);
  6338. bool foundSameNameMethod = false;
  6339. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  6340. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6341. Path.Decls = Path.Decls.slice(1)) {
  6342. NamedDecl *D = Path.Decls.front();
  6343. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6344. MD = MD->getCanonicalDecl();
  6345. foundSameNameMethod = true;
  6346. // Interested only in hidden virtual methods.
  6347. if (!MD->isVirtual())
  6348. continue;
  6349. // If the method we are checking overrides a method from its base
  6350. // don't warn about the other overloaded methods. Clang deviates from
  6351. // GCC by only diagnosing overloads of inherited virtual functions that
  6352. // do not override any other virtual functions in the base. GCC's
  6353. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  6354. // function from a base class. These cases may be better served by a
  6355. // warning (not specific to virtual functions) on call sites when the
  6356. // call would select a different function from the base class, were it
  6357. // visible.
  6358. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  6359. if (!S->IsOverload(Method, MD, false))
  6360. return true;
  6361. // Collect the overload only if its hidden.
  6362. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  6363. overloadedMethods.push_back(MD);
  6364. }
  6365. }
  6366. if (foundSameNameMethod)
  6367. OverloadedMethods.append(overloadedMethods.begin(),
  6368. overloadedMethods.end());
  6369. return foundSameNameMethod;
  6370. }
  6371. };
  6372. } // end anonymous namespace
  6373. /// \brief Add the most overriden methods from MD to Methods
  6374. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  6375. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  6376. if (MD->size_overridden_methods() == 0)
  6377. Methods.insert(MD->getCanonicalDecl());
  6378. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  6379. E = MD->end_overridden_methods();
  6380. I != E; ++I)
  6381. AddMostOverridenMethods(*I, Methods);
  6382. }
  6383. /// \brief Check if a method overloads virtual methods in a base class without
  6384. /// overriding any.
  6385. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  6386. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6387. if (!MD->getDeclName().isIdentifier())
  6388. return;
  6389. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  6390. /*bool RecordPaths=*/false,
  6391. /*bool DetectVirtual=*/false);
  6392. FindHiddenVirtualMethod FHVM;
  6393. FHVM.Method = MD;
  6394. FHVM.S = this;
  6395. // Keep the base methods that were overriden or introduced in the subclass
  6396. // by 'using' in a set. A base method not in this set is hidden.
  6397. CXXRecordDecl *DC = MD->getParent();
  6398. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  6399. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  6400. NamedDecl *ND = *I;
  6401. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  6402. ND = shad->getTargetDecl();
  6403. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  6404. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  6405. }
  6406. if (DC->lookupInBases(FHVM, Paths))
  6407. OverloadedMethods = FHVM.OverloadedMethods;
  6408. }
  6409. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  6410. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  6411. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  6412. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  6413. PartialDiagnostic PD = PDiag(
  6414. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  6415. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  6416. Diag(overloadedMD->getLocation(), PD);
  6417. }
  6418. }
  6419. /// \brief Diagnose methods which overload virtual methods in a base class
  6420. /// without overriding any.
  6421. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  6422. if (MD->isInvalidDecl())
  6423. return;
  6424. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  6425. return;
  6426. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  6427. FindHiddenVirtualMethods(MD, OverloadedMethods);
  6428. if (!OverloadedMethods.empty()) {
  6429. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  6430. << MD << (OverloadedMethods.size() > 1);
  6431. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  6432. }
  6433. }
  6434. void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
  6435. Decl *TagDecl,
  6436. SourceLocation LBrac,
  6437. SourceLocation RBrac,
  6438. AttributeList *AttrList) {
  6439. if (!TagDecl)
  6440. return;
  6441. AdjustDeclIfTemplate(TagDecl);
  6442. for (const AttributeList* l = AttrList; l; l = l->getNext()) {
  6443. if (l->getKind() != AttributeList::AT_Visibility)
  6444. continue;
  6445. l->setInvalid();
  6446. Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
  6447. l->getName();
  6448. }
  6449. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  6450. // strict aliasing violation!
  6451. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  6452. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  6453. CheckCompletedCXXClass(
  6454. dyn_cast_or_null<CXXRecordDecl>(TagDecl));
  6455. }
  6456. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  6457. /// special functions, such as the default constructor, copy
  6458. /// constructor, or destructor, to the given C++ class (C++
  6459. /// [special]p1). This routine can only be executed just before the
  6460. /// definition of the class is complete.
  6461. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  6462. if (ClassDecl->needsImplicitDefaultConstructor()) {
  6463. ++ASTContext::NumImplicitDefaultConstructors;
  6464. if (ClassDecl->hasInheritedConstructor())
  6465. DeclareImplicitDefaultConstructor(ClassDecl);
  6466. }
  6467. if (ClassDecl->needsImplicitCopyConstructor()) {
  6468. ++ASTContext::NumImplicitCopyConstructors;
  6469. // If the properties or semantics of the copy constructor couldn't be
  6470. // determined while the class was being declared, force a declaration
  6471. // of it now.
  6472. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  6473. ClassDecl->hasInheritedConstructor())
  6474. DeclareImplicitCopyConstructor(ClassDecl);
  6475. // For the MS ABI we need to know whether the copy ctor is deleted. A
  6476. // prerequisite for deleting the implicit copy ctor is that the class has a
  6477. // move ctor or move assignment that is either user-declared or whose
  6478. // semantics are inherited from a subobject. FIXME: We should provide a more
  6479. // direct way for CodeGen to ask whether the constructor was deleted.
  6480. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  6481. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  6482. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6483. ClassDecl->hasUserDeclaredMoveAssignment() ||
  6484. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  6485. DeclareImplicitCopyConstructor(ClassDecl);
  6486. }
  6487. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  6488. ++ASTContext::NumImplicitMoveConstructors;
  6489. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  6490. ClassDecl->hasInheritedConstructor())
  6491. DeclareImplicitMoveConstructor(ClassDecl);
  6492. }
  6493. if (ClassDecl->needsImplicitCopyAssignment()) {
  6494. ++ASTContext::NumImplicitCopyAssignmentOperators;
  6495. // If we have a dynamic class, then the copy assignment operator may be
  6496. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  6497. // it shows up in the right place in the vtable and that we diagnose
  6498. // problems with the implicit exception specification.
  6499. if (ClassDecl->isDynamicClass() ||
  6500. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  6501. ClassDecl->hasInheritedAssignment())
  6502. DeclareImplicitCopyAssignment(ClassDecl);
  6503. }
  6504. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  6505. ++ASTContext::NumImplicitMoveAssignmentOperators;
  6506. // Likewise for the move assignment operator.
  6507. if (ClassDecl->isDynamicClass() ||
  6508. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  6509. ClassDecl->hasInheritedAssignment())
  6510. DeclareImplicitMoveAssignment(ClassDecl);
  6511. }
  6512. if (ClassDecl->needsImplicitDestructor()) {
  6513. ++ASTContext::NumImplicitDestructors;
  6514. // If we have a dynamic class, then the destructor may be virtual, so we
  6515. // have to declare the destructor immediately. This ensures that, e.g., it
  6516. // shows up in the right place in the vtable and that we diagnose problems
  6517. // with the implicit exception specification.
  6518. if (ClassDecl->isDynamicClass() ||
  6519. ClassDecl->needsOverloadResolutionForDestructor())
  6520. DeclareImplicitDestructor(ClassDecl);
  6521. }
  6522. }
  6523. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  6524. if (!D)
  6525. return 0;
  6526. // The order of template parameters is not important here. All names
  6527. // get added to the same scope.
  6528. SmallVector<TemplateParameterList *, 4> ParameterLists;
  6529. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6530. D = TD->getTemplatedDecl();
  6531. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  6532. ParameterLists.push_back(PSD->getTemplateParameters());
  6533. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  6534. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  6535. ParameterLists.push_back(DD->getTemplateParameterList(i));
  6536. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  6537. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  6538. ParameterLists.push_back(FTD->getTemplateParameters());
  6539. }
  6540. }
  6541. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  6542. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  6543. ParameterLists.push_back(TD->getTemplateParameterList(i));
  6544. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  6545. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  6546. ParameterLists.push_back(CTD->getTemplateParameters());
  6547. }
  6548. }
  6549. unsigned Count = 0;
  6550. for (TemplateParameterList *Params : ParameterLists) {
  6551. if (Params->size() > 0)
  6552. // Ignore explicit specializations; they don't contribute to the template
  6553. // depth.
  6554. ++Count;
  6555. for (NamedDecl *Param : *Params) {
  6556. if (Param->getDeclName()) {
  6557. S->AddDecl(Param);
  6558. IdResolver.AddDecl(Param);
  6559. }
  6560. }
  6561. }
  6562. return Count;
  6563. }
  6564. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  6565. if (!RecordD) return;
  6566. AdjustDeclIfTemplate(RecordD);
  6567. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  6568. PushDeclContext(S, Record);
  6569. }
  6570. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  6571. if (!RecordD) return;
  6572. PopDeclContext();
  6573. }
  6574. /// This is used to implement the constant expression evaluation part of the
  6575. /// attribute enable_if extension. There is nothing in standard C++ which would
  6576. /// require reentering parameters.
  6577. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  6578. if (!Param)
  6579. return;
  6580. S->AddDecl(Param);
  6581. if (Param->getDeclName())
  6582. IdResolver.AddDecl(Param);
  6583. }
  6584. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  6585. /// parsing a top-level (non-nested) C++ class, and we are now
  6586. /// parsing those parts of the given Method declaration that could
  6587. /// not be parsed earlier (C++ [class.mem]p2), such as default
  6588. /// arguments. This action should enter the scope of the given
  6589. /// Method declaration as if we had just parsed the qualified method
  6590. /// name. However, it should not bring the parameters into scope;
  6591. /// that will be performed by ActOnDelayedCXXMethodParameter.
  6592. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  6593. }
  6594. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  6595. /// C++ method declaration. We're (re-)introducing the given
  6596. /// function parameter into scope for use in parsing later parts of
  6597. /// the method declaration. For example, we could see an
  6598. /// ActOnParamDefaultArgument event for this parameter.
  6599. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  6600. if (!ParamD)
  6601. return;
  6602. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  6603. // If this parameter has an unparsed default argument, clear it out
  6604. // to make way for the parsed default argument.
  6605. if (Param->hasUnparsedDefaultArg())
  6606. Param->setDefaultArg(nullptr);
  6607. S->AddDecl(Param);
  6608. if (Param->getDeclName())
  6609. IdResolver.AddDecl(Param);
  6610. }
  6611. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  6612. /// processing the delayed method declaration for Method. The method
  6613. /// declaration is now considered finished. There may be a separate
  6614. /// ActOnStartOfFunctionDef action later (not necessarily
  6615. /// immediately!) for this method, if it was also defined inside the
  6616. /// class body.
  6617. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  6618. if (!MethodD)
  6619. return;
  6620. AdjustDeclIfTemplate(MethodD);
  6621. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  6622. // Now that we have our default arguments, check the constructor
  6623. // again. It could produce additional diagnostics or affect whether
  6624. // the class has implicitly-declared destructors, among other
  6625. // things.
  6626. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  6627. CheckConstructor(Constructor);
  6628. // Check the default arguments, which we may have added.
  6629. if (!Method->isInvalidDecl())
  6630. CheckCXXDefaultArguments(Method);
  6631. }
  6632. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  6633. /// the well-formedness of the constructor declarator @p D with type @p
  6634. /// R. If there are any errors in the declarator, this routine will
  6635. /// emit diagnostics and set the invalid bit to true. In any case, the type
  6636. /// will be updated to reflect a well-formed type for the constructor and
  6637. /// returned.
  6638. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  6639. StorageClass &SC) {
  6640. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  6641. // C++ [class.ctor]p3:
  6642. // A constructor shall not be virtual (10.3) or static (9.4). A
  6643. // constructor can be invoked for a const, volatile or const
  6644. // volatile object. A constructor shall not be declared const,
  6645. // volatile, or const volatile (9.3.2).
  6646. if (isVirtual) {
  6647. if (!D.isInvalidType())
  6648. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  6649. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  6650. << SourceRange(D.getIdentifierLoc());
  6651. D.setInvalidType();
  6652. }
  6653. if (SC == SC_Static) {
  6654. if (!D.isInvalidType())
  6655. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  6656. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  6657. << SourceRange(D.getIdentifierLoc());
  6658. D.setInvalidType();
  6659. SC = SC_None;
  6660. }
  6661. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  6662. diagnoseIgnoredQualifiers(
  6663. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  6664. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  6665. D.getDeclSpec().getRestrictSpecLoc(),
  6666. D.getDeclSpec().getAtomicSpecLoc());
  6667. D.setInvalidType();
  6668. }
  6669. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6670. if (FTI.TypeQuals != 0) {
  6671. if (FTI.TypeQuals & Qualifiers::Const)
  6672. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  6673. << "const" << SourceRange(D.getIdentifierLoc());
  6674. if (FTI.TypeQuals & Qualifiers::Volatile)
  6675. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  6676. << "volatile" << SourceRange(D.getIdentifierLoc());
  6677. if (FTI.TypeQuals & Qualifiers::Restrict)
  6678. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  6679. << "restrict" << SourceRange(D.getIdentifierLoc());
  6680. D.setInvalidType();
  6681. }
  6682. // C++0x [class.ctor]p4:
  6683. // A constructor shall not be declared with a ref-qualifier.
  6684. if (FTI.hasRefQualifier()) {
  6685. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  6686. << FTI.RefQualifierIsLValueRef
  6687. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  6688. D.setInvalidType();
  6689. }
  6690. // Rebuild the function type "R" without any type qualifiers (in
  6691. // case any of the errors above fired) and with "void" as the
  6692. // return type, since constructors don't have return types.
  6693. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6694. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  6695. return R;
  6696. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  6697. EPI.TypeQuals = 0;
  6698. EPI.RefQualifier = RQ_None;
  6699. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  6700. }
  6701. /// CheckConstructor - Checks a fully-formed constructor for
  6702. /// well-formedness, issuing any diagnostics required. Returns true if
  6703. /// the constructor declarator is invalid.
  6704. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  6705. CXXRecordDecl *ClassDecl
  6706. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  6707. if (!ClassDecl)
  6708. return Constructor->setInvalidDecl();
  6709. // C++ [class.copy]p3:
  6710. // A declaration of a constructor for a class X is ill-formed if
  6711. // its first parameter is of type (optionally cv-qualified) X and
  6712. // either there are no other parameters or else all other
  6713. // parameters have default arguments.
  6714. if (!Constructor->isInvalidDecl() &&
  6715. ((Constructor->getNumParams() == 1) ||
  6716. (Constructor->getNumParams() > 1 &&
  6717. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  6718. Constructor->getTemplateSpecializationKind()
  6719. != TSK_ImplicitInstantiation) {
  6720. QualType ParamType = Constructor->getParamDecl(0)->getType();
  6721. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  6722. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  6723. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  6724. const char *ConstRef
  6725. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  6726. : " const &";
  6727. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  6728. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  6729. // FIXME: Rather that making the constructor invalid, we should endeavor
  6730. // to fix the type.
  6731. Constructor->setInvalidDecl();
  6732. }
  6733. }
  6734. }
  6735. /// CheckDestructor - Checks a fully-formed destructor definition for
  6736. /// well-formedness, issuing any diagnostics required. Returns true
  6737. /// on error.
  6738. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  6739. CXXRecordDecl *RD = Destructor->getParent();
  6740. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  6741. SourceLocation Loc;
  6742. if (!Destructor->isImplicit())
  6743. Loc = Destructor->getLocation();
  6744. else
  6745. Loc = RD->getLocation();
  6746. // If we have a virtual destructor, look up the deallocation function
  6747. if (FunctionDecl *OperatorDelete =
  6748. FindDeallocationFunctionForDestructor(Loc, RD)) {
  6749. MarkFunctionReferenced(Loc, OperatorDelete);
  6750. Destructor->setOperatorDelete(OperatorDelete);
  6751. }
  6752. }
  6753. return false;
  6754. }
  6755. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  6756. /// the well-formednes of the destructor declarator @p D with type @p
  6757. /// R. If there are any errors in the declarator, this routine will
  6758. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  6759. /// will be updated to reflect a well-formed type for the destructor and
  6760. /// returned.
  6761. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  6762. StorageClass& SC) {
  6763. // C++ [class.dtor]p1:
  6764. // [...] A typedef-name that names a class is a class-name
  6765. // (7.1.3); however, a typedef-name that names a class shall not
  6766. // be used as the identifier in the declarator for a destructor
  6767. // declaration.
  6768. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  6769. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  6770. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  6771. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  6772. else if (const TemplateSpecializationType *TST =
  6773. DeclaratorType->getAs<TemplateSpecializationType>())
  6774. if (TST->isTypeAlias())
  6775. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  6776. << DeclaratorType << 1;
  6777. // C++ [class.dtor]p2:
  6778. // A destructor is used to destroy objects of its class type. A
  6779. // destructor takes no parameters, and no return type can be
  6780. // specified for it (not even void). The address of a destructor
  6781. // shall not be taken. A destructor shall not be static. A
  6782. // destructor can be invoked for a const, volatile or const
  6783. // volatile object. A destructor shall not be declared const,
  6784. // volatile or const volatile (9.3.2).
  6785. if (SC == SC_Static) {
  6786. if (!D.isInvalidType())
  6787. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  6788. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  6789. << SourceRange(D.getIdentifierLoc())
  6790. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6791. SC = SC_None;
  6792. }
  6793. if (!D.isInvalidType()) {
  6794. // Destructors don't have return types, but the parser will
  6795. // happily parse something like:
  6796. //
  6797. // class X {
  6798. // float ~X();
  6799. // };
  6800. //
  6801. // The return type will be eliminated later.
  6802. if (D.getDeclSpec().hasTypeSpecifier())
  6803. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  6804. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6805. << SourceRange(D.getIdentifierLoc());
  6806. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  6807. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  6808. SourceLocation(),
  6809. D.getDeclSpec().getConstSpecLoc(),
  6810. D.getDeclSpec().getVolatileSpecLoc(),
  6811. D.getDeclSpec().getRestrictSpecLoc(),
  6812. D.getDeclSpec().getAtomicSpecLoc());
  6813. D.setInvalidType();
  6814. }
  6815. }
  6816. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6817. if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
  6818. if (FTI.TypeQuals & Qualifiers::Const)
  6819. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  6820. << "const" << SourceRange(D.getIdentifierLoc());
  6821. if (FTI.TypeQuals & Qualifiers::Volatile)
  6822. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  6823. << "volatile" << SourceRange(D.getIdentifierLoc());
  6824. if (FTI.TypeQuals & Qualifiers::Restrict)
  6825. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  6826. << "restrict" << SourceRange(D.getIdentifierLoc());
  6827. D.setInvalidType();
  6828. }
  6829. // C++0x [class.dtor]p2:
  6830. // A destructor shall not be declared with a ref-qualifier.
  6831. if (FTI.hasRefQualifier()) {
  6832. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  6833. << FTI.RefQualifierIsLValueRef
  6834. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  6835. D.setInvalidType();
  6836. }
  6837. // Make sure we don't have any parameters.
  6838. if (FTIHasNonVoidParameters(FTI)) {
  6839. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  6840. // Delete the parameters.
  6841. FTI.freeParams();
  6842. D.setInvalidType();
  6843. }
  6844. // Make sure the destructor isn't variadic.
  6845. if (FTI.isVariadic) {
  6846. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  6847. D.setInvalidType();
  6848. }
  6849. // Rebuild the function type "R" without any type qualifiers or
  6850. // parameters (in case any of the errors above fired) and with
  6851. // "void" as the return type, since destructors don't have return
  6852. // types.
  6853. if (!D.isInvalidType())
  6854. return R;
  6855. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6856. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  6857. EPI.Variadic = false;
  6858. EPI.TypeQuals = 0;
  6859. EPI.RefQualifier = RQ_None;
  6860. return Context.getFunctionType(Context.VoidTy, None, EPI);
  6861. }
  6862. static void extendLeft(SourceRange &R, SourceRange Before) {
  6863. if (Before.isInvalid())
  6864. return;
  6865. R.setBegin(Before.getBegin());
  6866. if (R.getEnd().isInvalid())
  6867. R.setEnd(Before.getEnd());
  6868. }
  6869. static void extendRight(SourceRange &R, SourceRange After) {
  6870. if (After.isInvalid())
  6871. return;
  6872. if (R.getBegin().isInvalid())
  6873. R.setBegin(After.getBegin());
  6874. R.setEnd(After.getEnd());
  6875. }
  6876. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  6877. /// well-formednes of the conversion function declarator @p D with
  6878. /// type @p R. If there are any errors in the declarator, this routine
  6879. /// will emit diagnostics and return true. Otherwise, it will return
  6880. /// false. Either way, the type @p R will be updated to reflect a
  6881. /// well-formed type for the conversion operator.
  6882. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  6883. StorageClass& SC) {
  6884. // C++ [class.conv.fct]p1:
  6885. // Neither parameter types nor return type can be specified. The
  6886. // type of a conversion function (8.3.5) is "function taking no
  6887. // parameter returning conversion-type-id."
  6888. if (SC == SC_Static) {
  6889. if (!D.isInvalidType())
  6890. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  6891. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  6892. << D.getName().getSourceRange();
  6893. D.setInvalidType();
  6894. SC = SC_None;
  6895. }
  6896. TypeSourceInfo *ConvTSI = nullptr;
  6897. QualType ConvType =
  6898. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  6899. if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
  6900. // Conversion functions don't have return types, but the parser will
  6901. // happily parse something like:
  6902. //
  6903. // class X {
  6904. // float operator bool();
  6905. // };
  6906. //
  6907. // The return type will be changed later anyway.
  6908. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  6909. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6910. << SourceRange(D.getIdentifierLoc());
  6911. D.setInvalidType();
  6912. }
  6913. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6914. // Make sure we don't have any parameters.
  6915. if (Proto->getNumParams() > 0) {
  6916. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  6917. // Delete the parameters.
  6918. D.getFunctionTypeInfo().freeParams();
  6919. D.setInvalidType();
  6920. } else if (Proto->isVariadic()) {
  6921. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  6922. D.setInvalidType();
  6923. }
  6924. // Diagnose "&operator bool()" and other such nonsense. This
  6925. // is actually a gcc extension which we don't support.
  6926. if (Proto->getReturnType() != ConvType) {
  6927. bool NeedsTypedef = false;
  6928. SourceRange Before, After;
  6929. // Walk the chunks and extract information on them for our diagnostic.
  6930. bool PastFunctionChunk = false;
  6931. for (auto &Chunk : D.type_objects()) {
  6932. switch (Chunk.Kind) {
  6933. case DeclaratorChunk::Function:
  6934. if (!PastFunctionChunk) {
  6935. if (Chunk.Fun.HasTrailingReturnType) {
  6936. TypeSourceInfo *TRT = nullptr;
  6937. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  6938. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  6939. }
  6940. PastFunctionChunk = true;
  6941. break;
  6942. }
  6943. // Fall through.
  6944. case DeclaratorChunk::Array:
  6945. NeedsTypedef = true;
  6946. extendRight(After, Chunk.getSourceRange());
  6947. break;
  6948. case DeclaratorChunk::Pointer:
  6949. case DeclaratorChunk::BlockPointer:
  6950. case DeclaratorChunk::Reference:
  6951. case DeclaratorChunk::MemberPointer:
  6952. case DeclaratorChunk::Pipe:
  6953. extendLeft(Before, Chunk.getSourceRange());
  6954. break;
  6955. case DeclaratorChunk::Paren:
  6956. extendLeft(Before, Chunk.Loc);
  6957. extendRight(After, Chunk.EndLoc);
  6958. break;
  6959. }
  6960. }
  6961. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  6962. After.isValid() ? After.getBegin() :
  6963. D.getIdentifierLoc();
  6964. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  6965. DB << Before << After;
  6966. if (!NeedsTypedef) {
  6967. DB << /*don't need a typedef*/0;
  6968. // If we can provide a correct fix-it hint, do so.
  6969. if (After.isInvalid() && ConvTSI) {
  6970. SourceLocation InsertLoc =
  6971. getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
  6972. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  6973. << FixItHint::CreateInsertionFromRange(
  6974. InsertLoc, CharSourceRange::getTokenRange(Before))
  6975. << FixItHint::CreateRemoval(Before);
  6976. }
  6977. } else if (!Proto->getReturnType()->isDependentType()) {
  6978. DB << /*typedef*/1 << Proto->getReturnType();
  6979. } else if (getLangOpts().CPlusPlus11) {
  6980. DB << /*alias template*/2 << Proto->getReturnType();
  6981. } else {
  6982. DB << /*might not be fixable*/3;
  6983. }
  6984. // Recover by incorporating the other type chunks into the result type.
  6985. // Note, this does *not* change the name of the function. This is compatible
  6986. // with the GCC extension:
  6987. // struct S { &operator int(); } s;
  6988. // int &r = s.operator int(); // ok in GCC
  6989. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  6990. ConvType = Proto->getReturnType();
  6991. }
  6992. // C++ [class.conv.fct]p4:
  6993. // The conversion-type-id shall not represent a function type nor
  6994. // an array type.
  6995. if (ConvType->isArrayType()) {
  6996. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  6997. ConvType = Context.getPointerType(ConvType);
  6998. D.setInvalidType();
  6999. } else if (ConvType->isFunctionType()) {
  7000. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  7001. ConvType = Context.getPointerType(ConvType);
  7002. D.setInvalidType();
  7003. }
  7004. // Rebuild the function type "R" without any parameters (in case any
  7005. // of the errors above fired) and with the conversion type as the
  7006. // return type.
  7007. if (D.isInvalidType())
  7008. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  7009. // C++0x explicit conversion operators.
  7010. if (D.getDeclSpec().isExplicitSpecified())
  7011. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7012. getLangOpts().CPlusPlus11 ?
  7013. diag::warn_cxx98_compat_explicit_conversion_functions :
  7014. diag::ext_explicit_conversion_functions)
  7015. << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
  7016. }
  7017. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  7018. /// the declaration of the given C++ conversion function. This routine
  7019. /// is responsible for recording the conversion function in the C++
  7020. /// class, if possible.
  7021. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  7022. assert(Conversion && "Expected to receive a conversion function declaration");
  7023. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  7024. // Make sure we aren't redeclaring the conversion function.
  7025. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  7026. // C++ [class.conv.fct]p1:
  7027. // [...] A conversion function is never used to convert a
  7028. // (possibly cv-qualified) object to the (possibly cv-qualified)
  7029. // same object type (or a reference to it), to a (possibly
  7030. // cv-qualified) base class of that type (or a reference to it),
  7031. // or to (possibly cv-qualified) void.
  7032. // FIXME: Suppress this warning if the conversion function ends up being a
  7033. // virtual function that overrides a virtual function in a base class.
  7034. QualType ClassType
  7035. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7036. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  7037. ConvType = ConvTypeRef->getPointeeType();
  7038. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  7039. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  7040. /* Suppress diagnostics for instantiations. */;
  7041. else if (ConvType->isRecordType()) {
  7042. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  7043. if (ConvType == ClassType)
  7044. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  7045. << ClassType;
  7046. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  7047. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  7048. << ClassType << ConvType;
  7049. } else if (ConvType->isVoidType()) {
  7050. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  7051. << ClassType << ConvType;
  7052. }
  7053. if (FunctionTemplateDecl *ConversionTemplate
  7054. = Conversion->getDescribedFunctionTemplate())
  7055. return ConversionTemplate;
  7056. return Conversion;
  7057. }
  7058. namespace {
  7059. /// Utility class to accumulate and print a diagnostic listing the invalid
  7060. /// specifier(s) on a declaration.
  7061. struct BadSpecifierDiagnoser {
  7062. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  7063. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  7064. ~BadSpecifierDiagnoser() {
  7065. Diagnostic << Specifiers;
  7066. }
  7067. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  7068. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  7069. }
  7070. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  7071. return check(SpecLoc,
  7072. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  7073. }
  7074. void check(SourceLocation SpecLoc, const char *Spec) {
  7075. if (SpecLoc.isInvalid()) return;
  7076. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  7077. if (!Specifiers.empty()) Specifiers += " ";
  7078. Specifiers += Spec;
  7079. }
  7080. Sema &S;
  7081. Sema::SemaDiagnosticBuilder Diagnostic;
  7082. std::string Specifiers;
  7083. };
  7084. }
  7085. /// Check the validity of a declarator that we parsed for a deduction-guide.
  7086. /// These aren't actually declarators in the grammar, so we need to check that
  7087. /// the user didn't specify any pieces that are not part of the deduction-guide
  7088. /// grammar.
  7089. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  7090. StorageClass &SC) {
  7091. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  7092. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  7093. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  7094. // C++ [temp.deduct.guide]p3:
  7095. // A deduction-gide shall be declared in the same scope as the
  7096. // corresponding class template.
  7097. if (!CurContext->getRedeclContext()->Equals(
  7098. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  7099. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  7100. << GuidedTemplateDecl;
  7101. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  7102. }
  7103. auto &DS = D.getMutableDeclSpec();
  7104. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  7105. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  7106. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  7107. DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
  7108. DS.isConceptSpecified()) {
  7109. BadSpecifierDiagnoser Diagnoser(
  7110. *this, D.getIdentifierLoc(),
  7111. diag::err_deduction_guide_invalid_specifier);
  7112. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  7113. DS.ClearStorageClassSpecs();
  7114. SC = SC_None;
  7115. // 'explicit' is permitted.
  7116. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  7117. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  7118. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  7119. Diagnoser.check(DS.getConceptSpecLoc(), "concept");
  7120. DS.ClearConstexprSpec();
  7121. DS.ClearConceptSpec();
  7122. Diagnoser.check(DS.getConstSpecLoc(), "const");
  7123. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  7124. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  7125. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  7126. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  7127. DS.ClearTypeQualifiers();
  7128. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  7129. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  7130. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  7131. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  7132. DS.ClearTypeSpecType();
  7133. }
  7134. if (D.isInvalidType())
  7135. return;
  7136. // Check the declarator is simple enough.
  7137. bool FoundFunction = false;
  7138. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  7139. if (Chunk.Kind == DeclaratorChunk::Paren)
  7140. continue;
  7141. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  7142. Diag(D.getDeclSpec().getLocStart(),
  7143. diag::err_deduction_guide_with_complex_decl)
  7144. << D.getSourceRange();
  7145. break;
  7146. }
  7147. if (!Chunk.Fun.hasTrailingReturnType()) {
  7148. Diag(D.getName().getLocStart(),
  7149. diag::err_deduction_guide_no_trailing_return_type);
  7150. break;
  7151. }
  7152. // Check that the return type is written as a specialization of
  7153. // the template specified as the deduction-guide's name.
  7154. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  7155. TypeSourceInfo *TSI = nullptr;
  7156. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  7157. assert(TSI && "deduction guide has valid type but invalid return type?");
  7158. bool AcceptableReturnType = false;
  7159. bool MightInstantiateToSpecialization = false;
  7160. if (auto RetTST =
  7161. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  7162. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  7163. bool TemplateMatches =
  7164. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  7165. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  7166. AcceptableReturnType = true;
  7167. else {
  7168. // This could still instantiate to the right type, unless we know it
  7169. // names the wrong class template.
  7170. auto *TD = SpecifiedName.getAsTemplateDecl();
  7171. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  7172. !TemplateMatches);
  7173. }
  7174. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  7175. MightInstantiateToSpecialization = true;
  7176. }
  7177. if (!AcceptableReturnType) {
  7178. Diag(TSI->getTypeLoc().getLocStart(),
  7179. diag::err_deduction_guide_bad_trailing_return_type)
  7180. << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
  7181. << TSI->getTypeLoc().getSourceRange();
  7182. }
  7183. // Keep going to check that we don't have any inner declarator pieces (we
  7184. // could still have a function returning a pointer to a function).
  7185. FoundFunction = true;
  7186. }
  7187. if (D.isFunctionDefinition())
  7188. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  7189. }
  7190. //===----------------------------------------------------------------------===//
  7191. // Namespace Handling
  7192. //===----------------------------------------------------------------------===//
  7193. /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
  7194. /// reopened.
  7195. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  7196. SourceLocation Loc,
  7197. IdentifierInfo *II, bool *IsInline,
  7198. NamespaceDecl *PrevNS) {
  7199. assert(*IsInline != PrevNS->isInline());
  7200. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  7201. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  7202. // inline namespaces, with the intention of bringing names into namespace std.
  7203. //
  7204. // We support this just well enough to get that case working; this is not
  7205. // sufficient to support reopening namespaces as inline in general.
  7206. if (*IsInline && II && II->getName().startswith("__atomic") &&
  7207. S.getSourceManager().isInSystemHeader(Loc)) {
  7208. // Mark all prior declarations of the namespace as inline.
  7209. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  7210. NS = NS->getPreviousDecl())
  7211. NS->setInline(*IsInline);
  7212. // Patch up the lookup table for the containing namespace. This isn't really
  7213. // correct, but it's good enough for this particular case.
  7214. for (auto *I : PrevNS->decls())
  7215. if (auto *ND = dyn_cast<NamedDecl>(I))
  7216. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  7217. return;
  7218. }
  7219. if (PrevNS->isInline())
  7220. // The user probably just forgot the 'inline', so suggest that it
  7221. // be added back.
  7222. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  7223. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  7224. else
  7225. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  7226. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  7227. *IsInline = PrevNS->isInline();
  7228. }
  7229. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  7230. /// definition.
  7231. Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
  7232. SourceLocation InlineLoc,
  7233. SourceLocation NamespaceLoc,
  7234. SourceLocation IdentLoc,
  7235. IdentifierInfo *II,
  7236. SourceLocation LBrace,
  7237. AttributeList *AttrList,
  7238. UsingDirectiveDecl *&UD) {
  7239. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  7240. // For anonymous namespace, take the location of the left brace.
  7241. SourceLocation Loc = II ? IdentLoc : LBrace;
  7242. bool IsInline = InlineLoc.isValid();
  7243. bool IsInvalid = false;
  7244. bool IsStd = false;
  7245. bool AddToKnown = false;
  7246. Scope *DeclRegionScope = NamespcScope->getParent();
  7247. NamespaceDecl *PrevNS = nullptr;
  7248. if (II) {
  7249. // C++ [namespace.def]p2:
  7250. // The identifier in an original-namespace-definition shall not
  7251. // have been previously defined in the declarative region in
  7252. // which the original-namespace-definition appears. The
  7253. // identifier in an original-namespace-definition is the name of
  7254. // the namespace. Subsequently in that declarative region, it is
  7255. // treated as an original-namespace-name.
  7256. //
  7257. // Since namespace names are unique in their scope, and we don't
  7258. // look through using directives, just look for any ordinary names
  7259. // as if by qualified name lookup.
  7260. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
  7261. LookupQualifiedName(R, CurContext->getRedeclContext());
  7262. NamedDecl *PrevDecl =
  7263. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  7264. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  7265. if (PrevNS) {
  7266. // This is an extended namespace definition.
  7267. if (IsInline != PrevNS->isInline())
  7268. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  7269. &IsInline, PrevNS);
  7270. } else if (PrevDecl) {
  7271. // This is an invalid name redefinition.
  7272. Diag(Loc, diag::err_redefinition_different_kind)
  7273. << II;
  7274. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7275. IsInvalid = true;
  7276. // Continue on to push Namespc as current DeclContext and return it.
  7277. } else if (II->isStr("std") &&
  7278. CurContext->getRedeclContext()->isTranslationUnit()) {
  7279. // This is the first "real" definition of the namespace "std", so update
  7280. // our cache of the "std" namespace to point at this definition.
  7281. PrevNS = getStdNamespace();
  7282. IsStd = true;
  7283. AddToKnown = !IsInline;
  7284. } else {
  7285. // We've seen this namespace for the first time.
  7286. AddToKnown = !IsInline;
  7287. }
  7288. } else {
  7289. // Anonymous namespaces.
  7290. // Determine whether the parent already has an anonymous namespace.
  7291. DeclContext *Parent = CurContext->getRedeclContext();
  7292. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7293. PrevNS = TU->getAnonymousNamespace();
  7294. } else {
  7295. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  7296. PrevNS = ND->getAnonymousNamespace();
  7297. }
  7298. if (PrevNS && IsInline != PrevNS->isInline())
  7299. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  7300. &IsInline, PrevNS);
  7301. }
  7302. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  7303. StartLoc, Loc, II, PrevNS);
  7304. if (IsInvalid)
  7305. Namespc->setInvalidDecl();
  7306. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  7307. // FIXME: Should we be merging attributes?
  7308. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  7309. PushNamespaceVisibilityAttr(Attr, Loc);
  7310. if (IsStd)
  7311. StdNamespace = Namespc;
  7312. if (AddToKnown)
  7313. KnownNamespaces[Namespc] = false;
  7314. if (II) {
  7315. PushOnScopeChains(Namespc, DeclRegionScope);
  7316. } else {
  7317. // Link the anonymous namespace into its parent.
  7318. DeclContext *Parent = CurContext->getRedeclContext();
  7319. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  7320. TU->setAnonymousNamespace(Namespc);
  7321. } else {
  7322. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  7323. }
  7324. CurContext->addDecl(Namespc);
  7325. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  7326. // behaves as if it were replaced by
  7327. // namespace unique { /* empty body */ }
  7328. // using namespace unique;
  7329. // namespace unique { namespace-body }
  7330. // where all occurrences of 'unique' in a translation unit are
  7331. // replaced by the same identifier and this identifier differs
  7332. // from all other identifiers in the entire program.
  7333. // We just create the namespace with an empty name and then add an
  7334. // implicit using declaration, just like the standard suggests.
  7335. //
  7336. // CodeGen enforces the "universally unique" aspect by giving all
  7337. // declarations semantically contained within an anonymous
  7338. // namespace internal linkage.
  7339. if (!PrevNS) {
  7340. UD = UsingDirectiveDecl::Create(Context, Parent,
  7341. /* 'using' */ LBrace,
  7342. /* 'namespace' */ SourceLocation(),
  7343. /* qualifier */ NestedNameSpecifierLoc(),
  7344. /* identifier */ SourceLocation(),
  7345. Namespc,
  7346. /* Ancestor */ Parent);
  7347. UD->setImplicit();
  7348. Parent->addDecl(UD);
  7349. }
  7350. }
  7351. ActOnDocumentableDecl(Namespc);
  7352. // Although we could have an invalid decl (i.e. the namespace name is a
  7353. // redefinition), push it as current DeclContext and try to continue parsing.
  7354. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  7355. // for the namespace has the declarations that showed up in that particular
  7356. // namespace definition.
  7357. PushDeclContext(NamespcScope, Namespc);
  7358. return Namespc;
  7359. }
  7360. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  7361. /// is a namespace alias, returns the namespace it points to.
  7362. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  7363. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  7364. return AD->getNamespace();
  7365. return dyn_cast_or_null<NamespaceDecl>(D);
  7366. }
  7367. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  7368. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  7369. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  7370. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  7371. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  7372. Namespc->setRBraceLoc(RBrace);
  7373. PopDeclContext();
  7374. if (Namespc->hasAttr<VisibilityAttr>())
  7375. PopPragmaVisibility(true, RBrace);
  7376. }
  7377. CXXRecordDecl *Sema::getStdBadAlloc() const {
  7378. return cast_or_null<CXXRecordDecl>(
  7379. StdBadAlloc.get(Context.getExternalSource()));
  7380. }
  7381. EnumDecl *Sema::getStdAlignValT() const {
  7382. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  7383. }
  7384. NamespaceDecl *Sema::getStdNamespace() const {
  7385. return cast_or_null<NamespaceDecl>(
  7386. StdNamespace.get(Context.getExternalSource()));
  7387. }
  7388. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  7389. if (!StdExperimentalNamespaceCache) {
  7390. if (auto Std = getStdNamespace()) {
  7391. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  7392. SourceLocation(), LookupNamespaceName);
  7393. if (!LookupQualifiedName(Result, Std) ||
  7394. !(StdExperimentalNamespaceCache =
  7395. Result.getAsSingle<NamespaceDecl>()))
  7396. Result.suppressDiagnostics();
  7397. }
  7398. }
  7399. return StdExperimentalNamespaceCache;
  7400. }
  7401. /// \brief Retrieve the special "std" namespace, which may require us to
  7402. /// implicitly define the namespace.
  7403. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  7404. if (!StdNamespace) {
  7405. // The "std" namespace has not yet been defined, so build one implicitly.
  7406. StdNamespace = NamespaceDecl::Create(Context,
  7407. Context.getTranslationUnitDecl(),
  7408. /*Inline=*/false,
  7409. SourceLocation(), SourceLocation(),
  7410. &PP.getIdentifierTable().get("std"),
  7411. /*PrevDecl=*/nullptr);
  7412. getStdNamespace()->setImplicit(true);
  7413. }
  7414. return getStdNamespace();
  7415. }
  7416. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  7417. assert(getLangOpts().CPlusPlus &&
  7418. "Looking for std::initializer_list outside of C++.");
  7419. // We're looking for implicit instantiations of
  7420. // template <typename E> class std::initializer_list.
  7421. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  7422. return false;
  7423. ClassTemplateDecl *Template = nullptr;
  7424. const TemplateArgument *Arguments = nullptr;
  7425. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  7426. ClassTemplateSpecializationDecl *Specialization =
  7427. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  7428. if (!Specialization)
  7429. return false;
  7430. Template = Specialization->getSpecializedTemplate();
  7431. Arguments = Specialization->getTemplateArgs().data();
  7432. } else if (const TemplateSpecializationType *TST =
  7433. Ty->getAs<TemplateSpecializationType>()) {
  7434. Template = dyn_cast_or_null<ClassTemplateDecl>(
  7435. TST->getTemplateName().getAsTemplateDecl());
  7436. Arguments = TST->getArgs();
  7437. }
  7438. if (!Template)
  7439. return false;
  7440. if (!StdInitializerList) {
  7441. // Haven't recognized std::initializer_list yet, maybe this is it.
  7442. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  7443. if (TemplateClass->getIdentifier() !=
  7444. &PP.getIdentifierTable().get("initializer_list") ||
  7445. !getStdNamespace()->InEnclosingNamespaceSetOf(
  7446. TemplateClass->getDeclContext()))
  7447. return false;
  7448. // This is a template called std::initializer_list, but is it the right
  7449. // template?
  7450. TemplateParameterList *Params = Template->getTemplateParameters();
  7451. if (Params->getMinRequiredArguments() != 1)
  7452. return false;
  7453. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  7454. return false;
  7455. // It's the right template.
  7456. StdInitializerList = Template;
  7457. }
  7458. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  7459. return false;
  7460. // This is an instance of std::initializer_list. Find the argument type.
  7461. if (Element)
  7462. *Element = Arguments[0].getAsType();
  7463. return true;
  7464. }
  7465. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  7466. NamespaceDecl *Std = S.getStdNamespace();
  7467. if (!Std) {
  7468. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  7469. return nullptr;
  7470. }
  7471. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  7472. Loc, Sema::LookupOrdinaryName);
  7473. if (!S.LookupQualifiedName(Result, Std)) {
  7474. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  7475. return nullptr;
  7476. }
  7477. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  7478. if (!Template) {
  7479. Result.suppressDiagnostics();
  7480. // We found something weird. Complain about the first thing we found.
  7481. NamedDecl *Found = *Result.begin();
  7482. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  7483. return nullptr;
  7484. }
  7485. // We found some template called std::initializer_list. Now verify that it's
  7486. // correct.
  7487. TemplateParameterList *Params = Template->getTemplateParameters();
  7488. if (Params->getMinRequiredArguments() != 1 ||
  7489. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  7490. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  7491. return nullptr;
  7492. }
  7493. return Template;
  7494. }
  7495. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  7496. if (!StdInitializerList) {
  7497. StdInitializerList = LookupStdInitializerList(*this, Loc);
  7498. if (!StdInitializerList)
  7499. return QualType();
  7500. }
  7501. TemplateArgumentListInfo Args(Loc, Loc);
  7502. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  7503. Context.getTrivialTypeSourceInfo(Element,
  7504. Loc)));
  7505. return Context.getCanonicalType(
  7506. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  7507. }
  7508. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  7509. // C++ [dcl.init.list]p2:
  7510. // A constructor is an initializer-list constructor if its first parameter
  7511. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  7512. // std::initializer_list<E> for some type E, and either there are no other
  7513. // parameters or else all other parameters have default arguments.
  7514. if (Ctor->getNumParams() < 1 ||
  7515. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  7516. return false;
  7517. QualType ArgType = Ctor->getParamDecl(0)->getType();
  7518. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  7519. ArgType = RT->getPointeeType().getUnqualifiedType();
  7520. return isStdInitializerList(ArgType, nullptr);
  7521. }
  7522. /// \brief Determine whether a using statement is in a context where it will be
  7523. /// apply in all contexts.
  7524. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  7525. switch (CurContext->getDeclKind()) {
  7526. case Decl::TranslationUnit:
  7527. return true;
  7528. case Decl::LinkageSpec:
  7529. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  7530. default:
  7531. return false;
  7532. }
  7533. }
  7534. namespace {
  7535. // Callback to only accept typo corrections that are namespaces.
  7536. class NamespaceValidatorCCC : public CorrectionCandidateCallback {
  7537. public:
  7538. bool ValidateCandidate(const TypoCorrection &candidate) override {
  7539. if (NamedDecl *ND = candidate.getCorrectionDecl())
  7540. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  7541. return false;
  7542. }
  7543. };
  7544. }
  7545. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  7546. CXXScopeSpec &SS,
  7547. SourceLocation IdentLoc,
  7548. IdentifierInfo *Ident) {
  7549. R.clear();
  7550. if (TypoCorrection Corrected =
  7551. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
  7552. llvm::make_unique<NamespaceValidatorCCC>(),
  7553. Sema::CTK_ErrorRecovery)) {
  7554. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  7555. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  7556. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  7557. Ident->getName().equals(CorrectedStr);
  7558. S.diagnoseTypo(Corrected,
  7559. S.PDiag(diag::err_using_directive_member_suggest)
  7560. << Ident << DC << DroppedSpecifier << SS.getRange(),
  7561. S.PDiag(diag::note_namespace_defined_here));
  7562. } else {
  7563. S.diagnoseTypo(Corrected,
  7564. S.PDiag(diag::err_using_directive_suggest) << Ident,
  7565. S.PDiag(diag::note_namespace_defined_here));
  7566. }
  7567. R.addDecl(Corrected.getFoundDecl());
  7568. return true;
  7569. }
  7570. return false;
  7571. }
  7572. Decl *Sema::ActOnUsingDirective(Scope *S,
  7573. SourceLocation UsingLoc,
  7574. SourceLocation NamespcLoc,
  7575. CXXScopeSpec &SS,
  7576. SourceLocation IdentLoc,
  7577. IdentifierInfo *NamespcName,
  7578. AttributeList *AttrList) {
  7579. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  7580. assert(NamespcName && "Invalid NamespcName.");
  7581. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  7582. // This can only happen along a recovery path.
  7583. while (S->isTemplateParamScope())
  7584. S = S->getParent();
  7585. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  7586. UsingDirectiveDecl *UDir = nullptr;
  7587. NestedNameSpecifier *Qualifier = nullptr;
  7588. if (SS.isSet())
  7589. Qualifier = SS.getScopeRep();
  7590. // Lookup namespace name.
  7591. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  7592. LookupParsedName(R, S, &SS);
  7593. if (R.isAmbiguous())
  7594. return nullptr;
  7595. if (R.empty()) {
  7596. R.clear();
  7597. // Allow "using namespace std;" or "using namespace ::std;" even if
  7598. // "std" hasn't been defined yet, for GCC compatibility.
  7599. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  7600. NamespcName->isStr("std")) {
  7601. Diag(IdentLoc, diag::ext_using_undefined_std);
  7602. R.addDecl(getOrCreateStdNamespace());
  7603. R.resolveKind();
  7604. }
  7605. // Otherwise, attempt typo correction.
  7606. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  7607. }
  7608. if (!R.empty()) {
  7609. NamedDecl *Named = R.getRepresentativeDecl();
  7610. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  7611. assert(NS && "expected namespace decl");
  7612. // The use of a nested name specifier may trigger deprecation warnings.
  7613. DiagnoseUseOfDecl(Named, IdentLoc);
  7614. // C++ [namespace.udir]p1:
  7615. // A using-directive specifies that the names in the nominated
  7616. // namespace can be used in the scope in which the
  7617. // using-directive appears after the using-directive. During
  7618. // unqualified name lookup (3.4.1), the names appear as if they
  7619. // were declared in the nearest enclosing namespace which
  7620. // contains both the using-directive and the nominated
  7621. // namespace. [Note: in this context, "contains" means "contains
  7622. // directly or indirectly". ]
  7623. // Find enclosing context containing both using-directive and
  7624. // nominated namespace.
  7625. DeclContext *CommonAncestor = cast<DeclContext>(NS);
  7626. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  7627. CommonAncestor = CommonAncestor->getParent();
  7628. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  7629. SS.getWithLocInContext(Context),
  7630. IdentLoc, Named, CommonAncestor);
  7631. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  7632. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  7633. Diag(IdentLoc, diag::warn_using_directive_in_header);
  7634. }
  7635. PushUsingDirective(S, UDir);
  7636. } else {
  7637. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  7638. }
  7639. if (UDir)
  7640. ProcessDeclAttributeList(S, UDir, AttrList);
  7641. return UDir;
  7642. }
  7643. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  7644. // If the scope has an associated entity and the using directive is at
  7645. // namespace or translation unit scope, add the UsingDirectiveDecl into
  7646. // its lookup structure so qualified name lookup can find it.
  7647. DeclContext *Ctx = S->getEntity();
  7648. if (Ctx && !Ctx->isFunctionOrMethod())
  7649. Ctx->addDecl(UDir);
  7650. else
  7651. // Otherwise, it is at block scope. The using-directives will affect lookup
  7652. // only to the end of the scope.
  7653. S->PushUsingDirective(UDir);
  7654. }
  7655. Decl *Sema::ActOnUsingDeclaration(Scope *S,
  7656. AccessSpecifier AS,
  7657. SourceLocation UsingLoc,
  7658. SourceLocation TypenameLoc,
  7659. CXXScopeSpec &SS,
  7660. UnqualifiedId &Name,
  7661. SourceLocation EllipsisLoc,
  7662. AttributeList *AttrList) {
  7663. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  7664. if (SS.isEmpty()) {
  7665. Diag(Name.getLocStart(), diag::err_using_requires_qualname);
  7666. return nullptr;
  7667. }
  7668. switch (Name.getKind()) {
  7669. case UnqualifiedId::IK_ImplicitSelfParam:
  7670. case UnqualifiedId::IK_Identifier:
  7671. case UnqualifiedId::IK_OperatorFunctionId:
  7672. case UnqualifiedId::IK_LiteralOperatorId:
  7673. case UnqualifiedId::IK_ConversionFunctionId:
  7674. break;
  7675. case UnqualifiedId::IK_ConstructorName:
  7676. case UnqualifiedId::IK_ConstructorTemplateId:
  7677. // C++11 inheriting constructors.
  7678. Diag(Name.getLocStart(),
  7679. getLangOpts().CPlusPlus11 ?
  7680. diag::warn_cxx98_compat_using_decl_constructor :
  7681. diag::err_using_decl_constructor)
  7682. << SS.getRange();
  7683. if (getLangOpts().CPlusPlus11) break;
  7684. return nullptr;
  7685. case UnqualifiedId::IK_DestructorName:
  7686. Diag(Name.getLocStart(), diag::err_using_decl_destructor)
  7687. << SS.getRange();
  7688. return nullptr;
  7689. case UnqualifiedId::IK_TemplateId:
  7690. Diag(Name.getLocStart(), diag::err_using_decl_template_id)
  7691. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  7692. return nullptr;
  7693. case UnqualifiedId::IK_DeductionGuideName:
  7694. llvm_unreachable("cannot parse qualified deduction guide name");
  7695. }
  7696. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  7697. DeclarationName TargetName = TargetNameInfo.getName();
  7698. if (!TargetName)
  7699. return nullptr;
  7700. // Warn about access declarations.
  7701. if (UsingLoc.isInvalid()) {
  7702. Diag(Name.getLocStart(),
  7703. getLangOpts().CPlusPlus11 ? diag::err_access_decl
  7704. : diag::warn_access_decl_deprecated)
  7705. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  7706. }
  7707. if (EllipsisLoc.isInvalid()) {
  7708. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  7709. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  7710. return nullptr;
  7711. } else {
  7712. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  7713. !TargetNameInfo.containsUnexpandedParameterPack()) {
  7714. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  7715. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  7716. EllipsisLoc = SourceLocation();
  7717. }
  7718. }
  7719. NamedDecl *UD =
  7720. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  7721. SS, TargetNameInfo, EllipsisLoc, AttrList,
  7722. /*IsInstantiation*/false);
  7723. if (UD)
  7724. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  7725. return UD;
  7726. }
  7727. /// \brief Determine whether a using declaration considers the given
  7728. /// declarations as "equivalent", e.g., if they are redeclarations of
  7729. /// the same entity or are both typedefs of the same type.
  7730. static bool
  7731. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  7732. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  7733. return true;
  7734. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  7735. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  7736. return Context.hasSameType(TD1->getUnderlyingType(),
  7737. TD2->getUnderlyingType());
  7738. return false;
  7739. }
  7740. /// Determines whether to create a using shadow decl for a particular
  7741. /// decl, given the set of decls existing prior to this using lookup.
  7742. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  7743. const LookupResult &Previous,
  7744. UsingShadowDecl *&PrevShadow) {
  7745. // Diagnose finding a decl which is not from a base class of the
  7746. // current class. We do this now because there are cases where this
  7747. // function will silently decide not to build a shadow decl, which
  7748. // will pre-empt further diagnostics.
  7749. //
  7750. // We don't need to do this in C++11 because we do the check once on
  7751. // the qualifier.
  7752. //
  7753. // FIXME: diagnose the following if we care enough:
  7754. // struct A { int foo; };
  7755. // struct B : A { using A::foo; };
  7756. // template <class T> struct C : A {};
  7757. // template <class T> struct D : C<T> { using B::foo; } // <---
  7758. // This is invalid (during instantiation) in C++03 because B::foo
  7759. // resolves to the using decl in B, which is not a base class of D<T>.
  7760. // We can't diagnose it immediately because C<T> is an unknown
  7761. // specialization. The UsingShadowDecl in D<T> then points directly
  7762. // to A::foo, which will look well-formed when we instantiate.
  7763. // The right solution is to not collapse the shadow-decl chain.
  7764. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  7765. DeclContext *OrigDC = Orig->getDeclContext();
  7766. // Handle enums and anonymous structs.
  7767. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  7768. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  7769. while (OrigRec->isAnonymousStructOrUnion())
  7770. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  7771. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  7772. if (OrigDC == CurContext) {
  7773. Diag(Using->getLocation(),
  7774. diag::err_using_decl_nested_name_specifier_is_current_class)
  7775. << Using->getQualifierLoc().getSourceRange();
  7776. Diag(Orig->getLocation(), diag::note_using_decl_target);
  7777. Using->setInvalidDecl();
  7778. return true;
  7779. }
  7780. Diag(Using->getQualifierLoc().getBeginLoc(),
  7781. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  7782. << Using->getQualifier()
  7783. << cast<CXXRecordDecl>(CurContext)
  7784. << Using->getQualifierLoc().getSourceRange();
  7785. Diag(Orig->getLocation(), diag::note_using_decl_target);
  7786. Using->setInvalidDecl();
  7787. return true;
  7788. }
  7789. }
  7790. if (Previous.empty()) return false;
  7791. NamedDecl *Target = Orig;
  7792. if (isa<UsingShadowDecl>(Target))
  7793. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  7794. // If the target happens to be one of the previous declarations, we
  7795. // don't have a conflict.
  7796. //
  7797. // FIXME: but we might be increasing its access, in which case we
  7798. // should redeclare it.
  7799. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  7800. bool FoundEquivalentDecl = false;
  7801. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7802. I != E; ++I) {
  7803. NamedDecl *D = (*I)->getUnderlyingDecl();
  7804. // We can have UsingDecls in our Previous results because we use the same
  7805. // LookupResult for checking whether the UsingDecl itself is a valid
  7806. // redeclaration.
  7807. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
  7808. continue;
  7809. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  7810. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  7811. PrevShadow = Shadow;
  7812. FoundEquivalentDecl = true;
  7813. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  7814. // We don't conflict with an existing using shadow decl of an equivalent
  7815. // declaration, but we're not a redeclaration of it.
  7816. FoundEquivalentDecl = true;
  7817. }
  7818. if (isVisible(D))
  7819. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  7820. }
  7821. if (FoundEquivalentDecl)
  7822. return false;
  7823. if (FunctionDecl *FD = Target->getAsFunction()) {
  7824. NamedDecl *OldDecl = nullptr;
  7825. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  7826. /*IsForUsingDecl*/ true)) {
  7827. case Ovl_Overload:
  7828. return false;
  7829. case Ovl_NonFunction:
  7830. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  7831. break;
  7832. // We found a decl with the exact signature.
  7833. case Ovl_Match:
  7834. // If we're in a record, we want to hide the target, so we
  7835. // return true (without a diagnostic) to tell the caller not to
  7836. // build a shadow decl.
  7837. if (CurContext->isRecord())
  7838. return true;
  7839. // If we're not in a record, this is an error.
  7840. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  7841. break;
  7842. }
  7843. Diag(Target->getLocation(), diag::note_using_decl_target);
  7844. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  7845. Using->setInvalidDecl();
  7846. return true;
  7847. }
  7848. // Target is not a function.
  7849. if (isa<TagDecl>(Target)) {
  7850. // No conflict between a tag and a non-tag.
  7851. if (!Tag) return false;
  7852. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  7853. Diag(Target->getLocation(), diag::note_using_decl_target);
  7854. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  7855. Using->setInvalidDecl();
  7856. return true;
  7857. }
  7858. // No conflict between a tag and a non-tag.
  7859. if (!NonTag) return false;
  7860. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  7861. Diag(Target->getLocation(), diag::note_using_decl_target);
  7862. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  7863. Using->setInvalidDecl();
  7864. return true;
  7865. }
  7866. /// Determine whether a direct base class is a virtual base class.
  7867. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  7868. if (!Derived->getNumVBases())
  7869. return false;
  7870. for (auto &B : Derived->bases())
  7871. if (B.getType()->getAsCXXRecordDecl() == Base)
  7872. return B.isVirtual();
  7873. llvm_unreachable("not a direct base class");
  7874. }
  7875. /// Builds a shadow declaration corresponding to a 'using' declaration.
  7876. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  7877. UsingDecl *UD,
  7878. NamedDecl *Orig,
  7879. UsingShadowDecl *PrevDecl) {
  7880. // If we resolved to another shadow declaration, just coalesce them.
  7881. NamedDecl *Target = Orig;
  7882. if (isa<UsingShadowDecl>(Target)) {
  7883. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  7884. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  7885. }
  7886. NamedDecl *NonTemplateTarget = Target;
  7887. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  7888. NonTemplateTarget = TargetTD->getTemplatedDecl();
  7889. UsingShadowDecl *Shadow;
  7890. if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
  7891. bool IsVirtualBase =
  7892. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  7893. UD->getQualifier()->getAsRecordDecl());
  7894. Shadow = ConstructorUsingShadowDecl::Create(
  7895. Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
  7896. } else {
  7897. Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
  7898. Target);
  7899. }
  7900. UD->addShadowDecl(Shadow);
  7901. Shadow->setAccess(UD->getAccess());
  7902. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  7903. Shadow->setInvalidDecl();
  7904. Shadow->setPreviousDecl(PrevDecl);
  7905. if (S)
  7906. PushOnScopeChains(Shadow, S);
  7907. else
  7908. CurContext->addDecl(Shadow);
  7909. return Shadow;
  7910. }
  7911. /// Hides a using shadow declaration. This is required by the current
  7912. /// using-decl implementation when a resolvable using declaration in a
  7913. /// class is followed by a declaration which would hide or override
  7914. /// one or more of the using decl's targets; for example:
  7915. ///
  7916. /// struct Base { void foo(int); };
  7917. /// struct Derived : Base {
  7918. /// using Base::foo;
  7919. /// void foo(int);
  7920. /// };
  7921. ///
  7922. /// The governing language is C++03 [namespace.udecl]p12:
  7923. ///
  7924. /// When a using-declaration brings names from a base class into a
  7925. /// derived class scope, member functions in the derived class
  7926. /// override and/or hide member functions with the same name and
  7927. /// parameter types in a base class (rather than conflicting).
  7928. ///
  7929. /// There are two ways to implement this:
  7930. /// (1) optimistically create shadow decls when they're not hidden
  7931. /// by existing declarations, or
  7932. /// (2) don't create any shadow decls (or at least don't make them
  7933. /// visible) until we've fully parsed/instantiated the class.
  7934. /// The problem with (1) is that we might have to retroactively remove
  7935. /// a shadow decl, which requires several O(n) operations because the
  7936. /// decl structures are (very reasonably) not designed for removal.
  7937. /// (2) avoids this but is very fiddly and phase-dependent.
  7938. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  7939. if (Shadow->getDeclName().getNameKind() ==
  7940. DeclarationName::CXXConversionFunctionName)
  7941. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  7942. // Remove it from the DeclContext...
  7943. Shadow->getDeclContext()->removeDecl(Shadow);
  7944. // ...and the scope, if applicable...
  7945. if (S) {
  7946. S->RemoveDecl(Shadow);
  7947. IdResolver.RemoveDecl(Shadow);
  7948. }
  7949. // ...and the using decl.
  7950. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  7951. // TODO: complain somehow if Shadow was used. It shouldn't
  7952. // be possible for this to happen, because...?
  7953. }
  7954. /// Find the base specifier for a base class with the given type.
  7955. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  7956. QualType DesiredBase,
  7957. bool &AnyDependentBases) {
  7958. // Check whether the named type is a direct base class.
  7959. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
  7960. for (auto &Base : Derived->bases()) {
  7961. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  7962. if (CanonicalDesiredBase == BaseType)
  7963. return &Base;
  7964. if (BaseType->isDependentType())
  7965. AnyDependentBases = true;
  7966. }
  7967. return nullptr;
  7968. }
  7969. namespace {
  7970. class UsingValidatorCCC : public CorrectionCandidateCallback {
  7971. public:
  7972. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  7973. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  7974. : HasTypenameKeyword(HasTypenameKeyword),
  7975. IsInstantiation(IsInstantiation), OldNNS(NNS),
  7976. RequireMemberOf(RequireMemberOf) {}
  7977. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  7978. NamedDecl *ND = Candidate.getCorrectionDecl();
  7979. // Keywords are not valid here.
  7980. if (!ND || isa<NamespaceDecl>(ND))
  7981. return false;
  7982. // Completely unqualified names are invalid for a 'using' declaration.
  7983. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  7984. return false;
  7985. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  7986. // reject.
  7987. if (RequireMemberOf) {
  7988. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  7989. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  7990. // No-one ever wants a using-declaration to name an injected-class-name
  7991. // of a base class, unless they're declaring an inheriting constructor.
  7992. ASTContext &Ctx = ND->getASTContext();
  7993. if (!Ctx.getLangOpts().CPlusPlus11)
  7994. return false;
  7995. QualType FoundType = Ctx.getRecordType(FoundRecord);
  7996. // Check that the injected-class-name is named as a member of its own
  7997. // type; we don't want to suggest 'using Derived::Base;', since that
  7998. // means something else.
  7999. NestedNameSpecifier *Specifier =
  8000. Candidate.WillReplaceSpecifier()
  8001. ? Candidate.getCorrectionSpecifier()
  8002. : OldNNS;
  8003. if (!Specifier->getAsType() ||
  8004. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  8005. return false;
  8006. // Check that this inheriting constructor declaration actually names a
  8007. // direct base class of the current class.
  8008. bool AnyDependentBases = false;
  8009. if (!findDirectBaseWithType(RequireMemberOf,
  8010. Ctx.getRecordType(FoundRecord),
  8011. AnyDependentBases) &&
  8012. !AnyDependentBases)
  8013. return false;
  8014. } else {
  8015. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  8016. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  8017. return false;
  8018. // FIXME: Check that the base class member is accessible?
  8019. }
  8020. } else {
  8021. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  8022. if (FoundRecord && FoundRecord->isInjectedClassName())
  8023. return false;
  8024. }
  8025. if (isa<TypeDecl>(ND))
  8026. return HasTypenameKeyword || !IsInstantiation;
  8027. return !HasTypenameKeyword;
  8028. }
  8029. private:
  8030. bool HasTypenameKeyword;
  8031. bool IsInstantiation;
  8032. NestedNameSpecifier *OldNNS;
  8033. CXXRecordDecl *RequireMemberOf;
  8034. };
  8035. } // end anonymous namespace
  8036. /// Builds a using declaration.
  8037. ///
  8038. /// \param IsInstantiation - Whether this call arises from an
  8039. /// instantiation of an unresolved using declaration. We treat
  8040. /// the lookup differently for these declarations.
  8041. NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
  8042. SourceLocation UsingLoc,
  8043. bool HasTypenameKeyword,
  8044. SourceLocation TypenameLoc,
  8045. CXXScopeSpec &SS,
  8046. DeclarationNameInfo NameInfo,
  8047. SourceLocation EllipsisLoc,
  8048. AttributeList *AttrList,
  8049. bool IsInstantiation) {
  8050. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  8051. SourceLocation IdentLoc = NameInfo.getLoc();
  8052. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  8053. // FIXME: We ignore attributes for now.
  8054. // For an inheriting constructor declaration, the name of the using
  8055. // declaration is the name of a constructor in this class, not in the
  8056. // base class.
  8057. DeclarationNameInfo UsingName = NameInfo;
  8058. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  8059. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  8060. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8061. Context.getCanonicalType(Context.getRecordType(RD))));
  8062. // Do the redeclaration lookup in the current scope.
  8063. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  8064. ForRedeclaration);
  8065. Previous.setHideTags(false);
  8066. if (S) {
  8067. LookupName(Previous, S);
  8068. // It is really dumb that we have to do this.
  8069. LookupResult::Filter F = Previous.makeFilter();
  8070. while (F.hasNext()) {
  8071. NamedDecl *D = F.next();
  8072. if (!isDeclInScope(D, CurContext, S))
  8073. F.erase();
  8074. // If we found a local extern declaration that's not ordinarily visible,
  8075. // and this declaration is being added to a non-block scope, ignore it.
  8076. // We're only checking for scope conflicts here, not also for violations
  8077. // of the linkage rules.
  8078. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  8079. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  8080. F.erase();
  8081. }
  8082. F.done();
  8083. } else {
  8084. assert(IsInstantiation && "no scope in non-instantiation");
  8085. if (CurContext->isRecord())
  8086. LookupQualifiedName(Previous, CurContext);
  8087. else {
  8088. // No redeclaration check is needed here; in non-member contexts we
  8089. // diagnosed all possible conflicts with other using-declarations when
  8090. // building the template:
  8091. //
  8092. // For a dependent non-type using declaration, the only valid case is
  8093. // if we instantiate to a single enumerator. We check for conflicts
  8094. // between shadow declarations we introduce, and we check in the template
  8095. // definition for conflicts between a non-type using declaration and any
  8096. // other declaration, which together covers all cases.
  8097. //
  8098. // A dependent typename using declaration will never successfully
  8099. // instantiate, since it will always name a class member, so we reject
  8100. // that in the template definition.
  8101. }
  8102. }
  8103. // Check for invalid redeclarations.
  8104. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  8105. SS, IdentLoc, Previous))
  8106. return nullptr;
  8107. // Check for bad qualifiers.
  8108. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  8109. IdentLoc))
  8110. return nullptr;
  8111. DeclContext *LookupContext = computeDeclContext(SS);
  8112. NamedDecl *D;
  8113. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8114. if (!LookupContext || EllipsisLoc.isValid()) {
  8115. if (HasTypenameKeyword) {
  8116. // FIXME: not all declaration name kinds are legal here
  8117. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  8118. UsingLoc, TypenameLoc,
  8119. QualifierLoc,
  8120. IdentLoc, NameInfo.getName(),
  8121. EllipsisLoc);
  8122. } else {
  8123. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  8124. QualifierLoc, NameInfo, EllipsisLoc);
  8125. }
  8126. D->setAccess(AS);
  8127. CurContext->addDecl(D);
  8128. return D;
  8129. }
  8130. auto Build = [&](bool Invalid) {
  8131. UsingDecl *UD =
  8132. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  8133. UsingName, HasTypenameKeyword);
  8134. UD->setAccess(AS);
  8135. CurContext->addDecl(UD);
  8136. UD->setInvalidDecl(Invalid);
  8137. return UD;
  8138. };
  8139. auto BuildInvalid = [&]{ return Build(true); };
  8140. auto BuildValid = [&]{ return Build(false); };
  8141. if (RequireCompleteDeclContext(SS, LookupContext))
  8142. return BuildInvalid();
  8143. // Look up the target name.
  8144. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8145. // Unlike most lookups, we don't always want to hide tag
  8146. // declarations: tag names are visible through the using declaration
  8147. // even if hidden by ordinary names, *except* in a dependent context
  8148. // where it's important for the sanity of two-phase lookup.
  8149. if (!IsInstantiation)
  8150. R.setHideTags(false);
  8151. // For the purposes of this lookup, we have a base object type
  8152. // equal to that of the current context.
  8153. if (CurContext->isRecord()) {
  8154. R.setBaseObjectType(
  8155. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  8156. }
  8157. LookupQualifiedName(R, LookupContext);
  8158. // Try to correct typos if possible. If constructor name lookup finds no
  8159. // results, that means the named class has no explicit constructors, and we
  8160. // suppressed declaring implicit ones (probably because it's dependent or
  8161. // invalid).
  8162. if (R.empty() &&
  8163. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  8164. // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
  8165. // it will believe that glibc provides a ::gets in cases where it does not,
  8166. // and will try to pull it into namespace std with a using-declaration.
  8167. // Just ignore the using-declaration in that case.
  8168. auto *II = NameInfo.getName().getAsIdentifierInfo();
  8169. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  8170. CurContext->isStdNamespace() &&
  8171. isa<TranslationUnitDecl>(LookupContext) &&
  8172. getSourceManager().isInSystemHeader(UsingLoc))
  8173. return nullptr;
  8174. if (TypoCorrection Corrected = CorrectTypo(
  8175. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  8176. llvm::make_unique<UsingValidatorCCC>(
  8177. HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  8178. dyn_cast<CXXRecordDecl>(CurContext)),
  8179. CTK_ErrorRecovery)) {
  8180. // We reject candidates where DroppedSpecifier == true, hence the
  8181. // literal '0' below.
  8182. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  8183. << NameInfo.getName() << LookupContext << 0
  8184. << SS.getRange());
  8185. // If we picked a correction with no attached Decl we can't do anything
  8186. // useful with it, bail out.
  8187. NamedDecl *ND = Corrected.getCorrectionDecl();
  8188. if (!ND)
  8189. return BuildInvalid();
  8190. // If we corrected to an inheriting constructor, handle it as one.
  8191. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  8192. if (RD && RD->isInjectedClassName()) {
  8193. // The parent of the injected class name is the class itself.
  8194. RD = cast<CXXRecordDecl>(RD->getParent());
  8195. // Fix up the information we'll use to build the using declaration.
  8196. if (Corrected.WillReplaceSpecifier()) {
  8197. NestedNameSpecifierLocBuilder Builder;
  8198. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  8199. QualifierLoc.getSourceRange());
  8200. QualifierLoc = Builder.getWithLocInContext(Context);
  8201. }
  8202. // In this case, the name we introduce is the name of a derived class
  8203. // constructor.
  8204. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  8205. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  8206. Context.getCanonicalType(Context.getRecordType(CurClass))));
  8207. UsingName.setNamedTypeInfo(nullptr);
  8208. for (auto *Ctor : LookupConstructors(RD))
  8209. R.addDecl(Ctor);
  8210. R.resolveKind();
  8211. } else {
  8212. // FIXME: Pick up all the declarations if we found an overloaded
  8213. // function.
  8214. UsingName.setName(ND->getDeclName());
  8215. R.addDecl(ND);
  8216. }
  8217. } else {
  8218. Diag(IdentLoc, diag::err_no_member)
  8219. << NameInfo.getName() << LookupContext << SS.getRange();
  8220. return BuildInvalid();
  8221. }
  8222. }
  8223. if (R.isAmbiguous())
  8224. return BuildInvalid();
  8225. if (HasTypenameKeyword) {
  8226. // If we asked for a typename and got a non-type decl, error out.
  8227. if (!R.getAsSingle<TypeDecl>()) {
  8228. Diag(IdentLoc, diag::err_using_typename_non_type);
  8229. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  8230. Diag((*I)->getUnderlyingDecl()->getLocation(),
  8231. diag::note_using_decl_target);
  8232. return BuildInvalid();
  8233. }
  8234. } else {
  8235. // If we asked for a non-typename and we got a type, error out,
  8236. // but only if this is an instantiation of an unresolved using
  8237. // decl. Otherwise just silently find the type name.
  8238. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  8239. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  8240. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  8241. return BuildInvalid();
  8242. }
  8243. }
  8244. // C++14 [namespace.udecl]p6:
  8245. // A using-declaration shall not name a namespace.
  8246. if (R.getAsSingle<NamespaceDecl>()) {
  8247. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  8248. << SS.getRange();
  8249. return BuildInvalid();
  8250. }
  8251. // C++14 [namespace.udecl]p7:
  8252. // A using-declaration shall not name a scoped enumerator.
  8253. if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
  8254. if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
  8255. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
  8256. << SS.getRange();
  8257. return BuildInvalid();
  8258. }
  8259. }
  8260. UsingDecl *UD = BuildValid();
  8261. // Some additional rules apply to inheriting constructors.
  8262. if (UsingName.getName().getNameKind() ==
  8263. DeclarationName::CXXConstructorName) {
  8264. // Suppress access diagnostics; the access check is instead performed at the
  8265. // point of use for an inheriting constructor.
  8266. R.suppressDiagnostics();
  8267. if (CheckInheritingConstructorUsingDecl(UD))
  8268. return UD;
  8269. }
  8270. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8271. UsingShadowDecl *PrevDecl = nullptr;
  8272. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  8273. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  8274. }
  8275. return UD;
  8276. }
  8277. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  8278. ArrayRef<NamedDecl *> Expansions) {
  8279. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  8280. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  8281. isa<UsingPackDecl>(InstantiatedFrom));
  8282. auto *UPD =
  8283. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  8284. UPD->setAccess(InstantiatedFrom->getAccess());
  8285. CurContext->addDecl(UPD);
  8286. return UPD;
  8287. }
  8288. /// Additional checks for a using declaration referring to a constructor name.
  8289. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  8290. assert(!UD->hasTypename() && "expecting a constructor name");
  8291. const Type *SourceType = UD->getQualifier()->getAsType();
  8292. assert(SourceType &&
  8293. "Using decl naming constructor doesn't have type in scope spec.");
  8294. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  8295. // Check whether the named type is a direct base class.
  8296. bool AnyDependentBases = false;
  8297. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  8298. AnyDependentBases);
  8299. if (!Base && !AnyDependentBases) {
  8300. Diag(UD->getUsingLoc(),
  8301. diag::err_using_decl_constructor_not_in_direct_base)
  8302. << UD->getNameInfo().getSourceRange()
  8303. << QualType(SourceType, 0) << TargetClass;
  8304. UD->setInvalidDecl();
  8305. return true;
  8306. }
  8307. if (Base)
  8308. Base->setInheritConstructors();
  8309. return false;
  8310. }
  8311. /// Checks that the given using declaration is not an invalid
  8312. /// redeclaration. Note that this is checking only for the using decl
  8313. /// itself, not for any ill-formedness among the UsingShadowDecls.
  8314. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  8315. bool HasTypenameKeyword,
  8316. const CXXScopeSpec &SS,
  8317. SourceLocation NameLoc,
  8318. const LookupResult &Prev) {
  8319. NestedNameSpecifier *Qual = SS.getScopeRep();
  8320. // C++03 [namespace.udecl]p8:
  8321. // C++0x [namespace.udecl]p10:
  8322. // A using-declaration is a declaration and can therefore be used
  8323. // repeatedly where (and only where) multiple declarations are
  8324. // allowed.
  8325. //
  8326. // That's in non-member contexts.
  8327. if (!CurContext->getRedeclContext()->isRecord()) {
  8328. // A dependent qualifier outside a class can only ever resolve to an
  8329. // enumeration type. Therefore it conflicts with any other non-type
  8330. // declaration in the same scope.
  8331. // FIXME: How should we check for dependent type-type conflicts at block
  8332. // scope?
  8333. if (Qual->isDependent() && !HasTypenameKeyword) {
  8334. for (auto *D : Prev) {
  8335. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  8336. bool OldCouldBeEnumerator =
  8337. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  8338. Diag(NameLoc,
  8339. OldCouldBeEnumerator ? diag::err_redefinition
  8340. : diag::err_redefinition_different_kind)
  8341. << Prev.getLookupName();
  8342. Diag(D->getLocation(), diag::note_previous_definition);
  8343. return true;
  8344. }
  8345. }
  8346. }
  8347. return false;
  8348. }
  8349. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  8350. NamedDecl *D = *I;
  8351. bool DTypename;
  8352. NestedNameSpecifier *DQual;
  8353. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  8354. DTypename = UD->hasTypename();
  8355. DQual = UD->getQualifier();
  8356. } else if (UnresolvedUsingValueDecl *UD
  8357. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  8358. DTypename = false;
  8359. DQual = UD->getQualifier();
  8360. } else if (UnresolvedUsingTypenameDecl *UD
  8361. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  8362. DTypename = true;
  8363. DQual = UD->getQualifier();
  8364. } else continue;
  8365. // using decls differ if one says 'typename' and the other doesn't.
  8366. // FIXME: non-dependent using decls?
  8367. if (HasTypenameKeyword != DTypename) continue;
  8368. // using decls differ if they name different scopes (but note that
  8369. // template instantiation can cause this check to trigger when it
  8370. // didn't before instantiation).
  8371. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  8372. Context.getCanonicalNestedNameSpecifier(DQual))
  8373. continue;
  8374. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  8375. Diag(D->getLocation(), diag::note_using_decl) << 1;
  8376. return true;
  8377. }
  8378. return false;
  8379. }
  8380. /// Checks that the given nested-name qualifier used in a using decl
  8381. /// in the current context is appropriately related to the current
  8382. /// scope. If an error is found, diagnoses it and returns true.
  8383. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  8384. bool HasTypename,
  8385. const CXXScopeSpec &SS,
  8386. const DeclarationNameInfo &NameInfo,
  8387. SourceLocation NameLoc) {
  8388. DeclContext *NamedContext = computeDeclContext(SS);
  8389. if (!CurContext->isRecord()) {
  8390. // C++03 [namespace.udecl]p3:
  8391. // C++0x [namespace.udecl]p8:
  8392. // A using-declaration for a class member shall be a member-declaration.
  8393. // If we weren't able to compute a valid scope, it might validly be a
  8394. // dependent class scope or a dependent enumeration unscoped scope. If
  8395. // we have a 'typename' keyword, the scope must resolve to a class type.
  8396. if ((HasTypename && !NamedContext) ||
  8397. (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
  8398. auto *RD = NamedContext
  8399. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  8400. : nullptr;
  8401. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  8402. RD = nullptr;
  8403. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  8404. << SS.getRange();
  8405. // If we have a complete, non-dependent source type, try to suggest a
  8406. // way to get the same effect.
  8407. if (!RD)
  8408. return true;
  8409. // Find what this using-declaration was referring to.
  8410. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  8411. R.setHideTags(false);
  8412. R.suppressDiagnostics();
  8413. LookupQualifiedName(R, RD);
  8414. if (R.getAsSingle<TypeDecl>()) {
  8415. if (getLangOpts().CPlusPlus11) {
  8416. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  8417. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  8418. << 0 // alias declaration
  8419. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  8420. NameInfo.getName().getAsString() +
  8421. " = ");
  8422. } else {
  8423. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  8424. SourceLocation InsertLoc =
  8425. getLocForEndOfToken(NameInfo.getLocEnd());
  8426. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  8427. << 1 // typedef declaration
  8428. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  8429. << FixItHint::CreateInsertion(
  8430. InsertLoc, " " + NameInfo.getName().getAsString());
  8431. }
  8432. } else if (R.getAsSingle<VarDecl>()) {
  8433. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  8434. // repeating the type of the static data member here.
  8435. FixItHint FixIt;
  8436. if (getLangOpts().CPlusPlus11) {
  8437. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  8438. FixIt = FixItHint::CreateReplacement(
  8439. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  8440. }
  8441. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  8442. << 2 // reference declaration
  8443. << FixIt;
  8444. } else if (R.getAsSingle<EnumConstantDecl>()) {
  8445. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  8446. // repeating the type of the enumeration here, and we can't do so if
  8447. // the type is anonymous.
  8448. FixItHint FixIt;
  8449. if (getLangOpts().CPlusPlus11) {
  8450. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  8451. FixIt = FixItHint::CreateReplacement(
  8452. UsingLoc,
  8453. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  8454. }
  8455. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  8456. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  8457. << FixIt;
  8458. }
  8459. return true;
  8460. }
  8461. // Otherwise, this might be valid.
  8462. return false;
  8463. }
  8464. // The current scope is a record.
  8465. // If the named context is dependent, we can't decide much.
  8466. if (!NamedContext) {
  8467. // FIXME: in C++0x, we can diagnose if we can prove that the
  8468. // nested-name-specifier does not refer to a base class, which is
  8469. // still possible in some cases.
  8470. // Otherwise we have to conservatively report that things might be
  8471. // okay.
  8472. return false;
  8473. }
  8474. if (!NamedContext->isRecord()) {
  8475. // Ideally this would point at the last name in the specifier,
  8476. // but we don't have that level of source info.
  8477. Diag(SS.getRange().getBegin(),
  8478. diag::err_using_decl_nested_name_specifier_is_not_class)
  8479. << SS.getScopeRep() << SS.getRange();
  8480. return true;
  8481. }
  8482. if (!NamedContext->isDependentContext() &&
  8483. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  8484. return true;
  8485. if (getLangOpts().CPlusPlus11) {
  8486. // C++11 [namespace.udecl]p3:
  8487. // In a using-declaration used as a member-declaration, the
  8488. // nested-name-specifier shall name a base class of the class
  8489. // being defined.
  8490. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  8491. cast<CXXRecordDecl>(NamedContext))) {
  8492. if (CurContext == NamedContext) {
  8493. Diag(NameLoc,
  8494. diag::err_using_decl_nested_name_specifier_is_current_class)
  8495. << SS.getRange();
  8496. return true;
  8497. }
  8498. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  8499. Diag(SS.getRange().getBegin(),
  8500. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8501. << SS.getScopeRep()
  8502. << cast<CXXRecordDecl>(CurContext)
  8503. << SS.getRange();
  8504. }
  8505. return true;
  8506. }
  8507. return false;
  8508. }
  8509. // C++03 [namespace.udecl]p4:
  8510. // A using-declaration used as a member-declaration shall refer
  8511. // to a member of a base class of the class being defined [etc.].
  8512. // Salient point: SS doesn't have to name a base class as long as
  8513. // lookup only finds members from base classes. Therefore we can
  8514. // diagnose here only if we can prove that that can't happen,
  8515. // i.e. if the class hierarchies provably don't intersect.
  8516. // TODO: it would be nice if "definitely valid" results were cached
  8517. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  8518. // need to be repeated.
  8519. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  8520. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  8521. Bases.insert(Base);
  8522. return true;
  8523. };
  8524. // Collect all bases. Return false if we find a dependent base.
  8525. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  8526. return false;
  8527. // Returns true if the base is dependent or is one of the accumulated base
  8528. // classes.
  8529. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  8530. return !Bases.count(Base);
  8531. };
  8532. // Return false if the class has a dependent base or if it or one
  8533. // of its bases is present in the base set of the current context.
  8534. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  8535. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  8536. return false;
  8537. Diag(SS.getRange().getBegin(),
  8538. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  8539. << SS.getScopeRep()
  8540. << cast<CXXRecordDecl>(CurContext)
  8541. << SS.getRange();
  8542. return true;
  8543. }
  8544. Decl *Sema::ActOnAliasDeclaration(Scope *S,
  8545. AccessSpecifier AS,
  8546. MultiTemplateParamsArg TemplateParamLists,
  8547. SourceLocation UsingLoc,
  8548. UnqualifiedId &Name,
  8549. AttributeList *AttrList,
  8550. TypeResult Type,
  8551. Decl *DeclFromDeclSpec) {
  8552. // Skip up to the relevant declaration scope.
  8553. while (S->isTemplateParamScope())
  8554. S = S->getParent();
  8555. assert((S->getFlags() & Scope::DeclScope) &&
  8556. "got alias-declaration outside of declaration scope");
  8557. if (Type.isInvalid())
  8558. return nullptr;
  8559. bool Invalid = false;
  8560. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  8561. TypeSourceInfo *TInfo = nullptr;
  8562. GetTypeFromParser(Type.get(), &TInfo);
  8563. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  8564. return nullptr;
  8565. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  8566. UPPC_DeclarationType)) {
  8567. Invalid = true;
  8568. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  8569. TInfo->getTypeLoc().getBeginLoc());
  8570. }
  8571. LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
  8572. LookupName(Previous, S);
  8573. // Warn about shadowing the name of a template parameter.
  8574. if (Previous.isSingleResult() &&
  8575. Previous.getFoundDecl()->isTemplateParameter()) {
  8576. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  8577. Previous.clear();
  8578. }
  8579. assert(Name.Kind == UnqualifiedId::IK_Identifier &&
  8580. "name in alias declaration must be an identifier");
  8581. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  8582. Name.StartLocation,
  8583. Name.Identifier, TInfo);
  8584. NewTD->setAccess(AS);
  8585. if (Invalid)
  8586. NewTD->setInvalidDecl();
  8587. ProcessDeclAttributeList(S, NewTD, AttrList);
  8588. CheckTypedefForVariablyModifiedType(S, NewTD);
  8589. Invalid |= NewTD->isInvalidDecl();
  8590. bool Redeclaration = false;
  8591. NamedDecl *NewND;
  8592. if (TemplateParamLists.size()) {
  8593. TypeAliasTemplateDecl *OldDecl = nullptr;
  8594. TemplateParameterList *OldTemplateParams = nullptr;
  8595. if (TemplateParamLists.size() != 1) {
  8596. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  8597. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  8598. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  8599. }
  8600. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  8601. // Check that we can declare a template here.
  8602. if (CheckTemplateDeclScope(S, TemplateParams))
  8603. return nullptr;
  8604. // Only consider previous declarations in the same scope.
  8605. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  8606. /*ExplicitInstantiationOrSpecialization*/false);
  8607. if (!Previous.empty()) {
  8608. Redeclaration = true;
  8609. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  8610. if (!OldDecl && !Invalid) {
  8611. Diag(UsingLoc, diag::err_redefinition_different_kind)
  8612. << Name.Identifier;
  8613. NamedDecl *OldD = Previous.getRepresentativeDecl();
  8614. if (OldD->getLocation().isValid())
  8615. Diag(OldD->getLocation(), diag::note_previous_definition);
  8616. Invalid = true;
  8617. }
  8618. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  8619. if (TemplateParameterListsAreEqual(TemplateParams,
  8620. OldDecl->getTemplateParameters(),
  8621. /*Complain=*/true,
  8622. TPL_TemplateMatch))
  8623. OldTemplateParams = OldDecl->getTemplateParameters();
  8624. else
  8625. Invalid = true;
  8626. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  8627. if (!Invalid &&
  8628. !Context.hasSameType(OldTD->getUnderlyingType(),
  8629. NewTD->getUnderlyingType())) {
  8630. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  8631. // but we can't reasonably accept it.
  8632. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  8633. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  8634. if (OldTD->getLocation().isValid())
  8635. Diag(OldTD->getLocation(), diag::note_previous_definition);
  8636. Invalid = true;
  8637. }
  8638. }
  8639. }
  8640. // Merge any previous default template arguments into our parameters,
  8641. // and check the parameter list.
  8642. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  8643. TPC_TypeAliasTemplate))
  8644. return nullptr;
  8645. TypeAliasTemplateDecl *NewDecl =
  8646. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  8647. Name.Identifier, TemplateParams,
  8648. NewTD);
  8649. NewTD->setDescribedAliasTemplate(NewDecl);
  8650. NewDecl->setAccess(AS);
  8651. if (Invalid)
  8652. NewDecl->setInvalidDecl();
  8653. else if (OldDecl)
  8654. NewDecl->setPreviousDecl(OldDecl);
  8655. NewND = NewDecl;
  8656. } else {
  8657. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  8658. setTagNameForLinkagePurposes(TD, NewTD);
  8659. handleTagNumbering(TD, S);
  8660. }
  8661. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  8662. NewND = NewTD;
  8663. }
  8664. PushOnScopeChains(NewND, S);
  8665. ActOnDocumentableDecl(NewND);
  8666. return NewND;
  8667. }
  8668. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  8669. SourceLocation AliasLoc,
  8670. IdentifierInfo *Alias, CXXScopeSpec &SS,
  8671. SourceLocation IdentLoc,
  8672. IdentifierInfo *Ident) {
  8673. // Lookup the namespace name.
  8674. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  8675. LookupParsedName(R, S, &SS);
  8676. if (R.isAmbiguous())
  8677. return nullptr;
  8678. if (R.empty()) {
  8679. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  8680. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  8681. return nullptr;
  8682. }
  8683. }
  8684. assert(!R.isAmbiguous() && !R.empty());
  8685. NamedDecl *ND = R.getRepresentativeDecl();
  8686. // Check if we have a previous declaration with the same name.
  8687. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  8688. ForRedeclaration);
  8689. LookupName(PrevR, S);
  8690. // Check we're not shadowing a template parameter.
  8691. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  8692. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  8693. PrevR.clear();
  8694. }
  8695. // Filter out any other lookup result from an enclosing scope.
  8696. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  8697. /*AllowInlineNamespace*/false);
  8698. // Find the previous declaration and check that we can redeclare it.
  8699. NamespaceAliasDecl *Prev = nullptr;
  8700. if (PrevR.isSingleResult()) {
  8701. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  8702. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  8703. // We already have an alias with the same name that points to the same
  8704. // namespace; check that it matches.
  8705. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  8706. Prev = AD;
  8707. } else if (isVisible(PrevDecl)) {
  8708. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  8709. << Alias;
  8710. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  8711. << AD->getNamespace();
  8712. return nullptr;
  8713. }
  8714. } else if (isVisible(PrevDecl)) {
  8715. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  8716. ? diag::err_redefinition
  8717. : diag::err_redefinition_different_kind;
  8718. Diag(AliasLoc, DiagID) << Alias;
  8719. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  8720. return nullptr;
  8721. }
  8722. }
  8723. // The use of a nested name specifier may trigger deprecation warnings.
  8724. DiagnoseUseOfDecl(ND, IdentLoc);
  8725. NamespaceAliasDecl *AliasDecl =
  8726. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  8727. Alias, SS.getWithLocInContext(Context),
  8728. IdentLoc, ND);
  8729. if (Prev)
  8730. AliasDecl->setPreviousDecl(Prev);
  8731. PushOnScopeChains(AliasDecl, S);
  8732. return AliasDecl;
  8733. }
  8734. Sema::ImplicitExceptionSpecification
  8735. Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
  8736. CXXMethodDecl *MD) {
  8737. CXXRecordDecl *ClassDecl = MD->getParent();
  8738. // C++ [except.spec]p14:
  8739. // An implicitly declared special member function (Clause 12) shall have an
  8740. // exception-specification. [...]
  8741. ImplicitExceptionSpecification ExceptSpec(*this);
  8742. if (ClassDecl->isInvalidDecl())
  8743. return ExceptSpec;
  8744. // Direct base-class constructors.
  8745. for (const auto &B : ClassDecl->bases()) {
  8746. if (B.isVirtual()) // Handled below.
  8747. continue;
  8748. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  8749. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  8750. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  8751. // If this is a deleted function, add it anyway. This might be conformant
  8752. // with the standard. This might not. I'm not sure. It might not matter.
  8753. if (Constructor)
  8754. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  8755. }
  8756. }
  8757. // Virtual base-class constructors.
  8758. for (const auto &B : ClassDecl->vbases()) {
  8759. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  8760. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  8761. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  8762. // If this is a deleted function, add it anyway. This might be conformant
  8763. // with the standard. This might not. I'm not sure. It might not matter.
  8764. if (Constructor)
  8765. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  8766. }
  8767. }
  8768. // Field constructors.
  8769. for (auto *F : ClassDecl->fields()) {
  8770. if (F->hasInClassInitializer()) {
  8771. Expr *E = F->getInClassInitializer();
  8772. if (!E)
  8773. // FIXME: It's a little wasteful to build and throw away a
  8774. // CXXDefaultInitExpr here.
  8775. E = BuildCXXDefaultInitExpr(Loc, F).get();
  8776. if (E)
  8777. ExceptSpec.CalledExpr(E);
  8778. } else if (const RecordType *RecordTy
  8779. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  8780. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  8781. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  8782. // If this is a deleted function, add it anyway. This might be conformant
  8783. // with the standard. This might not. I'm not sure. It might not matter.
  8784. // In particular, the problem is that this function never gets called. It
  8785. // might just be ill-formed because this function attempts to refer to
  8786. // a deleted function here.
  8787. if (Constructor)
  8788. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  8789. }
  8790. }
  8791. return ExceptSpec;
  8792. }
  8793. Sema::ImplicitExceptionSpecification
  8794. Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
  8795. CXXConstructorDecl *CD) {
  8796. CXXRecordDecl *ClassDecl = CD->getParent();
  8797. // C++ [except.spec]p14:
  8798. // An inheriting constructor [...] shall have an exception-specification. [...]
  8799. ImplicitExceptionSpecification ExceptSpec(*this);
  8800. if (ClassDecl->isInvalidDecl())
  8801. return ExceptSpec;
  8802. auto Inherited = CD->getInheritedConstructor();
  8803. InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
  8804. // Direct and virtual base-class constructors.
  8805. for (bool VBase : {false, true}) {
  8806. for (CXXBaseSpecifier &B :
  8807. VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
  8808. // Don't visit direct vbases twice.
  8809. if (B.isVirtual() != VBase)
  8810. continue;
  8811. CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
  8812. if (!BaseClass)
  8813. continue;
  8814. CXXConstructorDecl *Constructor =
  8815. ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
  8816. .first;
  8817. if (!Constructor)
  8818. Constructor = LookupDefaultConstructor(BaseClass);
  8819. if (Constructor)
  8820. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  8821. }
  8822. }
  8823. // Field constructors.
  8824. for (const auto *F : ClassDecl->fields()) {
  8825. if (F->hasInClassInitializer()) {
  8826. if (Expr *E = F->getInClassInitializer())
  8827. ExceptSpec.CalledExpr(E);
  8828. } else if (const RecordType *RecordTy
  8829. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  8830. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  8831. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  8832. if (Constructor)
  8833. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  8834. }
  8835. }
  8836. return ExceptSpec;
  8837. }
  8838. namespace {
  8839. /// RAII object to register a special member as being currently declared.
  8840. struct DeclaringSpecialMember {
  8841. Sema &S;
  8842. Sema::SpecialMemberDecl D;
  8843. Sema::ContextRAII SavedContext;
  8844. bool WasAlreadyBeingDeclared;
  8845. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  8846. : S(S), D(RD, CSM), SavedContext(S, RD) {
  8847. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  8848. if (WasAlreadyBeingDeclared)
  8849. // This almost never happens, but if it does, ensure that our cache
  8850. // doesn't contain a stale result.
  8851. S.SpecialMemberCache.clear();
  8852. // FIXME: Register a note to be produced if we encounter an error while
  8853. // declaring the special member.
  8854. }
  8855. ~DeclaringSpecialMember() {
  8856. if (!WasAlreadyBeingDeclared)
  8857. S.SpecialMembersBeingDeclared.erase(D);
  8858. }
  8859. /// \brief Are we already trying to declare this special member?
  8860. bool isAlreadyBeingDeclared() const {
  8861. return WasAlreadyBeingDeclared;
  8862. }
  8863. };
  8864. }
  8865. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  8866. // Look up any existing declarations, but don't trigger declaration of all
  8867. // implicit special members with this name.
  8868. DeclarationName Name = FD->getDeclName();
  8869. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  8870. ForRedeclaration);
  8871. for (auto *D : FD->getParent()->lookup(Name))
  8872. if (auto *Acceptable = R.getAcceptableDecl(D))
  8873. R.addDecl(Acceptable);
  8874. R.resolveKind();
  8875. R.suppressDiagnostics();
  8876. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  8877. }
  8878. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  8879. CXXRecordDecl *ClassDecl) {
  8880. // C++ [class.ctor]p5:
  8881. // A default constructor for a class X is a constructor of class X
  8882. // that can be called without an argument. If there is no
  8883. // user-declared constructor for class X, a default constructor is
  8884. // implicitly declared. An implicitly-declared default constructor
  8885. // is an inline public member of its class.
  8886. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  8887. "Should not build implicit default constructor!");
  8888. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  8889. if (DSM.isAlreadyBeingDeclared())
  8890. return nullptr;
  8891. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  8892. CXXDefaultConstructor,
  8893. false);
  8894. // Create the actual constructor declaration.
  8895. CanQualType ClassType
  8896. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  8897. SourceLocation ClassLoc = ClassDecl->getLocation();
  8898. DeclarationName Name
  8899. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  8900. DeclarationNameInfo NameInfo(Name, ClassLoc);
  8901. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  8902. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
  8903. /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
  8904. /*isImplicitlyDeclared=*/true, Constexpr);
  8905. DefaultCon->setAccess(AS_public);
  8906. DefaultCon->setDefaulted();
  8907. if (getLangOpts().CUDA) {
  8908. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  8909. DefaultCon,
  8910. /* ConstRHS */ false,
  8911. /* Diagnose */ false);
  8912. }
  8913. // Build an exception specification pointing back at this constructor.
  8914. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
  8915. DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  8916. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  8917. // constructors is easy to compute.
  8918. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  8919. // Note that we have declared this constructor.
  8920. ++ASTContext::NumImplicitDefaultConstructorsDeclared;
  8921. Scope *S = getScopeForContext(ClassDecl);
  8922. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  8923. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  8924. SetDeclDeleted(DefaultCon, ClassLoc);
  8925. if (S)
  8926. PushOnScopeChains(DefaultCon, S, false);
  8927. ClassDecl->addDecl(DefaultCon);
  8928. return DefaultCon;
  8929. }
  8930. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  8931. CXXConstructorDecl *Constructor) {
  8932. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  8933. !Constructor->doesThisDeclarationHaveABody() &&
  8934. !Constructor->isDeleted()) &&
  8935. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  8936. CXXRecordDecl *ClassDecl = Constructor->getParent();
  8937. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  8938. SynthesizedFunctionScope Scope(*this, Constructor);
  8939. DiagnosticErrorTrap Trap(Diags);
  8940. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
  8941. Trap.hasErrorOccurred()) {
  8942. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8943. << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
  8944. Constructor->setInvalidDecl();
  8945. return;
  8946. }
  8947. // The exception specification is needed because we are defining the
  8948. // function.
  8949. ResolveExceptionSpec(CurrentLocation,
  8950. Constructor->getType()->castAs<FunctionProtoType>());
  8951. SourceLocation Loc = Constructor->getLocEnd().isValid()
  8952. ? Constructor->getLocEnd()
  8953. : Constructor->getLocation();
  8954. Constructor->setBody(new (Context) CompoundStmt(Loc));
  8955. Constructor->markUsed(Context);
  8956. MarkVTableUsed(CurrentLocation, ClassDecl);
  8957. if (ASTMutationListener *L = getASTMutationListener()) {
  8958. L->CompletedImplicitDefinition(Constructor);
  8959. }
  8960. DiagnoseUninitializedFields(*this, Constructor);
  8961. }
  8962. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  8963. // Perform any delayed checks on exception specifications.
  8964. CheckDelayedMemberExceptionSpecs();
  8965. }
  8966. /// Find or create the fake constructor we synthesize to model constructing an
  8967. /// object of a derived class via a constructor of a base class.
  8968. CXXConstructorDecl *
  8969. Sema::findInheritingConstructor(SourceLocation Loc,
  8970. CXXConstructorDecl *BaseCtor,
  8971. ConstructorUsingShadowDecl *Shadow) {
  8972. CXXRecordDecl *Derived = Shadow->getParent();
  8973. SourceLocation UsingLoc = Shadow->getLocation();
  8974. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  8975. // For now we use the name of the base class constructor as a member of the
  8976. // derived class to indicate a (fake) inherited constructor name.
  8977. DeclarationName Name = BaseCtor->getDeclName();
  8978. // Check to see if we already have a fake constructor for this inherited
  8979. // constructor call.
  8980. for (NamedDecl *Ctor : Derived->lookup(Name))
  8981. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  8982. ->getInheritedConstructor()
  8983. .getConstructor(),
  8984. BaseCtor))
  8985. return cast<CXXConstructorDecl>(Ctor);
  8986. DeclarationNameInfo NameInfo(Name, UsingLoc);
  8987. TypeSourceInfo *TInfo =
  8988. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  8989. FunctionProtoTypeLoc ProtoLoc =
  8990. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  8991. // Check the inherited constructor is valid and find the list of base classes
  8992. // from which it was inherited.
  8993. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  8994. bool Constexpr =
  8995. BaseCtor->isConstexpr() &&
  8996. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  8997. false, BaseCtor, &ICI);
  8998. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  8999. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  9000. BaseCtor->isExplicit(), /*Inline=*/true,
  9001. /*ImplicitlyDeclared=*/true, Constexpr,
  9002. InheritedConstructor(Shadow, BaseCtor));
  9003. if (Shadow->isInvalidDecl())
  9004. DerivedCtor->setInvalidDecl();
  9005. // Build an unevaluated exception specification for this fake constructor.
  9006. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  9007. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9008. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9009. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  9010. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  9011. FPT->getParamTypes(), EPI));
  9012. // Build the parameter declarations.
  9013. SmallVector<ParmVarDecl *, 16> ParamDecls;
  9014. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  9015. TypeSourceInfo *TInfo =
  9016. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  9017. ParmVarDecl *PD = ParmVarDecl::Create(
  9018. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  9019. FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
  9020. PD->setScopeInfo(0, I);
  9021. PD->setImplicit();
  9022. // Ensure attributes are propagated onto parameters (this matters for
  9023. // format, pass_object_size, ...).
  9024. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  9025. ParamDecls.push_back(PD);
  9026. ProtoLoc.setParam(I, PD);
  9027. }
  9028. // Set up the new constructor.
  9029. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  9030. DerivedCtor->setAccess(BaseCtor->getAccess());
  9031. DerivedCtor->setParams(ParamDecls);
  9032. Derived->addDecl(DerivedCtor);
  9033. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  9034. SetDeclDeleted(DerivedCtor, UsingLoc);
  9035. return DerivedCtor;
  9036. }
  9037. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  9038. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  9039. Ctor->getInheritedConstructor().getShadowDecl());
  9040. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  9041. /*Diagnose*/true);
  9042. }
  9043. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  9044. CXXConstructorDecl *Constructor) {
  9045. CXXRecordDecl *ClassDecl = Constructor->getParent();
  9046. assert(Constructor->getInheritedConstructor() &&
  9047. !Constructor->doesThisDeclarationHaveABody() &&
  9048. !Constructor->isDeleted());
  9049. if (Constructor->isInvalidDecl())
  9050. return;
  9051. ConstructorUsingShadowDecl *Shadow =
  9052. Constructor->getInheritedConstructor().getShadowDecl();
  9053. CXXConstructorDecl *InheritedCtor =
  9054. Constructor->getInheritedConstructor().getConstructor();
  9055. // [class.inhctor.init]p1:
  9056. // initialization proceeds as if a defaulted default constructor is used to
  9057. // initialize the D object and each base class subobject from which the
  9058. // constructor was inherited
  9059. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  9060. CXXRecordDecl *RD = Shadow->getParent();
  9061. SourceLocation InitLoc = Shadow->getLocation();
  9062. // Initializations are performed "as if by a defaulted default constructor",
  9063. // so enter the appropriate scope.
  9064. SynthesizedFunctionScope Scope(*this, Constructor);
  9065. DiagnosticErrorTrap Trap(Diags);
  9066. // Build explicit initializers for all base classes from which the
  9067. // constructor was inherited.
  9068. SmallVector<CXXCtorInitializer*, 8> Inits;
  9069. for (bool VBase : {false, true}) {
  9070. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  9071. if (B.isVirtual() != VBase)
  9072. continue;
  9073. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  9074. if (!BaseRD)
  9075. continue;
  9076. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  9077. if (!BaseCtor.first)
  9078. continue;
  9079. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  9080. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  9081. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  9082. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  9083. Inits.push_back(new (Context) CXXCtorInitializer(
  9084. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  9085. SourceLocation()));
  9086. }
  9087. }
  9088. // We now proceed as if for a defaulted default constructor, with the relevant
  9089. // initializers replaced.
  9090. bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
  9091. if (HadError || Trap.hasErrorOccurred()) {
  9092. Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
  9093. Constructor->setInvalidDecl();
  9094. return;
  9095. }
  9096. // The exception specification is needed because we are defining the
  9097. // function.
  9098. ResolveExceptionSpec(CurrentLocation,
  9099. Constructor->getType()->castAs<FunctionProtoType>());
  9100. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  9101. Constructor->markUsed(Context);
  9102. MarkVTableUsed(CurrentLocation, ClassDecl);
  9103. if (ASTMutationListener *L = getASTMutationListener()) {
  9104. L->CompletedImplicitDefinition(Constructor);
  9105. }
  9106. DiagnoseUninitializedFields(*this, Constructor);
  9107. }
  9108. Sema::ImplicitExceptionSpecification
  9109. Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
  9110. CXXRecordDecl *ClassDecl = MD->getParent();
  9111. // C++ [except.spec]p14:
  9112. // An implicitly declared special member function (Clause 12) shall have
  9113. // an exception-specification.
  9114. ImplicitExceptionSpecification ExceptSpec(*this);
  9115. if (ClassDecl->isInvalidDecl())
  9116. return ExceptSpec;
  9117. // Direct base-class destructors.
  9118. for (const auto &B : ClassDecl->bases()) {
  9119. if (B.isVirtual()) // Handled below.
  9120. continue;
  9121. if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
  9122. ExceptSpec.CalledDecl(B.getLocStart(),
  9123. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  9124. }
  9125. // Virtual base-class destructors.
  9126. for (const auto &B : ClassDecl->vbases()) {
  9127. if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
  9128. ExceptSpec.CalledDecl(B.getLocStart(),
  9129. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  9130. }
  9131. // Field destructors.
  9132. for (const auto *F : ClassDecl->fields()) {
  9133. if (const RecordType *RecordTy
  9134. = Context.getBaseElementType(F->getType())->getAs<RecordType>())
  9135. ExceptSpec.CalledDecl(F->getLocation(),
  9136. LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
  9137. }
  9138. return ExceptSpec;
  9139. }
  9140. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  9141. // C++ [class.dtor]p2:
  9142. // If a class has no user-declared destructor, a destructor is
  9143. // declared implicitly. An implicitly-declared destructor is an
  9144. // inline public member of its class.
  9145. assert(ClassDecl->needsImplicitDestructor());
  9146. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  9147. if (DSM.isAlreadyBeingDeclared())
  9148. return nullptr;
  9149. // Create the actual destructor declaration.
  9150. CanQualType ClassType
  9151. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9152. SourceLocation ClassLoc = ClassDecl->getLocation();
  9153. DeclarationName Name
  9154. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  9155. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9156. CXXDestructorDecl *Destructor
  9157. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  9158. QualType(), nullptr, /*isInline=*/true,
  9159. /*isImplicitlyDeclared=*/true);
  9160. Destructor->setAccess(AS_public);
  9161. Destructor->setDefaulted();
  9162. if (getLangOpts().CUDA) {
  9163. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  9164. Destructor,
  9165. /* ConstRHS */ false,
  9166. /* Diagnose */ false);
  9167. }
  9168. // Build an exception specification pointing back at this destructor.
  9169. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
  9170. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9171. // We don't need to use SpecialMemberIsTrivial here; triviality for
  9172. // destructors is easy to compute.
  9173. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  9174. // Note that we have declared this destructor.
  9175. ++ASTContext::NumImplicitDestructorsDeclared;
  9176. Scope *S = getScopeForContext(ClassDecl);
  9177. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  9178. // We can't check whether an implicit destructor is deleted before we complete
  9179. // the definition of the class, because its validity depends on the alignment
  9180. // of the class. We'll check this from ActOnFields once the class is complete.
  9181. if (ClassDecl->isCompleteDefinition() &&
  9182. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  9183. SetDeclDeleted(Destructor, ClassLoc);
  9184. // Introduce this destructor into its scope.
  9185. if (S)
  9186. PushOnScopeChains(Destructor, S, false);
  9187. ClassDecl->addDecl(Destructor);
  9188. return Destructor;
  9189. }
  9190. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  9191. CXXDestructorDecl *Destructor) {
  9192. assert((Destructor->isDefaulted() &&
  9193. !Destructor->doesThisDeclarationHaveABody() &&
  9194. !Destructor->isDeleted()) &&
  9195. "DefineImplicitDestructor - call it for implicit default dtor");
  9196. CXXRecordDecl *ClassDecl = Destructor->getParent();
  9197. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  9198. if (Destructor->isInvalidDecl())
  9199. return;
  9200. SynthesizedFunctionScope Scope(*this, Destructor);
  9201. DiagnosticErrorTrap Trap(Diags);
  9202. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  9203. Destructor->getParent());
  9204. if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
  9205. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9206. << CXXDestructor << Context.getTagDeclType(ClassDecl);
  9207. Destructor->setInvalidDecl();
  9208. return;
  9209. }
  9210. // The exception specification is needed because we are defining the
  9211. // function.
  9212. ResolveExceptionSpec(CurrentLocation,
  9213. Destructor->getType()->castAs<FunctionProtoType>());
  9214. SourceLocation Loc = Destructor->getLocEnd().isValid()
  9215. ? Destructor->getLocEnd()
  9216. : Destructor->getLocation();
  9217. Destructor->setBody(new (Context) CompoundStmt(Loc));
  9218. Destructor->markUsed(Context);
  9219. MarkVTableUsed(CurrentLocation, ClassDecl);
  9220. if (ASTMutationListener *L = getASTMutationListener()) {
  9221. L->CompletedImplicitDefinition(Destructor);
  9222. }
  9223. }
  9224. /// \brief Perform any semantic analysis which needs to be delayed until all
  9225. /// pending class member declarations have been parsed.
  9226. void Sema::ActOnFinishCXXMemberDecls() {
  9227. // If the context is an invalid C++ class, just suppress these checks.
  9228. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  9229. if (Record->isInvalidDecl()) {
  9230. DelayedDefaultedMemberExceptionSpecs.clear();
  9231. DelayedExceptionSpecChecks.clear();
  9232. return;
  9233. }
  9234. checkForMultipleExportedDefaultConstructors(*this, Record);
  9235. }
  9236. }
  9237. void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
  9238. referenceDLLExportedClassMethods();
  9239. }
  9240. void Sema::referenceDLLExportedClassMethods() {
  9241. if (!DelayedDllExportClasses.empty()) {
  9242. // Calling ReferenceDllExportedMethods might cause the current function to
  9243. // be called again, so use a local copy of DelayedDllExportClasses.
  9244. SmallVector<CXXRecordDecl *, 4> WorkList;
  9245. std::swap(DelayedDllExportClasses, WorkList);
  9246. for (CXXRecordDecl *Class : WorkList)
  9247. ReferenceDllExportedMethods(*this, Class);
  9248. }
  9249. }
  9250. void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
  9251. CXXDestructorDecl *Destructor) {
  9252. assert(getLangOpts().CPlusPlus11 &&
  9253. "adjusting dtor exception specs was introduced in c++11");
  9254. // C++11 [class.dtor]p3:
  9255. // A declaration of a destructor that does not have an exception-
  9256. // specification is implicitly considered to have the same exception-
  9257. // specification as an implicit declaration.
  9258. const FunctionProtoType *DtorType = Destructor->getType()->
  9259. getAs<FunctionProtoType>();
  9260. if (DtorType->hasExceptionSpec())
  9261. return;
  9262. // Replace the destructor's type, building off the existing one. Fortunately,
  9263. // the only thing of interest in the destructor type is its extended info.
  9264. // The return and arguments are fixed.
  9265. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  9266. EPI.ExceptionSpec.Type = EST_Unevaluated;
  9267. EPI.ExceptionSpec.SourceDecl = Destructor;
  9268. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  9269. // FIXME: If the destructor has a body that could throw, and the newly created
  9270. // spec doesn't allow exceptions, we should emit a warning, because this
  9271. // change in behavior can break conforming C++03 programs at runtime.
  9272. // However, we don't have a body or an exception specification yet, so it
  9273. // needs to be done somewhere else.
  9274. }
  9275. namespace {
  9276. /// \brief An abstract base class for all helper classes used in building the
  9277. // copy/move operators. These classes serve as factory functions and help us
  9278. // avoid using the same Expr* in the AST twice.
  9279. class ExprBuilder {
  9280. ExprBuilder(const ExprBuilder&) = delete;
  9281. ExprBuilder &operator=(const ExprBuilder&) = delete;
  9282. protected:
  9283. static Expr *assertNotNull(Expr *E) {
  9284. assert(E && "Expression construction must not fail.");
  9285. return E;
  9286. }
  9287. public:
  9288. ExprBuilder() {}
  9289. virtual ~ExprBuilder() {}
  9290. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  9291. };
  9292. class RefBuilder: public ExprBuilder {
  9293. VarDecl *Var;
  9294. QualType VarType;
  9295. public:
  9296. Expr *build(Sema &S, SourceLocation Loc) const override {
  9297. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
  9298. }
  9299. RefBuilder(VarDecl *Var, QualType VarType)
  9300. : Var(Var), VarType(VarType) {}
  9301. };
  9302. class ThisBuilder: public ExprBuilder {
  9303. public:
  9304. Expr *build(Sema &S, SourceLocation Loc) const override {
  9305. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  9306. }
  9307. };
  9308. class CastBuilder: public ExprBuilder {
  9309. const ExprBuilder &Builder;
  9310. QualType Type;
  9311. ExprValueKind Kind;
  9312. const CXXCastPath &Path;
  9313. public:
  9314. Expr *build(Sema &S, SourceLocation Loc) const override {
  9315. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  9316. CK_UncheckedDerivedToBase, Kind,
  9317. &Path).get());
  9318. }
  9319. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  9320. const CXXCastPath &Path)
  9321. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  9322. };
  9323. class DerefBuilder: public ExprBuilder {
  9324. const ExprBuilder &Builder;
  9325. public:
  9326. Expr *build(Sema &S, SourceLocation Loc) const override {
  9327. return assertNotNull(
  9328. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  9329. }
  9330. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9331. };
  9332. class MemberBuilder: public ExprBuilder {
  9333. const ExprBuilder &Builder;
  9334. QualType Type;
  9335. CXXScopeSpec SS;
  9336. bool IsArrow;
  9337. LookupResult &MemberLookup;
  9338. public:
  9339. Expr *build(Sema &S, SourceLocation Loc) const override {
  9340. return assertNotNull(S.BuildMemberReferenceExpr(
  9341. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  9342. nullptr, MemberLookup, nullptr, nullptr).get());
  9343. }
  9344. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  9345. LookupResult &MemberLookup)
  9346. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  9347. MemberLookup(MemberLookup) {}
  9348. };
  9349. class MoveCastBuilder: public ExprBuilder {
  9350. const ExprBuilder &Builder;
  9351. public:
  9352. Expr *build(Sema &S, SourceLocation Loc) const override {
  9353. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  9354. }
  9355. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9356. };
  9357. class LvalueConvBuilder: public ExprBuilder {
  9358. const ExprBuilder &Builder;
  9359. public:
  9360. Expr *build(Sema &S, SourceLocation Loc) const override {
  9361. return assertNotNull(
  9362. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  9363. }
  9364. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  9365. };
  9366. class SubscriptBuilder: public ExprBuilder {
  9367. const ExprBuilder &Base;
  9368. const ExprBuilder &Index;
  9369. public:
  9370. Expr *build(Sema &S, SourceLocation Loc) const override {
  9371. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  9372. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  9373. }
  9374. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  9375. : Base(Base), Index(Index) {}
  9376. };
  9377. } // end anonymous namespace
  9378. /// When generating a defaulted copy or move assignment operator, if a field
  9379. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  9380. /// do so. This optimization only applies for arrays of scalars, and for arrays
  9381. /// of class type where the selected copy/move-assignment operator is trivial.
  9382. static StmtResult
  9383. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  9384. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  9385. // Compute the size of the memory buffer to be copied.
  9386. QualType SizeType = S.Context.getSizeType();
  9387. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  9388. S.Context.getTypeSizeInChars(T).getQuantity());
  9389. // Take the address of the field references for "from" and "to". We
  9390. // directly construct UnaryOperators here because semantic analysis
  9391. // does not permit us to take the address of an xvalue.
  9392. Expr *From = FromB.build(S, Loc);
  9393. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  9394. S.Context.getPointerType(From->getType()),
  9395. VK_RValue, OK_Ordinary, Loc);
  9396. Expr *To = ToB.build(S, Loc);
  9397. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  9398. S.Context.getPointerType(To->getType()),
  9399. VK_RValue, OK_Ordinary, Loc);
  9400. const Type *E = T->getBaseElementTypeUnsafe();
  9401. bool NeedsCollectableMemCpy =
  9402. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  9403. // Create a reference to the __builtin_objc_memmove_collectable function
  9404. StringRef MemCpyName = NeedsCollectableMemCpy ?
  9405. "__builtin_objc_memmove_collectable" :
  9406. "__builtin_memcpy";
  9407. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  9408. Sema::LookupOrdinaryName);
  9409. S.LookupName(R, S.TUScope, true);
  9410. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  9411. if (!MemCpy)
  9412. // Something went horribly wrong earlier, and we will have complained
  9413. // about it.
  9414. return StmtError();
  9415. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  9416. VK_RValue, Loc, nullptr);
  9417. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  9418. Expr *CallArgs[] = {
  9419. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  9420. };
  9421. ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  9422. Loc, CallArgs, Loc);
  9423. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  9424. return Call.getAs<Stmt>();
  9425. }
  9426. /// \brief Builds a statement that copies/moves the given entity from \p From to
  9427. /// \c To.
  9428. ///
  9429. /// This routine is used to copy/move the members of a class with an
  9430. /// implicitly-declared copy/move assignment operator. When the entities being
  9431. /// copied are arrays, this routine builds for loops to copy them.
  9432. ///
  9433. /// \param S The Sema object used for type-checking.
  9434. ///
  9435. /// \param Loc The location where the implicit copy/move is being generated.
  9436. ///
  9437. /// \param T The type of the expressions being copied/moved. Both expressions
  9438. /// must have this type.
  9439. ///
  9440. /// \param To The expression we are copying/moving to.
  9441. ///
  9442. /// \param From The expression we are copying/moving from.
  9443. ///
  9444. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  9445. /// Otherwise, it's a non-static member subobject.
  9446. ///
  9447. /// \param Copying Whether we're copying or moving.
  9448. ///
  9449. /// \param Depth Internal parameter recording the depth of the recursion.
  9450. ///
  9451. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  9452. /// if a memcpy should be used instead.
  9453. static StmtResult
  9454. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  9455. const ExprBuilder &To, const ExprBuilder &From,
  9456. bool CopyingBaseSubobject, bool Copying,
  9457. unsigned Depth = 0) {
  9458. // C++11 [class.copy]p28:
  9459. // Each subobject is assigned in the manner appropriate to its type:
  9460. //
  9461. // - if the subobject is of class type, as if by a call to operator= with
  9462. // the subobject as the object expression and the corresponding
  9463. // subobject of x as a single function argument (as if by explicit
  9464. // qualification; that is, ignoring any possible virtual overriding
  9465. // functions in more derived classes);
  9466. //
  9467. // C++03 [class.copy]p13:
  9468. // - if the subobject is of class type, the copy assignment operator for
  9469. // the class is used (as if by explicit qualification; that is,
  9470. // ignoring any possible virtual overriding functions in more derived
  9471. // classes);
  9472. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  9473. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  9474. // Look for operator=.
  9475. DeclarationName Name
  9476. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  9477. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  9478. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  9479. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  9480. // operator.
  9481. if (!S.getLangOpts().CPlusPlus11) {
  9482. LookupResult::Filter F = OpLookup.makeFilter();
  9483. while (F.hasNext()) {
  9484. NamedDecl *D = F.next();
  9485. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  9486. if (Method->isCopyAssignmentOperator() ||
  9487. (!Copying && Method->isMoveAssignmentOperator()))
  9488. continue;
  9489. F.erase();
  9490. }
  9491. F.done();
  9492. }
  9493. // Suppress the protected check (C++ [class.protected]) for each of the
  9494. // assignment operators we found. This strange dance is required when
  9495. // we're assigning via a base classes's copy-assignment operator. To
  9496. // ensure that we're getting the right base class subobject (without
  9497. // ambiguities), we need to cast "this" to that subobject type; to
  9498. // ensure that we don't go through the virtual call mechanism, we need
  9499. // to qualify the operator= name with the base class (see below). However,
  9500. // this means that if the base class has a protected copy assignment
  9501. // operator, the protected member access check will fail. So, we
  9502. // rewrite "protected" access to "public" access in this case, since we
  9503. // know by construction that we're calling from a derived class.
  9504. if (CopyingBaseSubobject) {
  9505. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  9506. L != LEnd; ++L) {
  9507. if (L.getAccess() == AS_protected)
  9508. L.setAccess(AS_public);
  9509. }
  9510. }
  9511. // Create the nested-name-specifier that will be used to qualify the
  9512. // reference to operator=; this is required to suppress the virtual
  9513. // call mechanism.
  9514. CXXScopeSpec SS;
  9515. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  9516. SS.MakeTrivial(S.Context,
  9517. NestedNameSpecifier::Create(S.Context, nullptr, false,
  9518. CanonicalT),
  9519. Loc);
  9520. // Create the reference to operator=.
  9521. ExprResult OpEqualRef
  9522. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
  9523. SS, /*TemplateKWLoc=*/SourceLocation(),
  9524. /*FirstQualifierInScope=*/nullptr,
  9525. OpLookup,
  9526. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  9527. /*SuppressQualifierCheck=*/true);
  9528. if (OpEqualRef.isInvalid())
  9529. return StmtError();
  9530. // Build the call to the assignment operator.
  9531. Expr *FromInst = From.build(S, Loc);
  9532. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  9533. OpEqualRef.getAs<Expr>(),
  9534. Loc, FromInst, Loc);
  9535. if (Call.isInvalid())
  9536. return StmtError();
  9537. // If we built a call to a trivial 'operator=' while copying an array,
  9538. // bail out. We'll replace the whole shebang with a memcpy.
  9539. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  9540. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  9541. return StmtResult((Stmt*)nullptr);
  9542. // Convert to an expression-statement, and clean up any produced
  9543. // temporaries.
  9544. return S.ActOnExprStmt(Call);
  9545. }
  9546. // - if the subobject is of scalar type, the built-in assignment
  9547. // operator is used.
  9548. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  9549. if (!ArrayTy) {
  9550. ExprResult Assignment = S.CreateBuiltinBinOp(
  9551. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  9552. if (Assignment.isInvalid())
  9553. return StmtError();
  9554. return S.ActOnExprStmt(Assignment);
  9555. }
  9556. // - if the subobject is an array, each element is assigned, in the
  9557. // manner appropriate to the element type;
  9558. // Construct a loop over the array bounds, e.g.,
  9559. //
  9560. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  9561. //
  9562. // that will copy each of the array elements.
  9563. QualType SizeType = S.Context.getSizeType();
  9564. // Create the iteration variable.
  9565. IdentifierInfo *IterationVarName = nullptr;
  9566. {
  9567. SmallString<8> Str;
  9568. llvm::raw_svector_ostream OS(Str);
  9569. OS << "__i" << Depth;
  9570. IterationVarName = &S.Context.Idents.get(OS.str());
  9571. }
  9572. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  9573. IterationVarName, SizeType,
  9574. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  9575. SC_None);
  9576. // Initialize the iteration variable to zero.
  9577. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  9578. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  9579. // Creates a reference to the iteration variable.
  9580. RefBuilder IterationVarRef(IterationVar, SizeType);
  9581. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  9582. // Create the DeclStmt that holds the iteration variable.
  9583. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  9584. // Subscript the "from" and "to" expressions with the iteration variable.
  9585. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  9586. MoveCastBuilder FromIndexMove(FromIndexCopy);
  9587. const ExprBuilder *FromIndex;
  9588. if (Copying)
  9589. FromIndex = &FromIndexCopy;
  9590. else
  9591. FromIndex = &FromIndexMove;
  9592. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  9593. // Build the copy/move for an individual element of the array.
  9594. StmtResult Copy =
  9595. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  9596. ToIndex, *FromIndex, CopyingBaseSubobject,
  9597. Copying, Depth + 1);
  9598. // Bail out if copying fails or if we determined that we should use memcpy.
  9599. if (Copy.isInvalid() || !Copy.get())
  9600. return Copy;
  9601. // Create the comparison against the array bound.
  9602. llvm::APInt Upper
  9603. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  9604. Expr *Comparison
  9605. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  9606. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  9607. BO_NE, S.Context.BoolTy,
  9608. VK_RValue, OK_Ordinary, Loc, false);
  9609. // Create the pre-increment of the iteration variable.
  9610. Expr *Increment
  9611. = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
  9612. SizeType, VK_LValue, OK_Ordinary, Loc);
  9613. // Construct the loop that copies all elements of this array.
  9614. return S.ActOnForStmt(
  9615. Loc, Loc, InitStmt,
  9616. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  9617. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  9618. }
  9619. static StmtResult
  9620. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  9621. const ExprBuilder &To, const ExprBuilder &From,
  9622. bool CopyingBaseSubobject, bool Copying) {
  9623. // Maybe we should use a memcpy?
  9624. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  9625. T.isTriviallyCopyableType(S.Context))
  9626. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  9627. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  9628. CopyingBaseSubobject,
  9629. Copying, 0));
  9630. // If we ended up picking a trivial assignment operator for an array of a
  9631. // non-trivially-copyable class type, just emit a memcpy.
  9632. if (!Result.isInvalid() && !Result.get())
  9633. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  9634. return Result;
  9635. }
  9636. Sema::ImplicitExceptionSpecification
  9637. Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
  9638. CXXRecordDecl *ClassDecl = MD->getParent();
  9639. ImplicitExceptionSpecification ExceptSpec(*this);
  9640. if (ClassDecl->isInvalidDecl())
  9641. return ExceptSpec;
  9642. const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
  9643. assert(T->getNumParams() == 1 && "not a copy assignment op");
  9644. unsigned ArgQuals =
  9645. T->getParamType(0).getNonReferenceType().getCVRQualifiers();
  9646. // C++ [except.spec]p14:
  9647. // An implicitly declared special member function (Clause 12) shall have an
  9648. // exception-specification. [...]
  9649. // It is unspecified whether or not an implicit copy assignment operator
  9650. // attempts to deduplicate calls to assignment operators of virtual bases are
  9651. // made. As such, this exception specification is effectively unspecified.
  9652. // Based on a similar decision made for constness in C++0x, we're erring on
  9653. // the side of assuming such calls to be made regardless of whether they
  9654. // actually happen.
  9655. for (const auto &Base : ClassDecl->bases()) {
  9656. if (Base.isVirtual())
  9657. continue;
  9658. CXXRecordDecl *BaseClassDecl
  9659. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9660. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  9661. ArgQuals, false, 0))
  9662. ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
  9663. }
  9664. for (const auto &Base : ClassDecl->vbases()) {
  9665. CXXRecordDecl *BaseClassDecl
  9666. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9667. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  9668. ArgQuals, false, 0))
  9669. ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
  9670. }
  9671. for (const auto *Field : ClassDecl->fields()) {
  9672. QualType FieldType = Context.getBaseElementType(Field->getType());
  9673. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  9674. if (CXXMethodDecl *CopyAssign =
  9675. LookupCopyingAssignment(FieldClassDecl,
  9676. ArgQuals | FieldType.getCVRQualifiers(),
  9677. false, 0))
  9678. ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
  9679. }
  9680. }
  9681. return ExceptSpec;
  9682. }
  9683. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  9684. // Note: The following rules are largely analoguous to the copy
  9685. // constructor rules. Note that virtual bases are not taken into account
  9686. // for determining the argument type of the operator. Note also that
  9687. // operators taking an object instead of a reference are allowed.
  9688. assert(ClassDecl->needsImplicitCopyAssignment());
  9689. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  9690. if (DSM.isAlreadyBeingDeclared())
  9691. return nullptr;
  9692. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  9693. QualType RetType = Context.getLValueReferenceType(ArgType);
  9694. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  9695. if (Const)
  9696. ArgType = ArgType.withConst();
  9697. ArgType = Context.getLValueReferenceType(ArgType);
  9698. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9699. CXXCopyAssignment,
  9700. Const);
  9701. // An implicitly-declared copy assignment operator is an inline public
  9702. // member of its class.
  9703. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  9704. SourceLocation ClassLoc = ClassDecl->getLocation();
  9705. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9706. CXXMethodDecl *CopyAssignment =
  9707. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  9708. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  9709. /*isInline=*/true, Constexpr, SourceLocation());
  9710. CopyAssignment->setAccess(AS_public);
  9711. CopyAssignment->setDefaulted();
  9712. CopyAssignment->setImplicit();
  9713. if (getLangOpts().CUDA) {
  9714. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  9715. CopyAssignment,
  9716. /* ConstRHS */ Const,
  9717. /* Diagnose */ false);
  9718. }
  9719. // Build an exception specification pointing back at this member.
  9720. FunctionProtoType::ExtProtoInfo EPI =
  9721. getImplicitMethodEPI(*this, CopyAssignment);
  9722. CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  9723. // Add the parameter to the operator.
  9724. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  9725. ClassLoc, ClassLoc,
  9726. /*Id=*/nullptr, ArgType,
  9727. /*TInfo=*/nullptr, SC_None,
  9728. nullptr);
  9729. CopyAssignment->setParams(FromParam);
  9730. CopyAssignment->setTrivial(
  9731. ClassDecl->needsOverloadResolutionForCopyAssignment()
  9732. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  9733. : ClassDecl->hasTrivialCopyAssignment());
  9734. // Note that we have added this copy-assignment operator.
  9735. ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  9736. Scope *S = getScopeForContext(ClassDecl);
  9737. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  9738. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  9739. SetDeclDeleted(CopyAssignment, ClassLoc);
  9740. if (S)
  9741. PushOnScopeChains(CopyAssignment, S, false);
  9742. ClassDecl->addDecl(CopyAssignment);
  9743. return CopyAssignment;
  9744. }
  9745. /// Diagnose an implicit copy operation for a class which is odr-used, but
  9746. /// which is deprecated because the class has a user-declared copy constructor,
  9747. /// copy assignment operator, or destructor.
  9748. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
  9749. SourceLocation UseLoc) {
  9750. assert(CopyOp->isImplicit());
  9751. CXXRecordDecl *RD = CopyOp->getParent();
  9752. CXXMethodDecl *UserDeclaredOperation = nullptr;
  9753. // In Microsoft mode, assignment operations don't affect constructors and
  9754. // vice versa.
  9755. if (RD->hasUserDeclaredDestructor()) {
  9756. UserDeclaredOperation = RD->getDestructor();
  9757. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  9758. RD->hasUserDeclaredCopyConstructor() &&
  9759. !S.getLangOpts().MSVCCompat) {
  9760. // Find any user-declared copy constructor.
  9761. for (auto *I : RD->ctors()) {
  9762. if (I->isCopyConstructor()) {
  9763. UserDeclaredOperation = I;
  9764. break;
  9765. }
  9766. }
  9767. assert(UserDeclaredOperation);
  9768. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  9769. RD->hasUserDeclaredCopyAssignment() &&
  9770. !S.getLangOpts().MSVCCompat) {
  9771. // Find any user-declared move assignment operator.
  9772. for (auto *I : RD->methods()) {
  9773. if (I->isCopyAssignmentOperator()) {
  9774. UserDeclaredOperation = I;
  9775. break;
  9776. }
  9777. }
  9778. assert(UserDeclaredOperation);
  9779. }
  9780. if (UserDeclaredOperation) {
  9781. S.Diag(UserDeclaredOperation->getLocation(),
  9782. diag::warn_deprecated_copy_operation)
  9783. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  9784. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  9785. S.Diag(UseLoc, diag::note_member_synthesized_at)
  9786. << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
  9787. : Sema::CXXCopyAssignment)
  9788. << RD;
  9789. }
  9790. }
  9791. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  9792. CXXMethodDecl *CopyAssignOperator) {
  9793. assert((CopyAssignOperator->isDefaulted() &&
  9794. CopyAssignOperator->isOverloadedOperator() &&
  9795. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  9796. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  9797. !CopyAssignOperator->isDeleted()) &&
  9798. "DefineImplicitCopyAssignment called for wrong function");
  9799. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  9800. if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
  9801. CopyAssignOperator->setInvalidDecl();
  9802. return;
  9803. }
  9804. // C++11 [class.copy]p18:
  9805. // The [definition of an implicitly declared copy assignment operator] is
  9806. // deprecated if the class has a user-declared copy constructor or a
  9807. // user-declared destructor.
  9808. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  9809. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
  9810. CopyAssignOperator->markUsed(Context);
  9811. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  9812. DiagnosticErrorTrap Trap(Diags);
  9813. // C++0x [class.copy]p30:
  9814. // The implicitly-defined or explicitly-defaulted copy assignment operator
  9815. // for a non-union class X performs memberwise copy assignment of its
  9816. // subobjects. The direct base classes of X are assigned first, in the
  9817. // order of their declaration in the base-specifier-list, and then the
  9818. // immediate non-static data members of X are assigned, in the order in
  9819. // which they were declared in the class definition.
  9820. // The statements that form the synthesized function body.
  9821. SmallVector<Stmt*, 8> Statements;
  9822. // The parameter for the "other" object, which we are copying from.
  9823. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  9824. Qualifiers OtherQuals = Other->getType().getQualifiers();
  9825. QualType OtherRefType = Other->getType();
  9826. if (const LValueReferenceType *OtherRef
  9827. = OtherRefType->getAs<LValueReferenceType>()) {
  9828. OtherRefType = OtherRef->getPointeeType();
  9829. OtherQuals = OtherRefType.getQualifiers();
  9830. }
  9831. // Our location for everything implicitly-generated.
  9832. SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
  9833. ? CopyAssignOperator->getLocEnd()
  9834. : CopyAssignOperator->getLocation();
  9835. // Builds a DeclRefExpr for the "other" object.
  9836. RefBuilder OtherRef(Other, OtherRefType);
  9837. // Builds the "this" pointer.
  9838. ThisBuilder This;
  9839. // Assign base classes.
  9840. bool Invalid = false;
  9841. for (auto &Base : ClassDecl->bases()) {
  9842. // Form the assignment:
  9843. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  9844. QualType BaseType = Base.getType().getUnqualifiedType();
  9845. if (!BaseType->isRecordType()) {
  9846. Invalid = true;
  9847. continue;
  9848. }
  9849. CXXCastPath BasePath;
  9850. BasePath.push_back(&Base);
  9851. // Construct the "from" expression, which is an implicit cast to the
  9852. // appropriately-qualified base type.
  9853. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  9854. VK_LValue, BasePath);
  9855. // Dereference "this".
  9856. DerefBuilder DerefThis(This);
  9857. CastBuilder To(DerefThis,
  9858. Context.getCVRQualifiedType(
  9859. BaseType, CopyAssignOperator->getTypeQualifiers()),
  9860. VK_LValue, BasePath);
  9861. // Build the copy.
  9862. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  9863. To, From,
  9864. /*CopyingBaseSubobject=*/true,
  9865. /*Copying=*/true);
  9866. if (Copy.isInvalid()) {
  9867. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9868. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  9869. CopyAssignOperator->setInvalidDecl();
  9870. return;
  9871. }
  9872. // Success! Record the copy.
  9873. Statements.push_back(Copy.getAs<Expr>());
  9874. }
  9875. // Assign non-static members.
  9876. for (auto *Field : ClassDecl->fields()) {
  9877. // FIXME: We should form some kind of AST representation for the implied
  9878. // memcpy in a union copy operation.
  9879. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  9880. continue;
  9881. if (Field->isInvalidDecl()) {
  9882. Invalid = true;
  9883. continue;
  9884. }
  9885. // Check for members of reference type; we can't copy those.
  9886. if (Field->getType()->isReferenceType()) {
  9887. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  9888. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  9889. Diag(Field->getLocation(), diag::note_declared_at);
  9890. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9891. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  9892. Invalid = true;
  9893. continue;
  9894. }
  9895. // Check for members of const-qualified, non-class type.
  9896. QualType BaseType = Context.getBaseElementType(Field->getType());
  9897. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  9898. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  9899. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  9900. Diag(Field->getLocation(), diag::note_declared_at);
  9901. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9902. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  9903. Invalid = true;
  9904. continue;
  9905. }
  9906. // Suppress assigning zero-width bitfields.
  9907. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  9908. continue;
  9909. QualType FieldType = Field->getType().getNonReferenceType();
  9910. if (FieldType->isIncompleteArrayType()) {
  9911. assert(ClassDecl->hasFlexibleArrayMember() &&
  9912. "Incomplete array type is not valid");
  9913. continue;
  9914. }
  9915. // Build references to the field in the object we're copying from and to.
  9916. CXXScopeSpec SS; // Intentionally empty
  9917. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  9918. LookupMemberName);
  9919. MemberLookup.addDecl(Field);
  9920. MemberLookup.resolveKind();
  9921. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  9922. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  9923. // Build the copy of this field.
  9924. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  9925. To, From,
  9926. /*CopyingBaseSubobject=*/false,
  9927. /*Copying=*/true);
  9928. if (Copy.isInvalid()) {
  9929. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9930. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  9931. CopyAssignOperator->setInvalidDecl();
  9932. return;
  9933. }
  9934. // Success! Record the copy.
  9935. Statements.push_back(Copy.getAs<Stmt>());
  9936. }
  9937. if (!Invalid) {
  9938. // Add a "return *this;"
  9939. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  9940. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  9941. if (Return.isInvalid())
  9942. Invalid = true;
  9943. else {
  9944. Statements.push_back(Return.getAs<Stmt>());
  9945. if (Trap.hasErrorOccurred()) {
  9946. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9947. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  9948. Invalid = true;
  9949. }
  9950. }
  9951. }
  9952. // The exception specification is needed because we are defining the
  9953. // function.
  9954. ResolveExceptionSpec(CurrentLocation,
  9955. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  9956. if (Invalid) {
  9957. CopyAssignOperator->setInvalidDecl();
  9958. return;
  9959. }
  9960. StmtResult Body;
  9961. {
  9962. CompoundScopeRAII CompoundScope(*this);
  9963. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  9964. /*isStmtExpr=*/false);
  9965. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  9966. }
  9967. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  9968. if (ASTMutationListener *L = getASTMutationListener()) {
  9969. L->CompletedImplicitDefinition(CopyAssignOperator);
  9970. }
  9971. }
  9972. Sema::ImplicitExceptionSpecification
  9973. Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
  9974. CXXRecordDecl *ClassDecl = MD->getParent();
  9975. ImplicitExceptionSpecification ExceptSpec(*this);
  9976. if (ClassDecl->isInvalidDecl())
  9977. return ExceptSpec;
  9978. // C++0x [except.spec]p14:
  9979. // An implicitly declared special member function (Clause 12) shall have an
  9980. // exception-specification. [...]
  9981. // It is unspecified whether or not an implicit move assignment operator
  9982. // attempts to deduplicate calls to assignment operators of virtual bases are
  9983. // made. As such, this exception specification is effectively unspecified.
  9984. // Based on a similar decision made for constness in C++0x, we're erring on
  9985. // the side of assuming such calls to be made regardless of whether they
  9986. // actually happen.
  9987. // Note that a move constructor is not implicitly declared when there are
  9988. // virtual bases, but it can still be user-declared and explicitly defaulted.
  9989. for (const auto &Base : ClassDecl->bases()) {
  9990. if (Base.isVirtual())
  9991. continue;
  9992. CXXRecordDecl *BaseClassDecl
  9993. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9994. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  9995. 0, false, 0))
  9996. ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
  9997. }
  9998. for (const auto &Base : ClassDecl->vbases()) {
  9999. CXXRecordDecl *BaseClassDecl
  10000. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  10001. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  10002. 0, false, 0))
  10003. ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
  10004. }
  10005. for (const auto *Field : ClassDecl->fields()) {
  10006. QualType FieldType = Context.getBaseElementType(Field->getType());
  10007. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  10008. if (CXXMethodDecl *MoveAssign =
  10009. LookupMovingAssignment(FieldClassDecl,
  10010. FieldType.getCVRQualifiers(),
  10011. false, 0))
  10012. ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
  10013. }
  10014. }
  10015. return ExceptSpec;
  10016. }
  10017. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  10018. assert(ClassDecl->needsImplicitMoveAssignment());
  10019. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  10020. if (DSM.isAlreadyBeingDeclared())
  10021. return nullptr;
  10022. // Note: The following rules are largely analoguous to the move
  10023. // constructor rules.
  10024. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  10025. QualType RetType = Context.getLValueReferenceType(ArgType);
  10026. ArgType = Context.getRValueReferenceType(ArgType);
  10027. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10028. CXXMoveAssignment,
  10029. false);
  10030. // An implicitly-declared move assignment operator is an inline public
  10031. // member of its class.
  10032. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  10033. SourceLocation ClassLoc = ClassDecl->getLocation();
  10034. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10035. CXXMethodDecl *MoveAssignment =
  10036. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  10037. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  10038. /*isInline=*/true, Constexpr, SourceLocation());
  10039. MoveAssignment->setAccess(AS_public);
  10040. MoveAssignment->setDefaulted();
  10041. MoveAssignment->setImplicit();
  10042. if (getLangOpts().CUDA) {
  10043. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  10044. MoveAssignment,
  10045. /* ConstRHS */ false,
  10046. /* Diagnose */ false);
  10047. }
  10048. // Build an exception specification pointing back at this member.
  10049. FunctionProtoType::ExtProtoInfo EPI =
  10050. getImplicitMethodEPI(*this, MoveAssignment);
  10051. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
  10052. // Add the parameter to the operator.
  10053. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  10054. ClassLoc, ClassLoc,
  10055. /*Id=*/nullptr, ArgType,
  10056. /*TInfo=*/nullptr, SC_None,
  10057. nullptr);
  10058. MoveAssignment->setParams(FromParam);
  10059. MoveAssignment->setTrivial(
  10060. ClassDecl->needsOverloadResolutionForMoveAssignment()
  10061. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  10062. : ClassDecl->hasTrivialMoveAssignment());
  10063. // Note that we have added this copy-assignment operator.
  10064. ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  10065. Scope *S = getScopeForContext(ClassDecl);
  10066. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  10067. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  10068. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  10069. SetDeclDeleted(MoveAssignment, ClassLoc);
  10070. }
  10071. if (S)
  10072. PushOnScopeChains(MoveAssignment, S, false);
  10073. ClassDecl->addDecl(MoveAssignment);
  10074. return MoveAssignment;
  10075. }
  10076. /// Check if we're implicitly defining a move assignment operator for a class
  10077. /// with virtual bases. Such a move assignment might move-assign the virtual
  10078. /// base multiple times.
  10079. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  10080. SourceLocation CurrentLocation) {
  10081. assert(!Class->isDependentContext() && "should not define dependent move");
  10082. // Only a virtual base could get implicitly move-assigned multiple times.
  10083. // Only a non-trivial move assignment can observe this. We only want to
  10084. // diagnose if we implicitly define an assignment operator that assigns
  10085. // two base classes, both of which move-assign the same virtual base.
  10086. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  10087. Class->getNumBases() < 2)
  10088. return;
  10089. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  10090. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  10091. VBaseMap VBases;
  10092. for (auto &BI : Class->bases()) {
  10093. Worklist.push_back(&BI);
  10094. while (!Worklist.empty()) {
  10095. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  10096. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  10097. // If the base has no non-trivial move assignment operators,
  10098. // we don't care about moves from it.
  10099. if (!Base->hasNonTrivialMoveAssignment())
  10100. continue;
  10101. // If there's nothing virtual here, skip it.
  10102. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  10103. continue;
  10104. // If we're not actually going to call a move assignment for this base,
  10105. // or the selected move assignment is trivial, skip it.
  10106. Sema::SpecialMemberOverloadResult *SMOR =
  10107. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  10108. /*ConstArg*/false, /*VolatileArg*/false,
  10109. /*RValueThis*/true, /*ConstThis*/false,
  10110. /*VolatileThis*/false);
  10111. if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
  10112. !SMOR->getMethod()->isMoveAssignmentOperator())
  10113. continue;
  10114. if (BaseSpec->isVirtual()) {
  10115. // We're going to move-assign this virtual base, and its move
  10116. // assignment operator is not trivial. If this can happen for
  10117. // multiple distinct direct bases of Class, diagnose it. (If it
  10118. // only happens in one base, we'll diagnose it when synthesizing
  10119. // that base class's move assignment operator.)
  10120. CXXBaseSpecifier *&Existing =
  10121. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  10122. .first->second;
  10123. if (Existing && Existing != &BI) {
  10124. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  10125. << Class << Base;
  10126. S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
  10127. << (Base->getCanonicalDecl() ==
  10128. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10129. << Base << Existing->getType() << Existing->getSourceRange();
  10130. S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
  10131. << (Base->getCanonicalDecl() ==
  10132. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  10133. << Base << BI.getType() << BaseSpec->getSourceRange();
  10134. // Only diagnose each vbase once.
  10135. Existing = nullptr;
  10136. }
  10137. } else {
  10138. // Only walk over bases that have defaulted move assignment operators.
  10139. // We assume that any user-provided move assignment operator handles
  10140. // the multiple-moves-of-vbase case itself somehow.
  10141. if (!SMOR->getMethod()->isDefaulted())
  10142. continue;
  10143. // We're going to move the base classes of Base. Add them to the list.
  10144. for (auto &BI : Base->bases())
  10145. Worklist.push_back(&BI);
  10146. }
  10147. }
  10148. }
  10149. }
  10150. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  10151. CXXMethodDecl *MoveAssignOperator) {
  10152. assert((MoveAssignOperator->isDefaulted() &&
  10153. MoveAssignOperator->isOverloadedOperator() &&
  10154. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  10155. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  10156. !MoveAssignOperator->isDeleted()) &&
  10157. "DefineImplicitMoveAssignment called for wrong function");
  10158. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  10159. if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
  10160. MoveAssignOperator->setInvalidDecl();
  10161. return;
  10162. }
  10163. MoveAssignOperator->markUsed(Context);
  10164. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  10165. DiagnosticErrorTrap Trap(Diags);
  10166. // C++0x [class.copy]p28:
  10167. // The implicitly-defined or move assignment operator for a non-union class
  10168. // X performs memberwise move assignment of its subobjects. The direct base
  10169. // classes of X are assigned first, in the order of their declaration in the
  10170. // base-specifier-list, and then the immediate non-static data members of X
  10171. // are assigned, in the order in which they were declared in the class
  10172. // definition.
  10173. // Issue a warning if our implicit move assignment operator will move
  10174. // from a virtual base more than once.
  10175. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  10176. // The statements that form the synthesized function body.
  10177. SmallVector<Stmt*, 8> Statements;
  10178. // The parameter for the "other" object, which we are move from.
  10179. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  10180. QualType OtherRefType = Other->getType()->
  10181. getAs<RValueReferenceType>()->getPointeeType();
  10182. assert(!OtherRefType.getQualifiers() &&
  10183. "Bad argument type of defaulted move assignment");
  10184. // Our location for everything implicitly-generated.
  10185. SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
  10186. ? MoveAssignOperator->getLocEnd()
  10187. : MoveAssignOperator->getLocation();
  10188. // Builds a reference to the "other" object.
  10189. RefBuilder OtherRef(Other, OtherRefType);
  10190. // Cast to rvalue.
  10191. MoveCastBuilder MoveOther(OtherRef);
  10192. // Builds the "this" pointer.
  10193. ThisBuilder This;
  10194. // Assign base classes.
  10195. bool Invalid = false;
  10196. for (auto &Base : ClassDecl->bases()) {
  10197. // C++11 [class.copy]p28:
  10198. // It is unspecified whether subobjects representing virtual base classes
  10199. // are assigned more than once by the implicitly-defined copy assignment
  10200. // operator.
  10201. // FIXME: Do not assign to a vbase that will be assigned by some other base
  10202. // class. For a move-assignment, this can result in the vbase being moved
  10203. // multiple times.
  10204. // Form the assignment:
  10205. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  10206. QualType BaseType = Base.getType().getUnqualifiedType();
  10207. if (!BaseType->isRecordType()) {
  10208. Invalid = true;
  10209. continue;
  10210. }
  10211. CXXCastPath BasePath;
  10212. BasePath.push_back(&Base);
  10213. // Construct the "from" expression, which is an implicit cast to the
  10214. // appropriately-qualified base type.
  10215. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  10216. // Dereference "this".
  10217. DerefBuilder DerefThis(This);
  10218. // Implicitly cast "this" to the appropriately-qualified base type.
  10219. CastBuilder To(DerefThis,
  10220. Context.getCVRQualifiedType(
  10221. BaseType, MoveAssignOperator->getTypeQualifiers()),
  10222. VK_LValue, BasePath);
  10223. // Build the move.
  10224. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  10225. To, From,
  10226. /*CopyingBaseSubobject=*/true,
  10227. /*Copying=*/false);
  10228. if (Move.isInvalid()) {
  10229. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10230. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  10231. MoveAssignOperator->setInvalidDecl();
  10232. return;
  10233. }
  10234. // Success! Record the move.
  10235. Statements.push_back(Move.getAs<Expr>());
  10236. }
  10237. // Assign non-static members.
  10238. for (auto *Field : ClassDecl->fields()) {
  10239. // FIXME: We should form some kind of AST representation for the implied
  10240. // memcpy in a union copy operation.
  10241. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  10242. continue;
  10243. if (Field->isInvalidDecl()) {
  10244. Invalid = true;
  10245. continue;
  10246. }
  10247. // Check for members of reference type; we can't move those.
  10248. if (Field->getType()->isReferenceType()) {
  10249. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10250. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  10251. Diag(Field->getLocation(), diag::note_declared_at);
  10252. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10253. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  10254. Invalid = true;
  10255. continue;
  10256. }
  10257. // Check for members of const-qualified, non-class type.
  10258. QualType BaseType = Context.getBaseElementType(Field->getType());
  10259. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  10260. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  10261. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  10262. Diag(Field->getLocation(), diag::note_declared_at);
  10263. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10264. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  10265. Invalid = true;
  10266. continue;
  10267. }
  10268. // Suppress assigning zero-width bitfields.
  10269. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  10270. continue;
  10271. QualType FieldType = Field->getType().getNonReferenceType();
  10272. if (FieldType->isIncompleteArrayType()) {
  10273. assert(ClassDecl->hasFlexibleArrayMember() &&
  10274. "Incomplete array type is not valid");
  10275. continue;
  10276. }
  10277. // Build references to the field in the object we're copying from and to.
  10278. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  10279. LookupMemberName);
  10280. MemberLookup.addDecl(Field);
  10281. MemberLookup.resolveKind();
  10282. MemberBuilder From(MoveOther, OtherRefType,
  10283. /*IsArrow=*/false, MemberLookup);
  10284. MemberBuilder To(This, getCurrentThisType(),
  10285. /*IsArrow=*/true, MemberLookup);
  10286. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  10287. "Member reference with rvalue base must be rvalue except for reference "
  10288. "members, which aren't allowed for move assignment.");
  10289. // Build the move of this field.
  10290. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  10291. To, From,
  10292. /*CopyingBaseSubobject=*/false,
  10293. /*Copying=*/false);
  10294. if (Move.isInvalid()) {
  10295. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10296. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  10297. MoveAssignOperator->setInvalidDecl();
  10298. return;
  10299. }
  10300. // Success! Record the copy.
  10301. Statements.push_back(Move.getAs<Stmt>());
  10302. }
  10303. if (!Invalid) {
  10304. // Add a "return *this;"
  10305. ExprResult ThisObj =
  10306. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  10307. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  10308. if (Return.isInvalid())
  10309. Invalid = true;
  10310. else {
  10311. Statements.push_back(Return.getAs<Stmt>());
  10312. if (Trap.hasErrorOccurred()) {
  10313. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10314. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  10315. Invalid = true;
  10316. }
  10317. }
  10318. }
  10319. // The exception specification is needed because we are defining the
  10320. // function.
  10321. ResolveExceptionSpec(CurrentLocation,
  10322. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  10323. if (Invalid) {
  10324. MoveAssignOperator->setInvalidDecl();
  10325. return;
  10326. }
  10327. StmtResult Body;
  10328. {
  10329. CompoundScopeRAII CompoundScope(*this);
  10330. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  10331. /*isStmtExpr=*/false);
  10332. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  10333. }
  10334. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  10335. if (ASTMutationListener *L = getASTMutationListener()) {
  10336. L->CompletedImplicitDefinition(MoveAssignOperator);
  10337. }
  10338. }
  10339. Sema::ImplicitExceptionSpecification
  10340. Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
  10341. CXXRecordDecl *ClassDecl = MD->getParent();
  10342. ImplicitExceptionSpecification ExceptSpec(*this);
  10343. if (ClassDecl->isInvalidDecl())
  10344. return ExceptSpec;
  10345. const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
  10346. assert(T->getNumParams() >= 1 && "not a copy ctor");
  10347. unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
  10348. // C++ [except.spec]p14:
  10349. // An implicitly declared special member function (Clause 12) shall have an
  10350. // exception-specification. [...]
  10351. for (const auto &Base : ClassDecl->bases()) {
  10352. // Virtual bases are handled below.
  10353. if (Base.isVirtual())
  10354. continue;
  10355. CXXRecordDecl *BaseClassDecl
  10356. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  10357. if (CXXConstructorDecl *CopyConstructor =
  10358. LookupCopyingConstructor(BaseClassDecl, Quals))
  10359. ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
  10360. }
  10361. for (const auto &Base : ClassDecl->vbases()) {
  10362. CXXRecordDecl *BaseClassDecl
  10363. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  10364. if (CXXConstructorDecl *CopyConstructor =
  10365. LookupCopyingConstructor(BaseClassDecl, Quals))
  10366. ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
  10367. }
  10368. for (const auto *Field : ClassDecl->fields()) {
  10369. QualType FieldType = Context.getBaseElementType(Field->getType());
  10370. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  10371. if (CXXConstructorDecl *CopyConstructor =
  10372. LookupCopyingConstructor(FieldClassDecl,
  10373. Quals | FieldType.getCVRQualifiers()))
  10374. ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
  10375. }
  10376. }
  10377. return ExceptSpec;
  10378. }
  10379. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  10380. CXXRecordDecl *ClassDecl) {
  10381. // C++ [class.copy]p4:
  10382. // If the class definition does not explicitly declare a copy
  10383. // constructor, one is declared implicitly.
  10384. assert(ClassDecl->needsImplicitCopyConstructor());
  10385. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  10386. if (DSM.isAlreadyBeingDeclared())
  10387. return nullptr;
  10388. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10389. QualType ArgType = ClassType;
  10390. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  10391. if (Const)
  10392. ArgType = ArgType.withConst();
  10393. ArgType = Context.getLValueReferenceType(ArgType);
  10394. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10395. CXXCopyConstructor,
  10396. Const);
  10397. DeclarationName Name
  10398. = Context.DeclarationNames.getCXXConstructorName(
  10399. Context.getCanonicalType(ClassType));
  10400. SourceLocation ClassLoc = ClassDecl->getLocation();
  10401. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10402. // An implicitly-declared copy constructor is an inline public
  10403. // member of its class.
  10404. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  10405. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10406. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  10407. Constexpr);
  10408. CopyConstructor->setAccess(AS_public);
  10409. CopyConstructor->setDefaulted();
  10410. if (getLangOpts().CUDA) {
  10411. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  10412. CopyConstructor,
  10413. /* ConstRHS */ Const,
  10414. /* Diagnose */ false);
  10415. }
  10416. // Build an exception specification pointing back at this member.
  10417. FunctionProtoType::ExtProtoInfo EPI =
  10418. getImplicitMethodEPI(*this, CopyConstructor);
  10419. CopyConstructor->setType(
  10420. Context.getFunctionType(Context.VoidTy, ArgType, EPI));
  10421. // Add the parameter to the constructor.
  10422. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  10423. ClassLoc, ClassLoc,
  10424. /*IdentifierInfo=*/nullptr,
  10425. ArgType, /*TInfo=*/nullptr,
  10426. SC_None, nullptr);
  10427. CopyConstructor->setParams(FromParam);
  10428. CopyConstructor->setTrivial(
  10429. ClassDecl->needsOverloadResolutionForCopyConstructor()
  10430. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  10431. : ClassDecl->hasTrivialCopyConstructor());
  10432. // Note that we have declared this constructor.
  10433. ++ASTContext::NumImplicitCopyConstructorsDeclared;
  10434. Scope *S = getScopeForContext(ClassDecl);
  10435. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  10436. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
  10437. SetDeclDeleted(CopyConstructor, ClassLoc);
  10438. if (S)
  10439. PushOnScopeChains(CopyConstructor, S, false);
  10440. ClassDecl->addDecl(CopyConstructor);
  10441. return CopyConstructor;
  10442. }
  10443. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  10444. CXXConstructorDecl *CopyConstructor) {
  10445. assert((CopyConstructor->isDefaulted() &&
  10446. CopyConstructor->isCopyConstructor() &&
  10447. !CopyConstructor->doesThisDeclarationHaveABody() &&
  10448. !CopyConstructor->isDeleted()) &&
  10449. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  10450. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  10451. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  10452. // C++11 [class.copy]p7:
  10453. // The [definition of an implicitly declared copy constructor] is
  10454. // deprecated if the class has a user-declared copy assignment operator
  10455. // or a user-declared destructor.
  10456. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  10457. diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
  10458. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  10459. DiagnosticErrorTrap Trap(Diags);
  10460. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
  10461. Trap.hasErrorOccurred()) {
  10462. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10463. << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
  10464. CopyConstructor->setInvalidDecl();
  10465. } else {
  10466. SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
  10467. ? CopyConstructor->getLocEnd()
  10468. : CopyConstructor->getLocation();
  10469. Sema::CompoundScopeRAII CompoundScope(*this);
  10470. CopyConstructor->setBody(
  10471. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  10472. }
  10473. // The exception specification is needed because we are defining the
  10474. // function.
  10475. ResolveExceptionSpec(CurrentLocation,
  10476. CopyConstructor->getType()->castAs<FunctionProtoType>());
  10477. CopyConstructor->markUsed(Context);
  10478. MarkVTableUsed(CurrentLocation, ClassDecl);
  10479. if (ASTMutationListener *L = getASTMutationListener()) {
  10480. L->CompletedImplicitDefinition(CopyConstructor);
  10481. }
  10482. }
  10483. Sema::ImplicitExceptionSpecification
  10484. Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
  10485. CXXRecordDecl *ClassDecl = MD->getParent();
  10486. // C++ [except.spec]p14:
  10487. // An implicitly declared special member function (Clause 12) shall have an
  10488. // exception-specification. [...]
  10489. ImplicitExceptionSpecification ExceptSpec(*this);
  10490. if (ClassDecl->isInvalidDecl())
  10491. return ExceptSpec;
  10492. // Direct base-class constructors.
  10493. for (const auto &B : ClassDecl->bases()) {
  10494. if (B.isVirtual()) // Handled below.
  10495. continue;
  10496. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  10497. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  10498. CXXConstructorDecl *Constructor =
  10499. LookupMovingConstructor(BaseClassDecl, 0);
  10500. // If this is a deleted function, add it anyway. This might be conformant
  10501. // with the standard. This might not. I'm not sure. It might not matter.
  10502. if (Constructor)
  10503. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  10504. }
  10505. }
  10506. // Virtual base-class constructors.
  10507. for (const auto &B : ClassDecl->vbases()) {
  10508. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  10509. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  10510. CXXConstructorDecl *Constructor =
  10511. LookupMovingConstructor(BaseClassDecl, 0);
  10512. // If this is a deleted function, add it anyway. This might be conformant
  10513. // with the standard. This might not. I'm not sure. It might not matter.
  10514. if (Constructor)
  10515. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  10516. }
  10517. }
  10518. // Field constructors.
  10519. for (const auto *F : ClassDecl->fields()) {
  10520. QualType FieldType = Context.getBaseElementType(F->getType());
  10521. if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
  10522. CXXConstructorDecl *Constructor =
  10523. LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
  10524. // If this is a deleted function, add it anyway. This might be conformant
  10525. // with the standard. This might not. I'm not sure. It might not matter.
  10526. // In particular, the problem is that this function never gets called. It
  10527. // might just be ill-formed because this function attempts to refer to
  10528. // a deleted function here.
  10529. if (Constructor)
  10530. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  10531. }
  10532. }
  10533. return ExceptSpec;
  10534. }
  10535. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  10536. CXXRecordDecl *ClassDecl) {
  10537. assert(ClassDecl->needsImplicitMoveConstructor());
  10538. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  10539. if (DSM.isAlreadyBeingDeclared())
  10540. return nullptr;
  10541. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  10542. QualType ArgType = Context.getRValueReferenceType(ClassType);
  10543. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  10544. CXXMoveConstructor,
  10545. false);
  10546. DeclarationName Name
  10547. = Context.DeclarationNames.getCXXConstructorName(
  10548. Context.getCanonicalType(ClassType));
  10549. SourceLocation ClassLoc = ClassDecl->getLocation();
  10550. DeclarationNameInfo NameInfo(Name, ClassLoc);
  10551. // C++11 [class.copy]p11:
  10552. // An implicitly-declared copy/move constructor is an inline public
  10553. // member of its class.
  10554. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  10555. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  10556. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  10557. Constexpr);
  10558. MoveConstructor->setAccess(AS_public);
  10559. MoveConstructor->setDefaulted();
  10560. if (getLangOpts().CUDA) {
  10561. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  10562. MoveConstructor,
  10563. /* ConstRHS */ false,
  10564. /* Diagnose */ false);
  10565. }
  10566. // Build an exception specification pointing back at this member.
  10567. FunctionProtoType::ExtProtoInfo EPI =
  10568. getImplicitMethodEPI(*this, MoveConstructor);
  10569. MoveConstructor->setType(
  10570. Context.getFunctionType(Context.VoidTy, ArgType, EPI));
  10571. // Add the parameter to the constructor.
  10572. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  10573. ClassLoc, ClassLoc,
  10574. /*IdentifierInfo=*/nullptr,
  10575. ArgType, /*TInfo=*/nullptr,
  10576. SC_None, nullptr);
  10577. MoveConstructor->setParams(FromParam);
  10578. MoveConstructor->setTrivial(
  10579. ClassDecl->needsOverloadResolutionForMoveConstructor()
  10580. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  10581. : ClassDecl->hasTrivialMoveConstructor());
  10582. // Note that we have declared this constructor.
  10583. ++ASTContext::NumImplicitMoveConstructorsDeclared;
  10584. Scope *S = getScopeForContext(ClassDecl);
  10585. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  10586. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  10587. ClassDecl->setImplicitMoveConstructorIsDeleted();
  10588. SetDeclDeleted(MoveConstructor, ClassLoc);
  10589. }
  10590. if (S)
  10591. PushOnScopeChains(MoveConstructor, S, false);
  10592. ClassDecl->addDecl(MoveConstructor);
  10593. return MoveConstructor;
  10594. }
  10595. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  10596. CXXConstructorDecl *MoveConstructor) {
  10597. assert((MoveConstructor->isDefaulted() &&
  10598. MoveConstructor->isMoveConstructor() &&
  10599. !MoveConstructor->doesThisDeclarationHaveABody() &&
  10600. !MoveConstructor->isDeleted()) &&
  10601. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  10602. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  10603. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  10604. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  10605. DiagnosticErrorTrap Trap(Diags);
  10606. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
  10607. Trap.hasErrorOccurred()) {
  10608. Diag(CurrentLocation, diag::note_member_synthesized_at)
  10609. << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
  10610. MoveConstructor->setInvalidDecl();
  10611. } else {
  10612. SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
  10613. ? MoveConstructor->getLocEnd()
  10614. : MoveConstructor->getLocation();
  10615. Sema::CompoundScopeRAII CompoundScope(*this);
  10616. MoveConstructor->setBody(ActOnCompoundStmt(
  10617. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  10618. }
  10619. // The exception specification is needed because we are defining the
  10620. // function.
  10621. ResolveExceptionSpec(CurrentLocation,
  10622. MoveConstructor->getType()->castAs<FunctionProtoType>());
  10623. MoveConstructor->markUsed(Context);
  10624. MarkVTableUsed(CurrentLocation, ClassDecl);
  10625. if (ASTMutationListener *L = getASTMutationListener()) {
  10626. L->CompletedImplicitDefinition(MoveConstructor);
  10627. }
  10628. }
  10629. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  10630. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  10631. }
  10632. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  10633. SourceLocation CurrentLocation,
  10634. CXXConversionDecl *Conv) {
  10635. CXXRecordDecl *Lambda = Conv->getParent();
  10636. CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  10637. // If we are defining a specialization of a conversion to function-ptr
  10638. // cache the deduced template arguments for this specialization
  10639. // so that we can use them to retrieve the corresponding call-operator
  10640. // and static-invoker.
  10641. const TemplateArgumentList *DeducedTemplateArgs = nullptr;
  10642. // Retrieve the corresponding call-operator specialization.
  10643. if (Lambda->isGenericLambda()) {
  10644. assert(Conv->isFunctionTemplateSpecialization());
  10645. FunctionTemplateDecl *CallOpTemplate =
  10646. CallOp->getDescribedFunctionTemplate();
  10647. DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
  10648. void *InsertPos = nullptr;
  10649. FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
  10650. DeducedTemplateArgs->asArray(),
  10651. InsertPos);
  10652. assert(CallOpSpec &&
  10653. "Conversion operator must have a corresponding call operator");
  10654. CallOp = cast<CXXMethodDecl>(CallOpSpec);
  10655. }
  10656. // Mark the call operator referenced (and add to pending instantiations
  10657. // if necessary).
  10658. // For both the conversion and static-invoker template specializations
  10659. // we construct their body's in this function, so no need to add them
  10660. // to the PendingInstantiations.
  10661. MarkFunctionReferenced(CurrentLocation, CallOp);
  10662. SynthesizedFunctionScope Scope(*this, Conv);
  10663. DiagnosticErrorTrap Trap(Diags);
  10664. // Retrieve the static invoker...
  10665. CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
  10666. // ... and get the corresponding specialization for a generic lambda.
  10667. if (Lambda->isGenericLambda()) {
  10668. assert(DeducedTemplateArgs &&
  10669. "Must have deduced template arguments from Conversion Operator");
  10670. FunctionTemplateDecl *InvokeTemplate =
  10671. Invoker->getDescribedFunctionTemplate();
  10672. void *InsertPos = nullptr;
  10673. FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
  10674. DeducedTemplateArgs->asArray(),
  10675. InsertPos);
  10676. assert(InvokeSpec &&
  10677. "Must have a corresponding static invoker specialization");
  10678. Invoker = cast<CXXMethodDecl>(InvokeSpec);
  10679. }
  10680. // Construct the body of the conversion function { return __invoke; }.
  10681. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  10682. VK_LValue, Conv->getLocation()).get();
  10683. assert(FunctionRef && "Can't refer to __invoke function?");
  10684. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  10685. Conv->setBody(new (Context) CompoundStmt(Context, Return,
  10686. Conv->getLocation(),
  10687. Conv->getLocation()));
  10688. Conv->markUsed(Context);
  10689. Conv->setReferenced();
  10690. // Fill in the __invoke function with a dummy implementation. IR generation
  10691. // will fill in the actual details.
  10692. Invoker->markUsed(Context);
  10693. Invoker->setReferenced();
  10694. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  10695. if (ASTMutationListener *L = getASTMutationListener()) {
  10696. L->CompletedImplicitDefinition(Conv);
  10697. L->CompletedImplicitDefinition(Invoker);
  10698. }
  10699. }
  10700. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  10701. SourceLocation CurrentLocation,
  10702. CXXConversionDecl *Conv)
  10703. {
  10704. assert(!Conv->getParent()->isGenericLambda());
  10705. Conv->markUsed(Context);
  10706. SynthesizedFunctionScope Scope(*this, Conv);
  10707. DiagnosticErrorTrap Trap(Diags);
  10708. // Copy-initialize the lambda object as needed to capture it.
  10709. Expr *This = ActOnCXXThis(CurrentLocation).get();
  10710. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  10711. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  10712. Conv->getLocation(),
  10713. Conv, DerefThis);
  10714. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  10715. // behavior. Note that only the general conversion function does this
  10716. // (since it's unusable otherwise); in the case where we inline the
  10717. // block literal, it has block literal lifetime semantics.
  10718. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  10719. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  10720. CK_CopyAndAutoreleaseBlockObject,
  10721. BuildBlock.get(), nullptr, VK_RValue);
  10722. if (BuildBlock.isInvalid()) {
  10723. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  10724. Conv->setInvalidDecl();
  10725. return;
  10726. }
  10727. // Create the return statement that returns the block from the conversion
  10728. // function.
  10729. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  10730. if (Return.isInvalid()) {
  10731. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  10732. Conv->setInvalidDecl();
  10733. return;
  10734. }
  10735. // Set the body of the conversion function.
  10736. Stmt *ReturnS = Return.get();
  10737. Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
  10738. Conv->getLocation(),
  10739. Conv->getLocation()));
  10740. // We're done; notify the mutation listener, if any.
  10741. if (ASTMutationListener *L = getASTMutationListener()) {
  10742. L->CompletedImplicitDefinition(Conv);
  10743. }
  10744. }
  10745. /// \brief Determine whether the given list arguments contains exactly one
  10746. /// "real" (non-default) argument.
  10747. static bool hasOneRealArgument(MultiExprArg Args) {
  10748. switch (Args.size()) {
  10749. case 0:
  10750. return false;
  10751. default:
  10752. if (!Args[1]->isDefaultArgument())
  10753. return false;
  10754. // fall through
  10755. case 1:
  10756. return !Args[0]->isDefaultArgument();
  10757. }
  10758. return false;
  10759. }
  10760. ExprResult
  10761. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  10762. NamedDecl *FoundDecl,
  10763. CXXConstructorDecl *Constructor,
  10764. MultiExprArg ExprArgs,
  10765. bool HadMultipleCandidates,
  10766. bool IsListInitialization,
  10767. bool IsStdInitListInitialization,
  10768. bool RequiresZeroInit,
  10769. unsigned ConstructKind,
  10770. SourceRange ParenRange) {
  10771. bool Elidable = false;
  10772. // C++0x [class.copy]p34:
  10773. // When certain criteria are met, an implementation is allowed to
  10774. // omit the copy/move construction of a class object, even if the
  10775. // copy/move constructor and/or destructor for the object have
  10776. // side effects. [...]
  10777. // - when a temporary class object that has not been bound to a
  10778. // reference (12.2) would be copied/moved to a class object
  10779. // with the same cv-unqualified type, the copy/move operation
  10780. // can be omitted by constructing the temporary object
  10781. // directly into the target of the omitted copy/move
  10782. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  10783. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  10784. Expr *SubExpr = ExprArgs[0];
  10785. Elidable = SubExpr->isTemporaryObject(
  10786. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  10787. }
  10788. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  10789. FoundDecl, Constructor,
  10790. Elidable, ExprArgs, HadMultipleCandidates,
  10791. IsListInitialization,
  10792. IsStdInitListInitialization, RequiresZeroInit,
  10793. ConstructKind, ParenRange);
  10794. }
  10795. ExprResult
  10796. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  10797. NamedDecl *FoundDecl,
  10798. CXXConstructorDecl *Constructor,
  10799. bool Elidable,
  10800. MultiExprArg ExprArgs,
  10801. bool HadMultipleCandidates,
  10802. bool IsListInitialization,
  10803. bool IsStdInitListInitialization,
  10804. bool RequiresZeroInit,
  10805. unsigned ConstructKind,
  10806. SourceRange ParenRange) {
  10807. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  10808. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  10809. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  10810. return ExprError();
  10811. }
  10812. return BuildCXXConstructExpr(
  10813. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  10814. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  10815. RequiresZeroInit, ConstructKind, ParenRange);
  10816. }
  10817. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  10818. /// including handling of its default argument expressions.
  10819. ExprResult
  10820. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  10821. CXXConstructorDecl *Constructor,
  10822. bool Elidable,
  10823. MultiExprArg ExprArgs,
  10824. bool HadMultipleCandidates,
  10825. bool IsListInitialization,
  10826. bool IsStdInitListInitialization,
  10827. bool RequiresZeroInit,
  10828. unsigned ConstructKind,
  10829. SourceRange ParenRange) {
  10830. assert(declaresSameEntity(
  10831. Constructor->getParent(),
  10832. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  10833. "given constructor for wrong type");
  10834. MarkFunctionReferenced(ConstructLoc, Constructor);
  10835. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  10836. return ExprError();
  10837. return CXXConstructExpr::Create(
  10838. Context, DeclInitType, ConstructLoc, Constructor, Elidable,
  10839. ExprArgs, HadMultipleCandidates, IsListInitialization,
  10840. IsStdInitListInitialization, RequiresZeroInit,
  10841. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  10842. ParenRange);
  10843. }
  10844. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  10845. assert(Field->hasInClassInitializer());
  10846. // If we already have the in-class initializer nothing needs to be done.
  10847. if (Field->getInClassInitializer())
  10848. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  10849. // If we might have already tried and failed to instantiate, don't try again.
  10850. if (Field->isInvalidDecl())
  10851. return ExprError();
  10852. // Maybe we haven't instantiated the in-class initializer. Go check the
  10853. // pattern FieldDecl to see if it has one.
  10854. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  10855. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  10856. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  10857. DeclContext::lookup_result Lookup =
  10858. ClassPattern->lookup(Field->getDeclName());
  10859. // Lookup can return at most two results: the pattern for the field, or the
  10860. // injected class name of the parent record. No other member can have the
  10861. // same name as the field.
  10862. // In modules mode, lookup can return multiple results (coming from
  10863. // different modules).
  10864. assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
  10865. "more than two lookup results for field name");
  10866. FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
  10867. if (!Pattern) {
  10868. assert(isa<CXXRecordDecl>(Lookup[0]) &&
  10869. "cannot have other non-field member with same name");
  10870. for (auto L : Lookup)
  10871. if (isa<FieldDecl>(L)) {
  10872. Pattern = cast<FieldDecl>(L);
  10873. break;
  10874. }
  10875. assert(Pattern && "We must have set the Pattern!");
  10876. }
  10877. if (InstantiateInClassInitializer(Loc, Field, Pattern,
  10878. getTemplateInstantiationArgs(Field))) {
  10879. // Don't diagnose this again.
  10880. Field->setInvalidDecl();
  10881. return ExprError();
  10882. }
  10883. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  10884. }
  10885. // DR1351:
  10886. // If the brace-or-equal-initializer of a non-static data member
  10887. // invokes a defaulted default constructor of its class or of an
  10888. // enclosing class in a potentially evaluated subexpression, the
  10889. // program is ill-formed.
  10890. //
  10891. // This resolution is unworkable: the exception specification of the
  10892. // default constructor can be needed in an unevaluated context, in
  10893. // particular, in the operand of a noexcept-expression, and we can be
  10894. // unable to compute an exception specification for an enclosed class.
  10895. //
  10896. // Any attempt to resolve the exception specification of a defaulted default
  10897. // constructor before the initializer is lexically complete will ultimately
  10898. // come here at which point we can diagnose it.
  10899. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  10900. Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
  10901. << OutermostClass << Field;
  10902. Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
  10903. // Recover by marking the field invalid, unless we're in a SFINAE context.
  10904. if (!isSFINAEContext())
  10905. Field->setInvalidDecl();
  10906. return ExprError();
  10907. }
  10908. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  10909. if (VD->isInvalidDecl()) return;
  10910. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  10911. if (ClassDecl->isInvalidDecl()) return;
  10912. if (ClassDecl->hasIrrelevantDestructor()) return;
  10913. if (ClassDecl->isDependentContext()) return;
  10914. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  10915. MarkFunctionReferenced(VD->getLocation(), Destructor);
  10916. CheckDestructorAccess(VD->getLocation(), Destructor,
  10917. PDiag(diag::err_access_dtor_var)
  10918. << VD->getDeclName()
  10919. << VD->getType());
  10920. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  10921. if (Destructor->isTrivial()) return;
  10922. if (!VD->hasGlobalStorage()) return;
  10923. // Emit warning for non-trivial dtor in global scope (a real global,
  10924. // class-static, function-static).
  10925. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  10926. // TODO: this should be re-enabled for static locals by !CXAAtExit
  10927. if (!VD->isStaticLocal())
  10928. Diag(VD->getLocation(), diag::warn_global_destructor);
  10929. }
  10930. /// \brief Given a constructor and the set of arguments provided for the
  10931. /// constructor, convert the arguments and add any required default arguments
  10932. /// to form a proper call to this constructor.
  10933. ///
  10934. /// \returns true if an error occurred, false otherwise.
  10935. bool
  10936. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  10937. MultiExprArg ArgsPtr,
  10938. SourceLocation Loc,
  10939. SmallVectorImpl<Expr*> &ConvertedArgs,
  10940. bool AllowExplicit,
  10941. bool IsListInitialization) {
  10942. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  10943. unsigned NumArgs = ArgsPtr.size();
  10944. Expr **Args = ArgsPtr.data();
  10945. const FunctionProtoType *Proto
  10946. = Constructor->getType()->getAs<FunctionProtoType>();
  10947. assert(Proto && "Constructor without a prototype?");
  10948. unsigned NumParams = Proto->getNumParams();
  10949. // If too few arguments are available, we'll fill in the rest with defaults.
  10950. if (NumArgs < NumParams)
  10951. ConvertedArgs.reserve(NumParams);
  10952. else
  10953. ConvertedArgs.reserve(NumArgs);
  10954. VariadicCallType CallType =
  10955. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  10956. SmallVector<Expr *, 8> AllArgs;
  10957. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  10958. Proto, 0,
  10959. llvm::makeArrayRef(Args, NumArgs),
  10960. AllArgs,
  10961. CallType, AllowExplicit,
  10962. IsListInitialization);
  10963. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  10964. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  10965. CheckConstructorCall(Constructor,
  10966. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  10967. Proto, Loc);
  10968. return Invalid;
  10969. }
  10970. static inline bool
  10971. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  10972. const FunctionDecl *FnDecl) {
  10973. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  10974. if (isa<NamespaceDecl>(DC)) {
  10975. return SemaRef.Diag(FnDecl->getLocation(),
  10976. diag::err_operator_new_delete_declared_in_namespace)
  10977. << FnDecl->getDeclName();
  10978. }
  10979. if (isa<TranslationUnitDecl>(DC) &&
  10980. FnDecl->getStorageClass() == SC_Static) {
  10981. return SemaRef.Diag(FnDecl->getLocation(),
  10982. diag::err_operator_new_delete_declared_static)
  10983. << FnDecl->getDeclName();
  10984. }
  10985. return false;
  10986. }
  10987. static inline bool
  10988. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  10989. CanQualType ExpectedResultType,
  10990. CanQualType ExpectedFirstParamType,
  10991. unsigned DependentParamTypeDiag,
  10992. unsigned InvalidParamTypeDiag) {
  10993. QualType ResultType =
  10994. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  10995. // Check that the result type is not dependent.
  10996. if (ResultType->isDependentType())
  10997. return SemaRef.Diag(FnDecl->getLocation(),
  10998. diag::err_operator_new_delete_dependent_result_type)
  10999. << FnDecl->getDeclName() << ExpectedResultType;
  11000. // Check that the result type is what we expect.
  11001. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  11002. return SemaRef.Diag(FnDecl->getLocation(),
  11003. diag::err_operator_new_delete_invalid_result_type)
  11004. << FnDecl->getDeclName() << ExpectedResultType;
  11005. // A function template must have at least 2 parameters.
  11006. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  11007. return SemaRef.Diag(FnDecl->getLocation(),
  11008. diag::err_operator_new_delete_template_too_few_parameters)
  11009. << FnDecl->getDeclName();
  11010. // The function decl must have at least 1 parameter.
  11011. if (FnDecl->getNumParams() == 0)
  11012. return SemaRef.Diag(FnDecl->getLocation(),
  11013. diag::err_operator_new_delete_too_few_parameters)
  11014. << FnDecl->getDeclName();
  11015. // Check the first parameter type is not dependent.
  11016. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  11017. if (FirstParamType->isDependentType())
  11018. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  11019. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11020. // Check that the first parameter type is what we expect.
  11021. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  11022. ExpectedFirstParamType)
  11023. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  11024. << FnDecl->getDeclName() << ExpectedFirstParamType;
  11025. return false;
  11026. }
  11027. static bool
  11028. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  11029. // C++ [basic.stc.dynamic.allocation]p1:
  11030. // A program is ill-formed if an allocation function is declared in a
  11031. // namespace scope other than global scope or declared static in global
  11032. // scope.
  11033. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11034. return true;
  11035. CanQualType SizeTy =
  11036. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  11037. // C++ [basic.stc.dynamic.allocation]p1:
  11038. // The return type shall be void*. The first parameter shall have type
  11039. // std::size_t.
  11040. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  11041. SizeTy,
  11042. diag::err_operator_new_dependent_param_type,
  11043. diag::err_operator_new_param_type))
  11044. return true;
  11045. // C++ [basic.stc.dynamic.allocation]p1:
  11046. // The first parameter shall not have an associated default argument.
  11047. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  11048. return SemaRef.Diag(FnDecl->getLocation(),
  11049. diag::err_operator_new_default_arg)
  11050. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  11051. return false;
  11052. }
  11053. static bool
  11054. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  11055. // C++ [basic.stc.dynamic.deallocation]p1:
  11056. // A program is ill-formed if deallocation functions are declared in a
  11057. // namespace scope other than global scope or declared static in global
  11058. // scope.
  11059. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  11060. return true;
  11061. // C++ [basic.stc.dynamic.deallocation]p2:
  11062. // Each deallocation function shall return void and its first parameter
  11063. // shall be void*.
  11064. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
  11065. SemaRef.Context.VoidPtrTy,
  11066. diag::err_operator_delete_dependent_param_type,
  11067. diag::err_operator_delete_param_type))
  11068. return true;
  11069. return false;
  11070. }
  11071. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  11072. /// of this overloaded operator is well-formed. If so, returns false;
  11073. /// otherwise, emits appropriate diagnostics and returns true.
  11074. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  11075. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  11076. "Expected an overloaded operator declaration");
  11077. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  11078. // C++ [over.oper]p5:
  11079. // The allocation and deallocation functions, operator new,
  11080. // operator new[], operator delete and operator delete[], are
  11081. // described completely in 3.7.3. The attributes and restrictions
  11082. // found in the rest of this subclause do not apply to them unless
  11083. // explicitly stated in 3.7.3.
  11084. if (Op == OO_Delete || Op == OO_Array_Delete)
  11085. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  11086. if (Op == OO_New || Op == OO_Array_New)
  11087. return CheckOperatorNewDeclaration(*this, FnDecl);
  11088. // C++ [over.oper]p6:
  11089. // An operator function shall either be a non-static member
  11090. // function or be a non-member function and have at least one
  11091. // parameter whose type is a class, a reference to a class, an
  11092. // enumeration, or a reference to an enumeration.
  11093. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  11094. if (MethodDecl->isStatic())
  11095. return Diag(FnDecl->getLocation(),
  11096. diag::err_operator_overload_static) << FnDecl->getDeclName();
  11097. } else {
  11098. bool ClassOrEnumParam = false;
  11099. for (auto Param : FnDecl->parameters()) {
  11100. QualType ParamType = Param->getType().getNonReferenceType();
  11101. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  11102. ParamType->isEnumeralType()) {
  11103. ClassOrEnumParam = true;
  11104. break;
  11105. }
  11106. }
  11107. if (!ClassOrEnumParam)
  11108. return Diag(FnDecl->getLocation(),
  11109. diag::err_operator_overload_needs_class_or_enum)
  11110. << FnDecl->getDeclName();
  11111. }
  11112. // C++ [over.oper]p8:
  11113. // An operator function cannot have default arguments (8.3.6),
  11114. // except where explicitly stated below.
  11115. //
  11116. // Only the function-call operator allows default arguments
  11117. // (C++ [over.call]p1).
  11118. if (Op != OO_Call) {
  11119. for (auto Param : FnDecl->parameters()) {
  11120. if (Param->hasDefaultArg())
  11121. return Diag(Param->getLocation(),
  11122. diag::err_operator_overload_default_arg)
  11123. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  11124. }
  11125. }
  11126. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  11127. { false, false, false }
  11128. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  11129. , { Unary, Binary, MemberOnly }
  11130. #include "clang/Basic/OperatorKinds.def"
  11131. };
  11132. bool CanBeUnaryOperator = OperatorUses[Op][0];
  11133. bool CanBeBinaryOperator = OperatorUses[Op][1];
  11134. bool MustBeMemberOperator = OperatorUses[Op][2];
  11135. // C++ [over.oper]p8:
  11136. // [...] Operator functions cannot have more or fewer parameters
  11137. // than the number required for the corresponding operator, as
  11138. // described in the rest of this subclause.
  11139. unsigned NumParams = FnDecl->getNumParams()
  11140. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  11141. if (Op != OO_Call &&
  11142. ((NumParams == 1 && !CanBeUnaryOperator) ||
  11143. (NumParams == 2 && !CanBeBinaryOperator) ||
  11144. (NumParams < 1) || (NumParams > 2))) {
  11145. // We have the wrong number of parameters.
  11146. unsigned ErrorKind;
  11147. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  11148. ErrorKind = 2; // 2 -> unary or binary.
  11149. } else if (CanBeUnaryOperator) {
  11150. ErrorKind = 0; // 0 -> unary
  11151. } else {
  11152. assert(CanBeBinaryOperator &&
  11153. "All non-call overloaded operators are unary or binary!");
  11154. ErrorKind = 1; // 1 -> binary
  11155. }
  11156. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  11157. << FnDecl->getDeclName() << NumParams << ErrorKind;
  11158. }
  11159. // Overloaded operators other than operator() cannot be variadic.
  11160. if (Op != OO_Call &&
  11161. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  11162. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  11163. << FnDecl->getDeclName();
  11164. }
  11165. // Some operators must be non-static member functions.
  11166. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  11167. return Diag(FnDecl->getLocation(),
  11168. diag::err_operator_overload_must_be_member)
  11169. << FnDecl->getDeclName();
  11170. }
  11171. // C++ [over.inc]p1:
  11172. // The user-defined function called operator++ implements the
  11173. // prefix and postfix ++ operator. If this function is a member
  11174. // function with no parameters, or a non-member function with one
  11175. // parameter of class or enumeration type, it defines the prefix
  11176. // increment operator ++ for objects of that type. If the function
  11177. // is a member function with one parameter (which shall be of type
  11178. // int) or a non-member function with two parameters (the second
  11179. // of which shall be of type int), it defines the postfix
  11180. // increment operator ++ for objects of that type.
  11181. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  11182. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  11183. QualType ParamType = LastParam->getType();
  11184. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  11185. !ParamType->isDependentType())
  11186. return Diag(LastParam->getLocation(),
  11187. diag::err_operator_overload_post_incdec_must_be_int)
  11188. << LastParam->getType() << (Op == OO_MinusMinus);
  11189. }
  11190. return false;
  11191. }
  11192. static bool
  11193. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  11194. FunctionTemplateDecl *TpDecl) {
  11195. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  11196. // Must have one or two template parameters.
  11197. if (TemplateParams->size() == 1) {
  11198. NonTypeTemplateParmDecl *PmDecl =
  11199. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  11200. // The template parameter must be a char parameter pack.
  11201. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  11202. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  11203. return false;
  11204. } else if (TemplateParams->size() == 2) {
  11205. TemplateTypeParmDecl *PmType =
  11206. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  11207. NonTypeTemplateParmDecl *PmArgs =
  11208. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  11209. // The second template parameter must be a parameter pack with the
  11210. // first template parameter as its type.
  11211. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  11212. PmArgs->isTemplateParameterPack()) {
  11213. const TemplateTypeParmType *TArgs =
  11214. PmArgs->getType()->getAs<TemplateTypeParmType>();
  11215. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  11216. TArgs->getIndex() == PmType->getIndex()) {
  11217. if (SemaRef.ActiveTemplateInstantiations.empty())
  11218. SemaRef.Diag(TpDecl->getLocation(),
  11219. diag::ext_string_literal_operator_template);
  11220. return false;
  11221. }
  11222. }
  11223. }
  11224. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  11225. diag::err_literal_operator_template)
  11226. << TpDecl->getTemplateParameters()->getSourceRange();
  11227. return true;
  11228. }
  11229. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  11230. /// of this literal operator function is well-formed. If so, returns
  11231. /// false; otherwise, emits appropriate diagnostics and returns true.
  11232. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  11233. if (isa<CXXMethodDecl>(FnDecl)) {
  11234. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  11235. << FnDecl->getDeclName();
  11236. return true;
  11237. }
  11238. if (FnDecl->isExternC()) {
  11239. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  11240. if (const LinkageSpecDecl *LSD =
  11241. FnDecl->getDeclContext()->getExternCContext())
  11242. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  11243. return true;
  11244. }
  11245. // This might be the definition of a literal operator template.
  11246. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  11247. // This might be a specialization of a literal operator template.
  11248. if (!TpDecl)
  11249. TpDecl = FnDecl->getPrimaryTemplate();
  11250. // template <char...> type operator "" name() and
  11251. // template <class T, T...> type operator "" name() are the only valid
  11252. // template signatures, and the only valid signatures with no parameters.
  11253. if (TpDecl) {
  11254. if (FnDecl->param_size() != 0) {
  11255. Diag(FnDecl->getLocation(),
  11256. diag::err_literal_operator_template_with_params);
  11257. return true;
  11258. }
  11259. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  11260. return true;
  11261. } else if (FnDecl->param_size() == 1) {
  11262. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  11263. QualType ParamType = Param->getType().getUnqualifiedType();
  11264. // Only unsigned long long int, long double, any character type, and const
  11265. // char * are allowed as the only parameters.
  11266. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  11267. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  11268. Context.hasSameType(ParamType, Context.CharTy) ||
  11269. Context.hasSameType(ParamType, Context.WideCharTy) ||
  11270. Context.hasSameType(ParamType, Context.Char16Ty) ||
  11271. Context.hasSameType(ParamType, Context.Char32Ty)) {
  11272. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  11273. QualType InnerType = Ptr->getPointeeType();
  11274. // Pointer parameter must be a const char *.
  11275. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  11276. Context.CharTy) &&
  11277. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  11278. Diag(Param->getSourceRange().getBegin(),
  11279. diag::err_literal_operator_param)
  11280. << ParamType << "'const char *'" << Param->getSourceRange();
  11281. return true;
  11282. }
  11283. } else if (ParamType->isRealFloatingType()) {
  11284. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11285. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  11286. return true;
  11287. } else if (ParamType->isIntegerType()) {
  11288. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  11289. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  11290. return true;
  11291. } else {
  11292. Diag(Param->getSourceRange().getBegin(),
  11293. diag::err_literal_operator_invalid_param)
  11294. << ParamType << Param->getSourceRange();
  11295. return true;
  11296. }
  11297. } else if (FnDecl->param_size() == 2) {
  11298. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  11299. // First, verify that the first parameter is correct.
  11300. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  11301. // Two parameter function must have a pointer to const as a
  11302. // first parameter; let's strip those qualifiers.
  11303. const PointerType *PT = FirstParamType->getAs<PointerType>();
  11304. if (!PT) {
  11305. Diag((*Param)->getSourceRange().getBegin(),
  11306. diag::err_literal_operator_param)
  11307. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11308. return true;
  11309. }
  11310. QualType PointeeType = PT->getPointeeType();
  11311. // First parameter must be const
  11312. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  11313. Diag((*Param)->getSourceRange().getBegin(),
  11314. diag::err_literal_operator_param)
  11315. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11316. return true;
  11317. }
  11318. QualType InnerType = PointeeType.getUnqualifiedType();
  11319. // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
  11320. // are allowed as the first parameter to a two-parameter function
  11321. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  11322. Context.hasSameType(InnerType, Context.WideCharTy) ||
  11323. Context.hasSameType(InnerType, Context.Char16Ty) ||
  11324. Context.hasSameType(InnerType, Context.Char32Ty))) {
  11325. Diag((*Param)->getSourceRange().getBegin(),
  11326. diag::err_literal_operator_param)
  11327. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  11328. return true;
  11329. }
  11330. // Move on to the second and final parameter.
  11331. ++Param;
  11332. // The second parameter must be a std::size_t.
  11333. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  11334. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  11335. Diag((*Param)->getSourceRange().getBegin(),
  11336. diag::err_literal_operator_param)
  11337. << SecondParamType << Context.getSizeType()
  11338. << (*Param)->getSourceRange();
  11339. return true;
  11340. }
  11341. } else {
  11342. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  11343. return true;
  11344. }
  11345. // Parameters are good.
  11346. // A parameter-declaration-clause containing a default argument is not
  11347. // equivalent to any of the permitted forms.
  11348. for (auto Param : FnDecl->parameters()) {
  11349. if (Param->hasDefaultArg()) {
  11350. Diag(Param->getDefaultArgRange().getBegin(),
  11351. diag::err_literal_operator_default_argument)
  11352. << Param->getDefaultArgRange();
  11353. break;
  11354. }
  11355. }
  11356. StringRef LiteralName
  11357. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  11358. if (LiteralName[0] != '_') {
  11359. // C++11 [usrlit.suffix]p1:
  11360. // Literal suffix identifiers that do not start with an underscore
  11361. // are reserved for future standardization.
  11362. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  11363. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  11364. }
  11365. return false;
  11366. }
  11367. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  11368. /// linkage specification, including the language and (if present)
  11369. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  11370. /// language string literal. LBraceLoc, if valid, provides the location of
  11371. /// the '{' brace. Otherwise, this linkage specification does not
  11372. /// have any braces.
  11373. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  11374. Expr *LangStr,
  11375. SourceLocation LBraceLoc) {
  11376. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  11377. if (!Lit->isAscii()) {
  11378. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  11379. << LangStr->getSourceRange();
  11380. return nullptr;
  11381. }
  11382. StringRef Lang = Lit->getString();
  11383. LinkageSpecDecl::LanguageIDs Language;
  11384. if (Lang == "C")
  11385. Language = LinkageSpecDecl::lang_c;
  11386. else if (Lang == "C++")
  11387. Language = LinkageSpecDecl::lang_cxx;
  11388. else {
  11389. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  11390. << LangStr->getSourceRange();
  11391. return nullptr;
  11392. }
  11393. // FIXME: Add all the various semantics of linkage specifications
  11394. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  11395. LangStr->getExprLoc(), Language,
  11396. LBraceLoc.isValid());
  11397. CurContext->addDecl(D);
  11398. PushDeclContext(S, D);
  11399. return D;
  11400. }
  11401. /// ActOnFinishLinkageSpecification - Complete the definition of
  11402. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  11403. /// valid, it's the position of the closing '}' brace in a linkage
  11404. /// specification that uses braces.
  11405. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  11406. Decl *LinkageSpec,
  11407. SourceLocation RBraceLoc) {
  11408. if (RBraceLoc.isValid()) {
  11409. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  11410. LSDecl->setRBraceLoc(RBraceLoc);
  11411. }
  11412. PopDeclContext();
  11413. return LinkageSpec;
  11414. }
  11415. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  11416. AttributeList *AttrList,
  11417. SourceLocation SemiLoc) {
  11418. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  11419. // Attribute declarations appertain to empty declaration so we handle
  11420. // them here.
  11421. if (AttrList)
  11422. ProcessDeclAttributeList(S, ED, AttrList);
  11423. CurContext->addDecl(ED);
  11424. return ED;
  11425. }
  11426. /// \brief Perform semantic analysis for the variable declaration that
  11427. /// occurs within a C++ catch clause, returning the newly-created
  11428. /// variable.
  11429. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  11430. TypeSourceInfo *TInfo,
  11431. SourceLocation StartLoc,
  11432. SourceLocation Loc,
  11433. IdentifierInfo *Name) {
  11434. bool Invalid = false;
  11435. QualType ExDeclType = TInfo->getType();
  11436. // Arrays and functions decay.
  11437. if (ExDeclType->isArrayType())
  11438. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  11439. else if (ExDeclType->isFunctionType())
  11440. ExDeclType = Context.getPointerType(ExDeclType);
  11441. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  11442. // The exception-declaration shall not denote a pointer or reference to an
  11443. // incomplete type, other than [cv] void*.
  11444. // N2844 forbids rvalue references.
  11445. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  11446. Diag(Loc, diag::err_catch_rvalue_ref);
  11447. Invalid = true;
  11448. }
  11449. if (ExDeclType->isVariablyModifiedType()) {
  11450. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  11451. Invalid = true;
  11452. }
  11453. QualType BaseType = ExDeclType;
  11454. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  11455. unsigned DK = diag::err_catch_incomplete;
  11456. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  11457. BaseType = Ptr->getPointeeType();
  11458. Mode = 1;
  11459. DK = diag::err_catch_incomplete_ptr;
  11460. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  11461. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  11462. BaseType = Ref->getPointeeType();
  11463. Mode = 2;
  11464. DK = diag::err_catch_incomplete_ref;
  11465. }
  11466. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  11467. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  11468. Invalid = true;
  11469. if (!Invalid && !ExDeclType->isDependentType() &&
  11470. RequireNonAbstractType(Loc, ExDeclType,
  11471. diag::err_abstract_type_in_decl,
  11472. AbstractVariableType))
  11473. Invalid = true;
  11474. // Only the non-fragile NeXT runtime currently supports C++ catches
  11475. // of ObjC types, and no runtime supports catching ObjC types by value.
  11476. if (!Invalid && getLangOpts().ObjC1) {
  11477. QualType T = ExDeclType;
  11478. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  11479. T = RT->getPointeeType();
  11480. if (T->isObjCObjectType()) {
  11481. Diag(Loc, diag::err_objc_object_catch);
  11482. Invalid = true;
  11483. } else if (T->isObjCObjectPointerType()) {
  11484. // FIXME: should this be a test for macosx-fragile specifically?
  11485. if (getLangOpts().ObjCRuntime.isFragile())
  11486. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  11487. }
  11488. }
  11489. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  11490. ExDeclType, TInfo, SC_None);
  11491. ExDecl->setExceptionVariable(true);
  11492. // In ARC, infer 'retaining' for variables of retainable type.
  11493. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  11494. Invalid = true;
  11495. if (!Invalid && !ExDeclType->isDependentType()) {
  11496. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  11497. // Insulate this from anything else we might currently be parsing.
  11498. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  11499. // C++ [except.handle]p16:
  11500. // The object declared in an exception-declaration or, if the
  11501. // exception-declaration does not specify a name, a temporary (12.2) is
  11502. // copy-initialized (8.5) from the exception object. [...]
  11503. // The object is destroyed when the handler exits, after the destruction
  11504. // of any automatic objects initialized within the handler.
  11505. //
  11506. // We just pretend to initialize the object with itself, then make sure
  11507. // it can be destroyed later.
  11508. QualType initType = Context.getExceptionObjectType(ExDeclType);
  11509. InitializedEntity entity =
  11510. InitializedEntity::InitializeVariable(ExDecl);
  11511. InitializationKind initKind =
  11512. InitializationKind::CreateCopy(Loc, SourceLocation());
  11513. Expr *opaqueValue =
  11514. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  11515. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  11516. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  11517. if (result.isInvalid())
  11518. Invalid = true;
  11519. else {
  11520. // If the constructor used was non-trivial, set this as the
  11521. // "initializer".
  11522. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  11523. if (!construct->getConstructor()->isTrivial()) {
  11524. Expr *init = MaybeCreateExprWithCleanups(construct);
  11525. ExDecl->setInit(init);
  11526. }
  11527. // And make sure it's destructable.
  11528. FinalizeVarWithDestructor(ExDecl, recordType);
  11529. }
  11530. }
  11531. }
  11532. if (Invalid)
  11533. ExDecl->setInvalidDecl();
  11534. return ExDecl;
  11535. }
  11536. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  11537. /// handler.
  11538. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  11539. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11540. bool Invalid = D.isInvalidType();
  11541. // Check for unexpanded parameter packs.
  11542. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11543. UPPC_ExceptionType)) {
  11544. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  11545. D.getIdentifierLoc());
  11546. Invalid = true;
  11547. }
  11548. IdentifierInfo *II = D.getIdentifier();
  11549. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  11550. LookupOrdinaryName,
  11551. ForRedeclaration)) {
  11552. // The scope should be freshly made just for us. There is just no way
  11553. // it contains any previous declaration, except for function parameters in
  11554. // a function-try-block's catch statement.
  11555. assert(!S->isDeclScope(PrevDecl));
  11556. if (isDeclInScope(PrevDecl, CurContext, S)) {
  11557. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  11558. << D.getIdentifier();
  11559. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11560. Invalid = true;
  11561. } else if (PrevDecl->isTemplateParameter())
  11562. // Maybe we will complain about the shadowed template parameter.
  11563. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11564. }
  11565. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  11566. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  11567. << D.getCXXScopeSpec().getRange();
  11568. Invalid = true;
  11569. }
  11570. VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
  11571. D.getLocStart(),
  11572. D.getIdentifierLoc(),
  11573. D.getIdentifier());
  11574. if (Invalid)
  11575. ExDecl->setInvalidDecl();
  11576. // Add the exception declaration into this scope.
  11577. if (II)
  11578. PushOnScopeChains(ExDecl, S);
  11579. else
  11580. CurContext->addDecl(ExDecl);
  11581. ProcessDeclAttributes(S, ExDecl, D);
  11582. return ExDecl;
  11583. }
  11584. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  11585. Expr *AssertExpr,
  11586. Expr *AssertMessageExpr,
  11587. SourceLocation RParenLoc) {
  11588. StringLiteral *AssertMessage =
  11589. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  11590. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  11591. return nullptr;
  11592. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  11593. AssertMessage, RParenLoc, false);
  11594. }
  11595. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  11596. Expr *AssertExpr,
  11597. StringLiteral *AssertMessage,
  11598. SourceLocation RParenLoc,
  11599. bool Failed) {
  11600. assert(AssertExpr != nullptr && "Expected non-null condition");
  11601. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  11602. !Failed) {
  11603. // In a static_assert-declaration, the constant-expression shall be a
  11604. // constant expression that can be contextually converted to bool.
  11605. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  11606. if (Converted.isInvalid())
  11607. Failed = true;
  11608. llvm::APSInt Cond;
  11609. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  11610. diag::err_static_assert_expression_is_not_constant,
  11611. /*AllowFold=*/false).isInvalid())
  11612. Failed = true;
  11613. if (!Failed && !Cond) {
  11614. SmallString<256> MsgBuffer;
  11615. llvm::raw_svector_ostream Msg(MsgBuffer);
  11616. if (AssertMessage)
  11617. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  11618. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  11619. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  11620. Failed = true;
  11621. }
  11622. }
  11623. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  11624. AssertExpr, AssertMessage, RParenLoc,
  11625. Failed);
  11626. CurContext->addDecl(Decl);
  11627. return Decl;
  11628. }
  11629. /// \brief Perform semantic analysis of the given friend type declaration.
  11630. ///
  11631. /// \returns A friend declaration that.
  11632. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  11633. SourceLocation FriendLoc,
  11634. TypeSourceInfo *TSInfo) {
  11635. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  11636. QualType T = TSInfo->getType();
  11637. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  11638. // C++03 [class.friend]p2:
  11639. // An elaborated-type-specifier shall be used in a friend declaration
  11640. // for a class.*
  11641. //
  11642. // * The class-key of the elaborated-type-specifier is required.
  11643. if (!ActiveTemplateInstantiations.empty()) {
  11644. // Do not complain about the form of friend template types during
  11645. // template instantiation; we will already have complained when the
  11646. // template was declared.
  11647. } else {
  11648. if (!T->isElaboratedTypeSpecifier()) {
  11649. // If we evaluated the type to a record type, suggest putting
  11650. // a tag in front.
  11651. if (const RecordType *RT = T->getAs<RecordType>()) {
  11652. RecordDecl *RD = RT->getDecl();
  11653. SmallString<16> InsertionText(" ");
  11654. InsertionText += RD->getKindName();
  11655. Diag(TypeRange.getBegin(),
  11656. getLangOpts().CPlusPlus11 ?
  11657. diag::warn_cxx98_compat_unelaborated_friend_type :
  11658. diag::ext_unelaborated_friend_type)
  11659. << (unsigned) RD->getTagKind()
  11660. << T
  11661. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  11662. InsertionText);
  11663. } else {
  11664. Diag(FriendLoc,
  11665. getLangOpts().CPlusPlus11 ?
  11666. diag::warn_cxx98_compat_nonclass_type_friend :
  11667. diag::ext_nonclass_type_friend)
  11668. << T
  11669. << TypeRange;
  11670. }
  11671. } else if (T->getAs<EnumType>()) {
  11672. Diag(FriendLoc,
  11673. getLangOpts().CPlusPlus11 ?
  11674. diag::warn_cxx98_compat_enum_friend :
  11675. diag::ext_enum_friend)
  11676. << T
  11677. << TypeRange;
  11678. }
  11679. // C++11 [class.friend]p3:
  11680. // A friend declaration that does not declare a function shall have one
  11681. // of the following forms:
  11682. // friend elaborated-type-specifier ;
  11683. // friend simple-type-specifier ;
  11684. // friend typename-specifier ;
  11685. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  11686. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  11687. }
  11688. // If the type specifier in a friend declaration designates a (possibly
  11689. // cv-qualified) class type, that class is declared as a friend; otherwise,
  11690. // the friend declaration is ignored.
  11691. return FriendDecl::Create(Context, CurContext,
  11692. TSInfo->getTypeLoc().getLocStart(), TSInfo,
  11693. FriendLoc);
  11694. }
  11695. /// Handle a friend tag declaration where the scope specifier was
  11696. /// templated.
  11697. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  11698. unsigned TagSpec, SourceLocation TagLoc,
  11699. CXXScopeSpec &SS,
  11700. IdentifierInfo *Name,
  11701. SourceLocation NameLoc,
  11702. AttributeList *Attr,
  11703. MultiTemplateParamsArg TempParamLists) {
  11704. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  11705. bool IsMemberSpecialization = false;
  11706. bool Invalid = false;
  11707. if (TemplateParameterList *TemplateParams =
  11708. MatchTemplateParametersToScopeSpecifier(
  11709. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  11710. IsMemberSpecialization, Invalid)) {
  11711. if (TemplateParams->size() > 0) {
  11712. // This is a declaration of a class template.
  11713. if (Invalid)
  11714. return nullptr;
  11715. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  11716. NameLoc, Attr, TemplateParams, AS_public,
  11717. /*ModulePrivateLoc=*/SourceLocation(),
  11718. FriendLoc, TempParamLists.size() - 1,
  11719. TempParamLists.data()).get();
  11720. } else {
  11721. // The "template<>" header is extraneous.
  11722. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  11723. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  11724. IsMemberSpecialization = true;
  11725. }
  11726. }
  11727. if (Invalid) return nullptr;
  11728. bool isAllExplicitSpecializations = true;
  11729. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  11730. if (TempParamLists[I]->size()) {
  11731. isAllExplicitSpecializations = false;
  11732. break;
  11733. }
  11734. }
  11735. // FIXME: don't ignore attributes.
  11736. // If it's explicit specializations all the way down, just forget
  11737. // about the template header and build an appropriate non-templated
  11738. // friend. TODO: for source fidelity, remember the headers.
  11739. if (isAllExplicitSpecializations) {
  11740. if (SS.isEmpty()) {
  11741. bool Owned = false;
  11742. bool IsDependent = false;
  11743. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  11744. Attr, AS_public,
  11745. /*ModulePrivateLoc=*/SourceLocation(),
  11746. MultiTemplateParamsArg(), Owned, IsDependent,
  11747. /*ScopedEnumKWLoc=*/SourceLocation(),
  11748. /*ScopedEnumUsesClassTag=*/false,
  11749. /*UnderlyingType=*/TypeResult(),
  11750. /*IsTypeSpecifier=*/false);
  11751. }
  11752. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  11753. ElaboratedTypeKeyword Keyword
  11754. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  11755. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  11756. *Name, NameLoc);
  11757. if (T.isNull())
  11758. return nullptr;
  11759. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  11760. if (isa<DependentNameType>(T)) {
  11761. DependentNameTypeLoc TL =
  11762. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  11763. TL.setElaboratedKeywordLoc(TagLoc);
  11764. TL.setQualifierLoc(QualifierLoc);
  11765. TL.setNameLoc(NameLoc);
  11766. } else {
  11767. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  11768. TL.setElaboratedKeywordLoc(TagLoc);
  11769. TL.setQualifierLoc(QualifierLoc);
  11770. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  11771. }
  11772. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  11773. TSI, FriendLoc, TempParamLists);
  11774. Friend->setAccess(AS_public);
  11775. CurContext->addDecl(Friend);
  11776. return Friend;
  11777. }
  11778. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  11779. // Handle the case of a templated-scope friend class. e.g.
  11780. // template <class T> class A<T>::B;
  11781. // FIXME: we don't support these right now.
  11782. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  11783. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  11784. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  11785. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  11786. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  11787. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  11788. TL.setElaboratedKeywordLoc(TagLoc);
  11789. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  11790. TL.setNameLoc(NameLoc);
  11791. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  11792. TSI, FriendLoc, TempParamLists);
  11793. Friend->setAccess(AS_public);
  11794. Friend->setUnsupportedFriend(true);
  11795. CurContext->addDecl(Friend);
  11796. return Friend;
  11797. }
  11798. /// Handle a friend type declaration. This works in tandem with
  11799. /// ActOnTag.
  11800. ///
  11801. /// Notes on friend class templates:
  11802. ///
  11803. /// We generally treat friend class declarations as if they were
  11804. /// declaring a class. So, for example, the elaborated type specifier
  11805. /// in a friend declaration is required to obey the restrictions of a
  11806. /// class-head (i.e. no typedefs in the scope chain), template
  11807. /// parameters are required to match up with simple template-ids, &c.
  11808. /// However, unlike when declaring a template specialization, it's
  11809. /// okay to refer to a template specialization without an empty
  11810. /// template parameter declaration, e.g.
  11811. /// friend class A<T>::B<unsigned>;
  11812. /// We permit this as a special case; if there are any template
  11813. /// parameters present at all, require proper matching, i.e.
  11814. /// template <> template \<class T> friend class A<int>::B;
  11815. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  11816. MultiTemplateParamsArg TempParams) {
  11817. SourceLocation Loc = DS.getLocStart();
  11818. assert(DS.isFriendSpecified());
  11819. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  11820. // Try to convert the decl specifier to a type. This works for
  11821. // friend templates because ActOnTag never produces a ClassTemplateDecl
  11822. // for a TUK_Friend.
  11823. Declarator TheDeclarator(DS, Declarator::MemberContext);
  11824. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  11825. QualType T = TSI->getType();
  11826. if (TheDeclarator.isInvalidType())
  11827. return nullptr;
  11828. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  11829. return nullptr;
  11830. // This is definitely an error in C++98. It's probably meant to
  11831. // be forbidden in C++0x, too, but the specification is just
  11832. // poorly written.
  11833. //
  11834. // The problem is with declarations like the following:
  11835. // template <T> friend A<T>::foo;
  11836. // where deciding whether a class C is a friend or not now hinges
  11837. // on whether there exists an instantiation of A that causes
  11838. // 'foo' to equal C. There are restrictions on class-heads
  11839. // (which we declare (by fiat) elaborated friend declarations to
  11840. // be) that makes this tractable.
  11841. //
  11842. // FIXME: handle "template <> friend class A<T>;", which
  11843. // is possibly well-formed? Who even knows?
  11844. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  11845. Diag(Loc, diag::err_tagless_friend_type_template)
  11846. << DS.getSourceRange();
  11847. return nullptr;
  11848. }
  11849. // C++98 [class.friend]p1: A friend of a class is a function
  11850. // or class that is not a member of the class . . .
  11851. // This is fixed in DR77, which just barely didn't make the C++03
  11852. // deadline. It's also a very silly restriction that seriously
  11853. // affects inner classes and which nobody else seems to implement;
  11854. // thus we never diagnose it, not even in -pedantic.
  11855. //
  11856. // But note that we could warn about it: it's always useless to
  11857. // friend one of your own members (it's not, however, worthless to
  11858. // friend a member of an arbitrary specialization of your template).
  11859. Decl *D;
  11860. if (!TempParams.empty())
  11861. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  11862. TempParams,
  11863. TSI,
  11864. DS.getFriendSpecLoc());
  11865. else
  11866. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  11867. if (!D)
  11868. return nullptr;
  11869. D->setAccess(AS_public);
  11870. CurContext->addDecl(D);
  11871. return D;
  11872. }
  11873. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  11874. MultiTemplateParamsArg TemplateParams) {
  11875. const DeclSpec &DS = D.getDeclSpec();
  11876. assert(DS.isFriendSpecified());
  11877. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  11878. SourceLocation Loc = D.getIdentifierLoc();
  11879. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11880. // C++ [class.friend]p1
  11881. // A friend of a class is a function or class....
  11882. // Note that this sees through typedefs, which is intended.
  11883. // It *doesn't* see through dependent types, which is correct
  11884. // according to [temp.arg.type]p3:
  11885. // If a declaration acquires a function type through a
  11886. // type dependent on a template-parameter and this causes
  11887. // a declaration that does not use the syntactic form of a
  11888. // function declarator to have a function type, the program
  11889. // is ill-formed.
  11890. if (!TInfo->getType()->isFunctionType()) {
  11891. Diag(Loc, diag::err_unexpected_friend);
  11892. // It might be worthwhile to try to recover by creating an
  11893. // appropriate declaration.
  11894. return nullptr;
  11895. }
  11896. // C++ [namespace.memdef]p3
  11897. // - If a friend declaration in a non-local class first declares a
  11898. // class or function, the friend class or function is a member
  11899. // of the innermost enclosing namespace.
  11900. // - The name of the friend is not found by simple name lookup
  11901. // until a matching declaration is provided in that namespace
  11902. // scope (either before or after the class declaration granting
  11903. // friendship).
  11904. // - If a friend function is called, its name may be found by the
  11905. // name lookup that considers functions from namespaces and
  11906. // classes associated with the types of the function arguments.
  11907. // - When looking for a prior declaration of a class or a function
  11908. // declared as a friend, scopes outside the innermost enclosing
  11909. // namespace scope are not considered.
  11910. CXXScopeSpec &SS = D.getCXXScopeSpec();
  11911. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  11912. DeclarationName Name = NameInfo.getName();
  11913. assert(Name);
  11914. // Check for unexpanded parameter packs.
  11915. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  11916. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  11917. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  11918. return nullptr;
  11919. // The context we found the declaration in, or in which we should
  11920. // create the declaration.
  11921. DeclContext *DC;
  11922. Scope *DCScope = S;
  11923. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  11924. ForRedeclaration);
  11925. // There are five cases here.
  11926. // - There's no scope specifier and we're in a local class. Only look
  11927. // for functions declared in the immediately-enclosing block scope.
  11928. // We recover from invalid scope qualifiers as if they just weren't there.
  11929. FunctionDecl *FunctionContainingLocalClass = nullptr;
  11930. if ((SS.isInvalid() || !SS.isSet()) &&
  11931. (FunctionContainingLocalClass =
  11932. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  11933. // C++11 [class.friend]p11:
  11934. // If a friend declaration appears in a local class and the name
  11935. // specified is an unqualified name, a prior declaration is
  11936. // looked up without considering scopes that are outside the
  11937. // innermost enclosing non-class scope. For a friend function
  11938. // declaration, if there is no prior declaration, the program is
  11939. // ill-formed.
  11940. // Find the innermost enclosing non-class scope. This is the block
  11941. // scope containing the local class definition (or for a nested class,
  11942. // the outer local class).
  11943. DCScope = S->getFnParent();
  11944. // Look up the function name in the scope.
  11945. Previous.clear(LookupLocalFriendName);
  11946. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  11947. if (!Previous.empty()) {
  11948. // All possible previous declarations must have the same context:
  11949. // either they were declared at block scope or they are members of
  11950. // one of the enclosing local classes.
  11951. DC = Previous.getRepresentativeDecl()->getDeclContext();
  11952. } else {
  11953. // This is ill-formed, but provide the context that we would have
  11954. // declared the function in, if we were permitted to, for error recovery.
  11955. DC = FunctionContainingLocalClass;
  11956. }
  11957. adjustContextForLocalExternDecl(DC);
  11958. // C++ [class.friend]p6:
  11959. // A function can be defined in a friend declaration of a class if and
  11960. // only if the class is a non-local class (9.8), the function name is
  11961. // unqualified, and the function has namespace scope.
  11962. if (D.isFunctionDefinition()) {
  11963. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  11964. }
  11965. // - There's no scope specifier, in which case we just go to the
  11966. // appropriate scope and look for a function or function template
  11967. // there as appropriate.
  11968. } else if (SS.isInvalid() || !SS.isSet()) {
  11969. // C++11 [namespace.memdef]p3:
  11970. // If the name in a friend declaration is neither qualified nor
  11971. // a template-id and the declaration is a function or an
  11972. // elaborated-type-specifier, the lookup to determine whether
  11973. // the entity has been previously declared shall not consider
  11974. // any scopes outside the innermost enclosing namespace.
  11975. bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
  11976. // Find the appropriate context according to the above.
  11977. DC = CurContext;
  11978. // Skip class contexts. If someone can cite chapter and verse
  11979. // for this behavior, that would be nice --- it's what GCC and
  11980. // EDG do, and it seems like a reasonable intent, but the spec
  11981. // really only says that checks for unqualified existing
  11982. // declarations should stop at the nearest enclosing namespace,
  11983. // not that they should only consider the nearest enclosing
  11984. // namespace.
  11985. while (DC->isRecord())
  11986. DC = DC->getParent();
  11987. DeclContext *LookupDC = DC;
  11988. while (LookupDC->isTransparentContext())
  11989. LookupDC = LookupDC->getParent();
  11990. while (true) {
  11991. LookupQualifiedName(Previous, LookupDC);
  11992. if (!Previous.empty()) {
  11993. DC = LookupDC;
  11994. break;
  11995. }
  11996. if (isTemplateId) {
  11997. if (isa<TranslationUnitDecl>(LookupDC)) break;
  11998. } else {
  11999. if (LookupDC->isFileContext()) break;
  12000. }
  12001. LookupDC = LookupDC->getParent();
  12002. }
  12003. DCScope = getScopeForDeclContext(S, DC);
  12004. // - There's a non-dependent scope specifier, in which case we
  12005. // compute it and do a previous lookup there for a function
  12006. // or function template.
  12007. } else if (!SS.getScopeRep()->isDependent()) {
  12008. DC = computeDeclContext(SS);
  12009. if (!DC) return nullptr;
  12010. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  12011. LookupQualifiedName(Previous, DC);
  12012. // Ignore things found implicitly in the wrong scope.
  12013. // TODO: better diagnostics for this case. Suggesting the right
  12014. // qualified scope would be nice...
  12015. LookupResult::Filter F = Previous.makeFilter();
  12016. while (F.hasNext()) {
  12017. NamedDecl *D = F.next();
  12018. if (!DC->InEnclosingNamespaceSetOf(
  12019. D->getDeclContext()->getRedeclContext()))
  12020. F.erase();
  12021. }
  12022. F.done();
  12023. if (Previous.empty()) {
  12024. D.setInvalidType();
  12025. Diag(Loc, diag::err_qualified_friend_not_found)
  12026. << Name << TInfo->getType();
  12027. return nullptr;
  12028. }
  12029. // C++ [class.friend]p1: A friend of a class is a function or
  12030. // class that is not a member of the class . . .
  12031. if (DC->Equals(CurContext))
  12032. Diag(DS.getFriendSpecLoc(),
  12033. getLangOpts().CPlusPlus11 ?
  12034. diag::warn_cxx98_compat_friend_is_member :
  12035. diag::err_friend_is_member);
  12036. if (D.isFunctionDefinition()) {
  12037. // C++ [class.friend]p6:
  12038. // A function can be defined in a friend declaration of a class if and
  12039. // only if the class is a non-local class (9.8), the function name is
  12040. // unqualified, and the function has namespace scope.
  12041. SemaDiagnosticBuilder DB
  12042. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  12043. DB << SS.getScopeRep();
  12044. if (DC->isFileContext())
  12045. DB << FixItHint::CreateRemoval(SS.getRange());
  12046. SS.clear();
  12047. }
  12048. // - There's a scope specifier that does not match any template
  12049. // parameter lists, in which case we use some arbitrary context,
  12050. // create a method or method template, and wait for instantiation.
  12051. // - There's a scope specifier that does match some template
  12052. // parameter lists, which we don't handle right now.
  12053. } else {
  12054. if (D.isFunctionDefinition()) {
  12055. // C++ [class.friend]p6:
  12056. // A function can be defined in a friend declaration of a class if and
  12057. // only if the class is a non-local class (9.8), the function name is
  12058. // unqualified, and the function has namespace scope.
  12059. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  12060. << SS.getScopeRep();
  12061. }
  12062. DC = CurContext;
  12063. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  12064. }
  12065. if (!DC->isRecord()) {
  12066. int DiagArg = -1;
  12067. switch (D.getName().getKind()) {
  12068. case UnqualifiedId::IK_ConstructorTemplateId:
  12069. case UnqualifiedId::IK_ConstructorName:
  12070. DiagArg = 0;
  12071. break;
  12072. case UnqualifiedId::IK_DestructorName:
  12073. DiagArg = 1;
  12074. break;
  12075. case UnqualifiedId::IK_ConversionFunctionId:
  12076. DiagArg = 2;
  12077. break;
  12078. case UnqualifiedId::IK_DeductionGuideName:
  12079. DiagArg = 3;
  12080. break;
  12081. case UnqualifiedId::IK_Identifier:
  12082. case UnqualifiedId::IK_ImplicitSelfParam:
  12083. case UnqualifiedId::IK_LiteralOperatorId:
  12084. case UnqualifiedId::IK_OperatorFunctionId:
  12085. case UnqualifiedId::IK_TemplateId:
  12086. break;
  12087. }
  12088. // This implies that it has to be an operator or function.
  12089. if (DiagArg >= 0) {
  12090. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  12091. return nullptr;
  12092. }
  12093. }
  12094. // FIXME: This is an egregious hack to cope with cases where the scope stack
  12095. // does not contain the declaration context, i.e., in an out-of-line
  12096. // definition of a class.
  12097. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  12098. if (!DCScope) {
  12099. FakeDCScope.setEntity(DC);
  12100. DCScope = &FakeDCScope;
  12101. }
  12102. bool AddToScope = true;
  12103. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  12104. TemplateParams, AddToScope);
  12105. if (!ND) return nullptr;
  12106. assert(ND->getLexicalDeclContext() == CurContext);
  12107. // If we performed typo correction, we might have added a scope specifier
  12108. // and changed the decl context.
  12109. DC = ND->getDeclContext();
  12110. // Add the function declaration to the appropriate lookup tables,
  12111. // adjusting the redeclarations list as necessary. We don't
  12112. // want to do this yet if the friending class is dependent.
  12113. //
  12114. // Also update the scope-based lookup if the target context's
  12115. // lookup context is in lexical scope.
  12116. if (!CurContext->isDependentContext()) {
  12117. DC = DC->getRedeclContext();
  12118. DC->makeDeclVisibleInContext(ND);
  12119. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12120. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  12121. }
  12122. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  12123. D.getIdentifierLoc(), ND,
  12124. DS.getFriendSpecLoc());
  12125. FrD->setAccess(AS_public);
  12126. CurContext->addDecl(FrD);
  12127. if (ND->isInvalidDecl()) {
  12128. FrD->setInvalidDecl();
  12129. } else {
  12130. if (DC->isRecord()) CheckFriendAccess(ND);
  12131. FunctionDecl *FD;
  12132. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  12133. FD = FTD->getTemplatedDecl();
  12134. else
  12135. FD = cast<FunctionDecl>(ND);
  12136. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  12137. // default argument expression, that declaration shall be a definition
  12138. // and shall be the only declaration of the function or function
  12139. // template in the translation unit.
  12140. if (functionDeclHasDefaultArgument(FD)) {
  12141. // We can't look at FD->getPreviousDecl() because it may not have been set
  12142. // if we're in a dependent context. If the function is known to be a
  12143. // redeclaration, we will have narrowed Previous down to the right decl.
  12144. if (D.isRedeclaration()) {
  12145. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  12146. Diag(Previous.getRepresentativeDecl()->getLocation(),
  12147. diag::note_previous_declaration);
  12148. } else if (!D.isFunctionDefinition())
  12149. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  12150. }
  12151. // Mark templated-scope function declarations as unsupported.
  12152. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  12153. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  12154. << SS.getScopeRep() << SS.getRange()
  12155. << cast<CXXRecordDecl>(CurContext);
  12156. FrD->setUnsupportedFriend(true);
  12157. }
  12158. }
  12159. return ND;
  12160. }
  12161. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  12162. AdjustDeclIfTemplate(Dcl);
  12163. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  12164. if (!Fn) {
  12165. Diag(DelLoc, diag::err_deleted_non_function);
  12166. return;
  12167. }
  12168. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  12169. // Don't consider the implicit declaration we generate for explicit
  12170. // specializations. FIXME: Do not generate these implicit declarations.
  12171. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  12172. Prev->getPreviousDecl()) &&
  12173. !Prev->isDefined()) {
  12174. Diag(DelLoc, diag::err_deleted_decl_not_first);
  12175. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  12176. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  12177. : diag::note_previous_declaration);
  12178. }
  12179. // If the declaration wasn't the first, we delete the function anyway for
  12180. // recovery.
  12181. Fn = Fn->getCanonicalDecl();
  12182. }
  12183. // dllimport/dllexport cannot be deleted.
  12184. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  12185. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  12186. Fn->setInvalidDecl();
  12187. }
  12188. if (Fn->isDeleted())
  12189. return;
  12190. // See if we're deleting a function which is already known to override a
  12191. // non-deleted virtual function.
  12192. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  12193. bool IssuedDiagnostic = false;
  12194. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  12195. E = MD->end_overridden_methods();
  12196. I != E; ++I) {
  12197. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  12198. if (!IssuedDiagnostic) {
  12199. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  12200. IssuedDiagnostic = true;
  12201. }
  12202. Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  12203. }
  12204. }
  12205. // If this function was implicitly deleted because it was defaulted,
  12206. // explain why it was deleted.
  12207. if (IssuedDiagnostic && MD->isDefaulted())
  12208. ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
  12209. /*Diagnose*/true);
  12210. }
  12211. // C++11 [basic.start.main]p3:
  12212. // A program that defines main as deleted [...] is ill-formed.
  12213. if (Fn->isMain())
  12214. Diag(DelLoc, diag::err_deleted_main);
  12215. // C++11 [dcl.fct.def.delete]p4:
  12216. // A deleted function is implicitly inline.
  12217. Fn->setImplicitlyInline();
  12218. Fn->setDeletedAsWritten();
  12219. }
  12220. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  12221. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  12222. if (MD) {
  12223. if (MD->getParent()->isDependentType()) {
  12224. MD->setDefaulted();
  12225. MD->setExplicitlyDefaulted();
  12226. return;
  12227. }
  12228. CXXSpecialMember Member = getSpecialMember(MD);
  12229. if (Member == CXXInvalid) {
  12230. if (!MD->isInvalidDecl())
  12231. Diag(DefaultLoc, diag::err_default_special_members);
  12232. return;
  12233. }
  12234. MD->setDefaulted();
  12235. MD->setExplicitlyDefaulted();
  12236. // If this definition appears within the record, do the checking when
  12237. // the record is complete.
  12238. const FunctionDecl *Primary = MD;
  12239. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  12240. // Ask the template instantiation pattern that actually had the
  12241. // '= default' on it.
  12242. Primary = Pattern;
  12243. // If the method was defaulted on its first declaration, we will have
  12244. // already performed the checking in CheckCompletedCXXClass. Such a
  12245. // declaration doesn't trigger an implicit definition.
  12246. if (Primary->getCanonicalDecl()->isDefaulted())
  12247. return;
  12248. CheckExplicitlyDefaultedSpecialMember(MD);
  12249. if (!MD->isInvalidDecl())
  12250. DefineImplicitSpecialMember(*this, MD, DefaultLoc);
  12251. } else {
  12252. Diag(DefaultLoc, diag::err_default_special_members);
  12253. }
  12254. }
  12255. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  12256. for (Stmt *SubStmt : S->children()) {
  12257. if (!SubStmt)
  12258. continue;
  12259. if (isa<ReturnStmt>(SubStmt))
  12260. Self.Diag(SubStmt->getLocStart(),
  12261. diag::err_return_in_constructor_handler);
  12262. if (!isa<Expr>(SubStmt))
  12263. SearchForReturnInStmt(Self, SubStmt);
  12264. }
  12265. }
  12266. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  12267. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  12268. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  12269. SearchForReturnInStmt(*this, Handler);
  12270. }
  12271. }
  12272. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  12273. const CXXMethodDecl *Old) {
  12274. const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
  12275. const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
  12276. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  12277. // If the calling conventions match, everything is fine
  12278. if (NewCC == OldCC)
  12279. return false;
  12280. // If the calling conventions mismatch because the new function is static,
  12281. // suppress the calling convention mismatch error; the error about static
  12282. // function override (err_static_overrides_virtual from
  12283. // Sema::CheckFunctionDeclaration) is more clear.
  12284. if (New->getStorageClass() == SC_Static)
  12285. return false;
  12286. Diag(New->getLocation(),
  12287. diag::err_conflicting_overriding_cc_attributes)
  12288. << New->getDeclName() << New->getType() << Old->getType();
  12289. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  12290. return true;
  12291. }
  12292. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  12293. const CXXMethodDecl *Old) {
  12294. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  12295. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  12296. if (Context.hasSameType(NewTy, OldTy) ||
  12297. NewTy->isDependentType() || OldTy->isDependentType())
  12298. return false;
  12299. // Check if the return types are covariant
  12300. QualType NewClassTy, OldClassTy;
  12301. /// Both types must be pointers or references to classes.
  12302. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  12303. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  12304. NewClassTy = NewPT->getPointeeType();
  12305. OldClassTy = OldPT->getPointeeType();
  12306. }
  12307. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  12308. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  12309. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  12310. NewClassTy = NewRT->getPointeeType();
  12311. OldClassTy = OldRT->getPointeeType();
  12312. }
  12313. }
  12314. }
  12315. // The return types aren't either both pointers or references to a class type.
  12316. if (NewClassTy.isNull()) {
  12317. Diag(New->getLocation(),
  12318. diag::err_different_return_type_for_overriding_virtual_function)
  12319. << New->getDeclName() << NewTy << OldTy
  12320. << New->getReturnTypeSourceRange();
  12321. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12322. << Old->getReturnTypeSourceRange();
  12323. return true;
  12324. }
  12325. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  12326. // C++14 [class.virtual]p8:
  12327. // If the class type in the covariant return type of D::f differs from
  12328. // that of B::f, the class type in the return type of D::f shall be
  12329. // complete at the point of declaration of D::f or shall be the class
  12330. // type D.
  12331. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  12332. if (!RT->isBeingDefined() &&
  12333. RequireCompleteType(New->getLocation(), NewClassTy,
  12334. diag::err_covariant_return_incomplete,
  12335. New->getDeclName()))
  12336. return true;
  12337. }
  12338. // Check if the new class derives from the old class.
  12339. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  12340. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  12341. << New->getDeclName() << NewTy << OldTy
  12342. << New->getReturnTypeSourceRange();
  12343. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12344. << Old->getReturnTypeSourceRange();
  12345. return true;
  12346. }
  12347. // Check if we the conversion from derived to base is valid.
  12348. if (CheckDerivedToBaseConversion(
  12349. NewClassTy, OldClassTy,
  12350. diag::err_covariant_return_inaccessible_base,
  12351. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  12352. New->getLocation(), New->getReturnTypeSourceRange(),
  12353. New->getDeclName(), nullptr)) {
  12354. // FIXME: this note won't trigger for delayed access control
  12355. // diagnostics, and it's impossible to get an undelayed error
  12356. // here from access control during the original parse because
  12357. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  12358. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12359. << Old->getReturnTypeSourceRange();
  12360. return true;
  12361. }
  12362. }
  12363. // The qualifiers of the return types must be the same.
  12364. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  12365. Diag(New->getLocation(),
  12366. diag::err_covariant_return_type_different_qualifications)
  12367. << New->getDeclName() << NewTy << OldTy
  12368. << New->getReturnTypeSourceRange();
  12369. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12370. << Old->getReturnTypeSourceRange();
  12371. return true;
  12372. }
  12373. // The new class type must have the same or less qualifiers as the old type.
  12374. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  12375. Diag(New->getLocation(),
  12376. diag::err_covariant_return_type_class_type_more_qualified)
  12377. << New->getDeclName() << NewTy << OldTy
  12378. << New->getReturnTypeSourceRange();
  12379. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  12380. << Old->getReturnTypeSourceRange();
  12381. return true;
  12382. }
  12383. return false;
  12384. }
  12385. /// \brief Mark the given method pure.
  12386. ///
  12387. /// \param Method the method to be marked pure.
  12388. ///
  12389. /// \param InitRange the source range that covers the "0" initializer.
  12390. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  12391. SourceLocation EndLoc = InitRange.getEnd();
  12392. if (EndLoc.isValid())
  12393. Method->setRangeEnd(EndLoc);
  12394. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  12395. Method->setPure();
  12396. return false;
  12397. }
  12398. if (!Method->isInvalidDecl())
  12399. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  12400. << Method->getDeclName() << InitRange;
  12401. return true;
  12402. }
  12403. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  12404. if (D->getFriendObjectKind())
  12405. Diag(D->getLocation(), diag::err_pure_friend);
  12406. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  12407. CheckPureMethod(M, ZeroLoc);
  12408. else
  12409. Diag(D->getLocation(), diag::err_illegal_initializer);
  12410. }
  12411. /// \brief Determine whether the given declaration is a static data member.
  12412. static bool isStaticDataMember(const Decl *D) {
  12413. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  12414. return Var->isStaticDataMember();
  12415. return false;
  12416. }
  12417. /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
  12418. /// an initializer for the out-of-line declaration 'Dcl'. The scope
  12419. /// is a fresh scope pushed for just this purpose.
  12420. ///
  12421. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  12422. /// static data member of class X, names should be looked up in the scope of
  12423. /// class X.
  12424. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  12425. // If there is no declaration, there was an error parsing it.
  12426. if (!D || D->isInvalidDecl())
  12427. return;
  12428. // We will always have a nested name specifier here, but this declaration
  12429. // might not be out of line if the specifier names the current namespace:
  12430. // extern int n;
  12431. // int ::n = 0;
  12432. if (D->isOutOfLine())
  12433. EnterDeclaratorContext(S, D->getDeclContext());
  12434. // If we are parsing the initializer for a static data member, push a
  12435. // new expression evaluation context that is associated with this static
  12436. // data member.
  12437. if (isStaticDataMember(D))
  12438. PushExpressionEvaluationContext(PotentiallyEvaluated, D);
  12439. }
  12440. /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
  12441. /// initializer for the out-of-line declaration 'D'.
  12442. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  12443. // If there is no declaration, there was an error parsing it.
  12444. if (!D || D->isInvalidDecl())
  12445. return;
  12446. if (isStaticDataMember(D))
  12447. PopExpressionEvaluationContext();
  12448. if (D->isOutOfLine())
  12449. ExitDeclaratorContext(S);
  12450. }
  12451. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  12452. /// C++ if/switch/while/for statement.
  12453. /// e.g: "if (int x = f()) {...}"
  12454. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  12455. // C++ 6.4p2:
  12456. // The declarator shall not specify a function or an array.
  12457. // The type-specifier-seq shall not contain typedef and shall not declare a
  12458. // new class or enumeration.
  12459. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  12460. "Parser allowed 'typedef' as storage class of condition decl.");
  12461. Decl *Dcl = ActOnDeclarator(S, D);
  12462. if (!Dcl)
  12463. return true;
  12464. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  12465. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  12466. << D.getSourceRange();
  12467. return true;
  12468. }
  12469. return Dcl;
  12470. }
  12471. void Sema::LoadExternalVTableUses() {
  12472. if (!ExternalSource)
  12473. return;
  12474. SmallVector<ExternalVTableUse, 4> VTables;
  12475. ExternalSource->ReadUsedVTables(VTables);
  12476. SmallVector<VTableUse, 4> NewUses;
  12477. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  12478. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  12479. = VTablesUsed.find(VTables[I].Record);
  12480. // Even if a definition wasn't required before, it may be required now.
  12481. if (Pos != VTablesUsed.end()) {
  12482. if (!Pos->second && VTables[I].DefinitionRequired)
  12483. Pos->second = true;
  12484. continue;
  12485. }
  12486. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  12487. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  12488. }
  12489. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  12490. }
  12491. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  12492. bool DefinitionRequired) {
  12493. // Ignore any vtable uses in unevaluated operands or for classes that do
  12494. // not have a vtable.
  12495. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  12496. CurContext->isDependentContext() || isUnevaluatedContext())
  12497. return;
  12498. // Try to insert this class into the map.
  12499. LoadExternalVTableUses();
  12500. Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  12501. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  12502. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  12503. if (!Pos.second) {
  12504. // If we already had an entry, check to see if we are promoting this vtable
  12505. // to require a definition. If so, we need to reappend to the VTableUses
  12506. // list, since we may have already processed the first entry.
  12507. if (DefinitionRequired && !Pos.first->second) {
  12508. Pos.first->second = true;
  12509. } else {
  12510. // Otherwise, we can early exit.
  12511. return;
  12512. }
  12513. } else {
  12514. // The Microsoft ABI requires that we perform the destructor body
  12515. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  12516. // the deleting destructor is emitted with the vtable, not with the
  12517. // destructor definition as in the Itanium ABI.
  12518. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12519. CXXDestructorDecl *DD = Class->getDestructor();
  12520. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  12521. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  12522. // If this is an out-of-line declaration, marking it referenced will
  12523. // not do anything. Manually call CheckDestructor to look up operator
  12524. // delete().
  12525. ContextRAII SavedContext(*this, DD);
  12526. CheckDestructor(DD);
  12527. } else {
  12528. MarkFunctionReferenced(Loc, Class->getDestructor());
  12529. }
  12530. }
  12531. }
  12532. }
  12533. // Local classes need to have their virtual members marked
  12534. // immediately. For all other classes, we mark their virtual members
  12535. // at the end of the translation unit.
  12536. if (Class->isLocalClass())
  12537. MarkVirtualMembersReferenced(Loc, Class);
  12538. else
  12539. VTableUses.push_back(std::make_pair(Class, Loc));
  12540. }
  12541. bool Sema::DefineUsedVTables() {
  12542. LoadExternalVTableUses();
  12543. if (VTableUses.empty())
  12544. return false;
  12545. // Note: The VTableUses vector could grow as a result of marking
  12546. // the members of a class as "used", so we check the size each
  12547. // time through the loop and prefer indices (which are stable) to
  12548. // iterators (which are not).
  12549. bool DefinedAnything = false;
  12550. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  12551. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  12552. if (!Class)
  12553. continue;
  12554. TemplateSpecializationKind ClassTSK =
  12555. Class->getTemplateSpecializationKind();
  12556. SourceLocation Loc = VTableUses[I].second;
  12557. bool DefineVTable = true;
  12558. // If this class has a key function, but that key function is
  12559. // defined in another translation unit, we don't need to emit the
  12560. // vtable even though we're using it.
  12561. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  12562. if (KeyFunction && !KeyFunction->hasBody()) {
  12563. // The key function is in another translation unit.
  12564. DefineVTable = false;
  12565. TemplateSpecializationKind TSK =
  12566. KeyFunction->getTemplateSpecializationKind();
  12567. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  12568. TSK != TSK_ImplicitInstantiation &&
  12569. "Instantiations don't have key functions");
  12570. (void)TSK;
  12571. } else if (!KeyFunction) {
  12572. // If we have a class with no key function that is the subject
  12573. // of an explicit instantiation declaration, suppress the
  12574. // vtable; it will live with the explicit instantiation
  12575. // definition.
  12576. bool IsExplicitInstantiationDeclaration =
  12577. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  12578. for (auto R : Class->redecls()) {
  12579. TemplateSpecializationKind TSK
  12580. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  12581. if (TSK == TSK_ExplicitInstantiationDeclaration)
  12582. IsExplicitInstantiationDeclaration = true;
  12583. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  12584. IsExplicitInstantiationDeclaration = false;
  12585. break;
  12586. }
  12587. }
  12588. if (IsExplicitInstantiationDeclaration)
  12589. DefineVTable = false;
  12590. }
  12591. // The exception specifications for all virtual members may be needed even
  12592. // if we are not providing an authoritative form of the vtable in this TU.
  12593. // We may choose to emit it available_externally anyway.
  12594. if (!DefineVTable) {
  12595. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  12596. continue;
  12597. }
  12598. // Mark all of the virtual members of this class as referenced, so
  12599. // that we can build a vtable. Then, tell the AST consumer that a
  12600. // vtable for this class is required.
  12601. DefinedAnything = true;
  12602. MarkVirtualMembersReferenced(Loc, Class);
  12603. CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  12604. if (VTablesUsed[Canonical])
  12605. Consumer.HandleVTable(Class);
  12606. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  12607. // no key function or the key function is inlined. Don't warn in C++ ABIs
  12608. // that lack key functions, since the user won't be able to make one.
  12609. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  12610. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
  12611. const FunctionDecl *KeyFunctionDef = nullptr;
  12612. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  12613. KeyFunctionDef->isInlined())) {
  12614. Diag(Class->getLocation(),
  12615. ClassTSK == TSK_ExplicitInstantiationDefinition
  12616. ? diag::warn_weak_template_vtable
  12617. : diag::warn_weak_vtable)
  12618. << Class;
  12619. }
  12620. }
  12621. }
  12622. VTableUses.clear();
  12623. return DefinedAnything;
  12624. }
  12625. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  12626. const CXXRecordDecl *RD) {
  12627. for (const auto *I : RD->methods())
  12628. if (I->isVirtual() && !I->isPure())
  12629. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  12630. }
  12631. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  12632. const CXXRecordDecl *RD) {
  12633. // Mark all functions which will appear in RD's vtable as used.
  12634. CXXFinalOverriderMap FinalOverriders;
  12635. RD->getFinalOverriders(FinalOverriders);
  12636. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  12637. E = FinalOverriders.end();
  12638. I != E; ++I) {
  12639. for (OverridingMethods::const_iterator OI = I->second.begin(),
  12640. OE = I->second.end();
  12641. OI != OE; ++OI) {
  12642. assert(OI->second.size() > 0 && "no final overrider");
  12643. CXXMethodDecl *Overrider = OI->second.front().Method;
  12644. // C++ [basic.def.odr]p2:
  12645. // [...] A virtual member function is used if it is not pure. [...]
  12646. if (!Overrider->isPure())
  12647. MarkFunctionReferenced(Loc, Overrider);
  12648. }
  12649. }
  12650. // Only classes that have virtual bases need a VTT.
  12651. if (RD->getNumVBases() == 0)
  12652. return;
  12653. for (const auto &I : RD->bases()) {
  12654. const CXXRecordDecl *Base =
  12655. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  12656. if (Base->getNumVBases() == 0)
  12657. continue;
  12658. MarkVirtualMembersReferenced(Loc, Base);
  12659. }
  12660. }
  12661. /// SetIvarInitializers - This routine builds initialization ASTs for the
  12662. /// Objective-C implementation whose ivars need be initialized.
  12663. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  12664. if (!getLangOpts().CPlusPlus)
  12665. return;
  12666. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  12667. SmallVector<ObjCIvarDecl*, 8> ivars;
  12668. CollectIvarsToConstructOrDestruct(OID, ivars);
  12669. if (ivars.empty())
  12670. return;
  12671. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  12672. for (unsigned i = 0; i < ivars.size(); i++) {
  12673. FieldDecl *Field = ivars[i];
  12674. if (Field->isInvalidDecl())
  12675. continue;
  12676. CXXCtorInitializer *Member;
  12677. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  12678. InitializationKind InitKind =
  12679. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  12680. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  12681. ExprResult MemberInit =
  12682. InitSeq.Perform(*this, InitEntity, InitKind, None);
  12683. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  12684. // Note, MemberInit could actually come back empty if no initialization
  12685. // is required (e.g., because it would call a trivial default constructor)
  12686. if (!MemberInit.get() || MemberInit.isInvalid())
  12687. continue;
  12688. Member =
  12689. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  12690. SourceLocation(),
  12691. MemberInit.getAs<Expr>(),
  12692. SourceLocation());
  12693. AllToInit.push_back(Member);
  12694. // Be sure that the destructor is accessible and is marked as referenced.
  12695. if (const RecordType *RecordTy =
  12696. Context.getBaseElementType(Field->getType())
  12697. ->getAs<RecordType>()) {
  12698. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  12699. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  12700. MarkFunctionReferenced(Field->getLocation(), Destructor);
  12701. CheckDestructorAccess(Field->getLocation(), Destructor,
  12702. PDiag(diag::err_access_dtor_ivar)
  12703. << Context.getBaseElementType(Field->getType()));
  12704. }
  12705. }
  12706. }
  12707. ObjCImplementation->setIvarInitializers(Context,
  12708. AllToInit.data(), AllToInit.size());
  12709. }
  12710. }
  12711. static
  12712. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  12713. llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
  12714. llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
  12715. llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
  12716. Sema &S) {
  12717. if (Ctor->isInvalidDecl())
  12718. return;
  12719. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  12720. // Target may not be determinable yet, for instance if this is a dependent
  12721. // call in an uninstantiated template.
  12722. if (Target) {
  12723. const FunctionDecl *FNTarget = nullptr;
  12724. (void)Target->hasBody(FNTarget);
  12725. Target = const_cast<CXXConstructorDecl*>(
  12726. cast_or_null<CXXConstructorDecl>(FNTarget));
  12727. }
  12728. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  12729. // Avoid dereferencing a null pointer here.
  12730. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  12731. if (!Current.insert(Canonical).second)
  12732. return;
  12733. // We know that beyond here, we aren't chaining into a cycle.
  12734. if (!Target || !Target->isDelegatingConstructor() ||
  12735. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  12736. Valid.insert(Current.begin(), Current.end());
  12737. Current.clear();
  12738. // We've hit a cycle.
  12739. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  12740. Current.count(TCanonical)) {
  12741. // If we haven't diagnosed this cycle yet, do so now.
  12742. if (!Invalid.count(TCanonical)) {
  12743. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  12744. diag::warn_delegating_ctor_cycle)
  12745. << Ctor;
  12746. // Don't add a note for a function delegating directly to itself.
  12747. if (TCanonical != Canonical)
  12748. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  12749. CXXConstructorDecl *C = Target;
  12750. while (C->getCanonicalDecl() != Canonical) {
  12751. const FunctionDecl *FNTarget = nullptr;
  12752. (void)C->getTargetConstructor()->hasBody(FNTarget);
  12753. assert(FNTarget && "Ctor cycle through bodiless function");
  12754. C = const_cast<CXXConstructorDecl*>(
  12755. cast<CXXConstructorDecl>(FNTarget));
  12756. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  12757. }
  12758. }
  12759. Invalid.insert(Current.begin(), Current.end());
  12760. Current.clear();
  12761. } else {
  12762. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  12763. }
  12764. }
  12765. void Sema::CheckDelegatingCtorCycles() {
  12766. llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  12767. for (DelegatingCtorDeclsType::iterator
  12768. I = DelegatingCtorDecls.begin(ExternalSource),
  12769. E = DelegatingCtorDecls.end();
  12770. I != E; ++I)
  12771. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  12772. for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
  12773. CE = Invalid.end();
  12774. CI != CE; ++CI)
  12775. (*CI)->setInvalidDecl();
  12776. }
  12777. namespace {
  12778. /// \brief AST visitor that finds references to the 'this' expression.
  12779. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  12780. Sema &S;
  12781. public:
  12782. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  12783. bool VisitCXXThisExpr(CXXThisExpr *E) {
  12784. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  12785. << E->isImplicit();
  12786. return false;
  12787. }
  12788. };
  12789. }
  12790. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  12791. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  12792. if (!TSInfo)
  12793. return false;
  12794. TypeLoc TL = TSInfo->getTypeLoc();
  12795. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  12796. if (!ProtoTL)
  12797. return false;
  12798. // C++11 [expr.prim.general]p3:
  12799. // [The expression this] shall not appear before the optional
  12800. // cv-qualifier-seq and it shall not appear within the declaration of a
  12801. // static member function (although its type and value category are defined
  12802. // within a static member function as they are within a non-static member
  12803. // function). [ Note: this is because declaration matching does not occur
  12804. // until the complete declarator is known. - end note ]
  12805. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  12806. FindCXXThisExpr Finder(*this);
  12807. // If the return type came after the cv-qualifier-seq, check it now.
  12808. if (Proto->hasTrailingReturn() &&
  12809. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  12810. return true;
  12811. // Check the exception specification.
  12812. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  12813. return true;
  12814. return checkThisInStaticMemberFunctionAttributes(Method);
  12815. }
  12816. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  12817. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  12818. if (!TSInfo)
  12819. return false;
  12820. TypeLoc TL = TSInfo->getTypeLoc();
  12821. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  12822. if (!ProtoTL)
  12823. return false;
  12824. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  12825. FindCXXThisExpr Finder(*this);
  12826. switch (Proto->getExceptionSpecType()) {
  12827. case EST_Unparsed:
  12828. case EST_Uninstantiated:
  12829. case EST_Unevaluated:
  12830. case EST_BasicNoexcept:
  12831. case EST_DynamicNone:
  12832. case EST_MSAny:
  12833. case EST_None:
  12834. break;
  12835. case EST_ComputedNoexcept:
  12836. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  12837. return true;
  12838. case EST_Dynamic:
  12839. for (const auto &E : Proto->exceptions()) {
  12840. if (!Finder.TraverseType(E))
  12841. return true;
  12842. }
  12843. break;
  12844. }
  12845. return false;
  12846. }
  12847. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  12848. FindCXXThisExpr Finder(*this);
  12849. // Check attributes.
  12850. for (const auto *A : Method->attrs()) {
  12851. // FIXME: This should be emitted by tblgen.
  12852. Expr *Arg = nullptr;
  12853. ArrayRef<Expr *> Args;
  12854. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  12855. Arg = G->getArg();
  12856. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  12857. Arg = G->getArg();
  12858. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  12859. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  12860. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  12861. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  12862. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  12863. Arg = ETLF->getSuccessValue();
  12864. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  12865. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  12866. Arg = STLF->getSuccessValue();
  12867. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  12868. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  12869. Arg = LR->getArg();
  12870. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  12871. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  12872. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  12873. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  12874. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  12875. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  12876. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  12877. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  12878. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  12879. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  12880. if (Arg && !Finder.TraverseStmt(Arg))
  12881. return true;
  12882. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  12883. if (!Finder.TraverseStmt(Args[I]))
  12884. return true;
  12885. }
  12886. }
  12887. return false;
  12888. }
  12889. void Sema::checkExceptionSpecification(
  12890. bool IsTopLevel, ExceptionSpecificationType EST,
  12891. ArrayRef<ParsedType> DynamicExceptions,
  12892. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  12893. SmallVectorImpl<QualType> &Exceptions,
  12894. FunctionProtoType::ExceptionSpecInfo &ESI) {
  12895. Exceptions.clear();
  12896. ESI.Type = EST;
  12897. if (EST == EST_Dynamic) {
  12898. Exceptions.reserve(DynamicExceptions.size());
  12899. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  12900. // FIXME: Preserve type source info.
  12901. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  12902. if (IsTopLevel) {
  12903. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  12904. collectUnexpandedParameterPacks(ET, Unexpanded);
  12905. if (!Unexpanded.empty()) {
  12906. DiagnoseUnexpandedParameterPacks(
  12907. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  12908. Unexpanded);
  12909. continue;
  12910. }
  12911. }
  12912. // Check that the type is valid for an exception spec, and
  12913. // drop it if not.
  12914. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  12915. Exceptions.push_back(ET);
  12916. }
  12917. ESI.Exceptions = Exceptions;
  12918. return;
  12919. }
  12920. if (EST == EST_ComputedNoexcept) {
  12921. // If an error occurred, there's no expression here.
  12922. if (NoexceptExpr) {
  12923. assert((NoexceptExpr->isTypeDependent() ||
  12924. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  12925. Context.BoolTy) &&
  12926. "Parser should have made sure that the expression is boolean");
  12927. if (IsTopLevel && NoexceptExpr &&
  12928. DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  12929. ESI.Type = EST_BasicNoexcept;
  12930. return;
  12931. }
  12932. if (!NoexceptExpr->isValueDependent())
  12933. NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
  12934. diag::err_noexcept_needs_constant_expression,
  12935. /*AllowFold*/ false).get();
  12936. ESI.NoexceptExpr = NoexceptExpr;
  12937. }
  12938. return;
  12939. }
  12940. }
  12941. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  12942. ExceptionSpecificationType EST,
  12943. SourceRange SpecificationRange,
  12944. ArrayRef<ParsedType> DynamicExceptions,
  12945. ArrayRef<SourceRange> DynamicExceptionRanges,
  12946. Expr *NoexceptExpr) {
  12947. if (!MethodD)
  12948. return;
  12949. // Dig out the method we're referring to.
  12950. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  12951. MethodD = FunTmpl->getTemplatedDecl();
  12952. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  12953. if (!Method)
  12954. return;
  12955. // Check the exception specification.
  12956. llvm::SmallVector<QualType, 4> Exceptions;
  12957. FunctionProtoType::ExceptionSpecInfo ESI;
  12958. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  12959. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  12960. ESI);
  12961. // Update the exception specification on the function type.
  12962. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  12963. if (Method->isStatic())
  12964. checkThisInStaticMemberFunctionExceptionSpec(Method);
  12965. if (Method->isVirtual()) {
  12966. // Check overrides, which we previously had to delay.
  12967. for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
  12968. OEnd = Method->end_overridden_methods();
  12969. O != OEnd; ++O)
  12970. CheckOverridingFunctionExceptionSpec(Method, *O);
  12971. }
  12972. }
  12973. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  12974. ///
  12975. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  12976. SourceLocation DeclStart,
  12977. Declarator &D, Expr *BitWidth,
  12978. InClassInitStyle InitStyle,
  12979. AccessSpecifier AS,
  12980. AttributeList *MSPropertyAttr) {
  12981. IdentifierInfo *II = D.getIdentifier();
  12982. if (!II) {
  12983. Diag(DeclStart, diag::err_anonymous_property);
  12984. return nullptr;
  12985. }
  12986. SourceLocation Loc = D.getIdentifierLoc();
  12987. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12988. QualType T = TInfo->getType();
  12989. if (getLangOpts().CPlusPlus) {
  12990. CheckExtraCXXDefaultArguments(D);
  12991. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12992. UPPC_DataMemberType)) {
  12993. D.setInvalidType();
  12994. T = Context.IntTy;
  12995. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  12996. }
  12997. }
  12998. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  12999. if (D.getDeclSpec().isInlineSpecified())
  13000. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13001. << getLangOpts().CPlusPlus1z;
  13002. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13003. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13004. diag::err_invalid_thread)
  13005. << DeclSpec::getSpecifierName(TSCS);
  13006. // Check to see if this name was declared as a member previously
  13007. NamedDecl *PrevDecl = nullptr;
  13008. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  13009. LookupName(Previous, S);
  13010. switch (Previous.getResultKind()) {
  13011. case LookupResult::Found:
  13012. case LookupResult::FoundUnresolvedValue:
  13013. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13014. break;
  13015. case LookupResult::FoundOverloaded:
  13016. PrevDecl = Previous.getRepresentativeDecl();
  13017. break;
  13018. case LookupResult::NotFound:
  13019. case LookupResult::NotFoundInCurrentInstantiation:
  13020. case LookupResult::Ambiguous:
  13021. break;
  13022. }
  13023. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13024. // Maybe we will complain about the shadowed template parameter.
  13025. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13026. // Just pretend that we didn't see the previous declaration.
  13027. PrevDecl = nullptr;
  13028. }
  13029. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13030. PrevDecl = nullptr;
  13031. SourceLocation TSSL = D.getLocStart();
  13032. const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
  13033. MSPropertyDecl *NewPD = MSPropertyDecl::Create(
  13034. Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
  13035. ProcessDeclAttributes(TUScope, NewPD, D);
  13036. NewPD->setAccess(AS);
  13037. if (NewPD->isInvalidDecl())
  13038. Record->setInvalidDecl();
  13039. if (D.getDeclSpec().isModulePrivateSpecified())
  13040. NewPD->setModulePrivate();
  13041. if (NewPD->isInvalidDecl() && PrevDecl) {
  13042. // Don't introduce NewFD into scope; there's already something
  13043. // with the same name in the same scope.
  13044. } else if (II) {
  13045. PushOnScopeChains(NewPD, S);
  13046. } else
  13047. Record->addDecl(NewPD);
  13048. return NewPD;
  13049. }