SemaDeclCXX.cpp 694 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for C++ declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/ComparisonCategories.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/AST/TypeLoc.h"
  25. #include "clang/AST/TypeOrdering.h"
  26. #include "clang/Basic/AttributeCommonInfo.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/Specifiers.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/LiteralSupport.h"
  31. #include "clang/Lex/Preprocessor.h"
  32. #include "clang/Sema/CXXFieldCollector.h"
  33. #include "clang/Sema/DeclSpec.h"
  34. #include "clang/Sema/Initialization.h"
  35. #include "clang/Sema/Lookup.h"
  36. #include "clang/Sema/ParsedTemplate.h"
  37. #include "clang/Sema/Scope.h"
  38. #include "clang/Sema/ScopeInfo.h"
  39. #include "clang/Sema/SemaInternal.h"
  40. #include "clang/Sema/Template.h"
  41. #include "llvm/ADT/ScopeExit.h"
  42. #include "llvm/ADT/SmallString.h"
  43. #include "llvm/ADT/STLExtras.h"
  44. #include "llvm/ADT/StringExtras.h"
  45. #include <map>
  46. #include <set>
  47. using namespace clang;
  48. //===----------------------------------------------------------------------===//
  49. // CheckDefaultArgumentVisitor
  50. //===----------------------------------------------------------------------===//
  51. namespace {
  52. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  53. /// the default argument of a parameter to determine whether it
  54. /// contains any ill-formed subexpressions. For example, this will
  55. /// diagnose the use of local variables or parameters within the
  56. /// default argument expression.
  57. class CheckDefaultArgumentVisitor
  58. : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
  59. Sema &S;
  60. const Expr *DefaultArg;
  61. public:
  62. CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
  63. : S(S), DefaultArg(DefaultArg) {}
  64. bool VisitExpr(const Expr *Node);
  65. bool VisitDeclRefExpr(const DeclRefExpr *DRE);
  66. bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
  67. bool VisitLambdaExpr(const LambdaExpr *Lambda);
  68. bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
  69. };
  70. /// VisitExpr - Visit all of the children of this expression.
  71. bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
  72. bool IsInvalid = false;
  73. for (const Stmt *SubStmt : Node->children())
  74. IsInvalid |= Visit(SubStmt);
  75. return IsInvalid;
  76. }
  77. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  78. /// determine whether this declaration can be used in the default
  79. /// argument expression.
  80. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
  81. const NamedDecl *Decl = DRE->getDecl();
  82. if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
  83. // C++ [dcl.fct.default]p9:
  84. // [...] parameters of a function shall not be used in default
  85. // argument expressions, even if they are not evaluated. [...]
  86. //
  87. // C++17 [dcl.fct.default]p9 (by CWG 2082):
  88. // [...] A parameter shall not appear as a potentially-evaluated
  89. // expression in a default argument. [...]
  90. //
  91. if (DRE->isNonOdrUse() != NOUR_Unevaluated)
  92. return S.Diag(DRE->getBeginLoc(),
  93. diag::err_param_default_argument_references_param)
  94. << Param->getDeclName() << DefaultArg->getSourceRange();
  95. } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
  96. // C++ [dcl.fct.default]p7:
  97. // Local variables shall not be used in default argument
  98. // expressions.
  99. //
  100. // C++17 [dcl.fct.default]p7 (by CWG 2082):
  101. // A local variable shall not appear as a potentially-evaluated
  102. // expression in a default argument.
  103. //
  104. // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
  105. // Note: A local variable cannot be odr-used (6.3) in a default argument.
  106. //
  107. if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
  108. return S.Diag(DRE->getBeginLoc(),
  109. diag::err_param_default_argument_references_local)
  110. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  111. }
  112. return false;
  113. }
  114. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  115. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
  116. // C++ [dcl.fct.default]p8:
  117. // The keyword this shall not be used in a default argument of a
  118. // member function.
  119. return S.Diag(ThisE->getBeginLoc(),
  120. diag::err_param_default_argument_references_this)
  121. << ThisE->getSourceRange();
  122. }
  123. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
  124. const PseudoObjectExpr *POE) {
  125. bool Invalid = false;
  126. for (const Expr *E : POE->semantics()) {
  127. // Look through bindings.
  128. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  129. E = OVE->getSourceExpr();
  130. assert(E && "pseudo-object binding without source expression?");
  131. }
  132. Invalid |= Visit(E);
  133. }
  134. return Invalid;
  135. }
  136. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
  137. // C++11 [expr.lambda.prim]p13:
  138. // A lambda-expression appearing in a default argument shall not
  139. // implicitly or explicitly capture any entity.
  140. if (Lambda->capture_begin() == Lambda->capture_end())
  141. return false;
  142. return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
  143. }
  144. } // namespace
  145. void
  146. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  147. const CXXMethodDecl *Method) {
  148. // If we have an MSAny spec already, don't bother.
  149. if (!Method || ComputedEST == EST_MSAny)
  150. return;
  151. const FunctionProtoType *Proto
  152. = Method->getType()->getAs<FunctionProtoType>();
  153. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  154. if (!Proto)
  155. return;
  156. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  157. // If we have a throw-all spec at this point, ignore the function.
  158. if (ComputedEST == EST_None)
  159. return;
  160. if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
  161. EST = EST_BasicNoexcept;
  162. switch (EST) {
  163. case EST_Unparsed:
  164. case EST_Uninstantiated:
  165. case EST_Unevaluated:
  166. llvm_unreachable("should not see unresolved exception specs here");
  167. // If this function can throw any exceptions, make a note of that.
  168. case EST_MSAny:
  169. case EST_None:
  170. // FIXME: Whichever we see last of MSAny and None determines our result.
  171. // We should make a consistent, order-independent choice here.
  172. ClearExceptions();
  173. ComputedEST = EST;
  174. return;
  175. case EST_NoexceptFalse:
  176. ClearExceptions();
  177. ComputedEST = EST_None;
  178. return;
  179. // FIXME: If the call to this decl is using any of its default arguments, we
  180. // need to search them for potentially-throwing calls.
  181. // If this function has a basic noexcept, it doesn't affect the outcome.
  182. case EST_BasicNoexcept:
  183. case EST_NoexceptTrue:
  184. case EST_NoThrow:
  185. return;
  186. // If we're still at noexcept(true) and there's a throw() callee,
  187. // change to that specification.
  188. case EST_DynamicNone:
  189. if (ComputedEST == EST_BasicNoexcept)
  190. ComputedEST = EST_DynamicNone;
  191. return;
  192. case EST_DependentNoexcept:
  193. llvm_unreachable(
  194. "should not generate implicit declarations for dependent cases");
  195. case EST_Dynamic:
  196. break;
  197. }
  198. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  199. assert(ComputedEST != EST_None &&
  200. "Shouldn't collect exceptions when throw-all is guaranteed.");
  201. ComputedEST = EST_Dynamic;
  202. // Record the exceptions in this function's exception specification.
  203. for (const auto &E : Proto->exceptions())
  204. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  205. Exceptions.push_back(E);
  206. }
  207. void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
  208. if (!S || ComputedEST == EST_MSAny)
  209. return;
  210. // FIXME:
  211. //
  212. // C++0x [except.spec]p14:
  213. // [An] implicit exception-specification specifies the type-id T if and
  214. // only if T is allowed by the exception-specification of a function directly
  215. // invoked by f's implicit definition; f shall allow all exceptions if any
  216. // function it directly invokes allows all exceptions, and f shall allow no
  217. // exceptions if every function it directly invokes allows no exceptions.
  218. //
  219. // Note in particular that if an implicit exception-specification is generated
  220. // for a function containing a throw-expression, that specification can still
  221. // be noexcept(true).
  222. //
  223. // Note also that 'directly invoked' is not defined in the standard, and there
  224. // is no indication that we should only consider potentially-evaluated calls.
  225. //
  226. // Ultimately we should implement the intent of the standard: the exception
  227. // specification should be the set of exceptions which can be thrown by the
  228. // implicit definition. For now, we assume that any non-nothrow expression can
  229. // throw any exception.
  230. if (Self->canThrow(S))
  231. ComputedEST = EST_None;
  232. }
  233. ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  234. SourceLocation EqualLoc) {
  235. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  236. diag::err_typecheck_decl_incomplete_type))
  237. return true;
  238. // C++ [dcl.fct.default]p5
  239. // A default argument expression is implicitly converted (clause
  240. // 4) to the parameter type. The default argument expression has
  241. // the same semantic constraints as the initializer expression in
  242. // a declaration of a variable of the parameter type, using the
  243. // copy-initialization semantics (8.5).
  244. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  245. Param);
  246. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  247. EqualLoc);
  248. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  249. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  250. if (Result.isInvalid())
  251. return true;
  252. Arg = Result.getAs<Expr>();
  253. CheckCompletedExpr(Arg, EqualLoc);
  254. Arg = MaybeCreateExprWithCleanups(Arg);
  255. return Arg;
  256. }
  257. void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  258. SourceLocation EqualLoc) {
  259. // Add the default argument to the parameter
  260. Param->setDefaultArg(Arg);
  261. // We have already instantiated this parameter; provide each of the
  262. // instantiations with the uninstantiated default argument.
  263. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  264. = UnparsedDefaultArgInstantiations.find(Param);
  265. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  266. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  267. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  268. // We're done tracking this parameter's instantiations.
  269. UnparsedDefaultArgInstantiations.erase(InstPos);
  270. }
  271. }
  272. /// ActOnParamDefaultArgument - Check whether the default argument
  273. /// provided for a function parameter is well-formed. If so, attach it
  274. /// to the parameter declaration.
  275. void
  276. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  277. Expr *DefaultArg) {
  278. if (!param || !DefaultArg)
  279. return;
  280. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  281. UnparsedDefaultArgLocs.erase(Param);
  282. auto Fail = [&] {
  283. Param->setInvalidDecl();
  284. Param->setDefaultArg(new (Context) OpaqueValueExpr(
  285. EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
  286. };
  287. // Default arguments are only permitted in C++
  288. if (!getLangOpts().CPlusPlus) {
  289. Diag(EqualLoc, diag::err_param_default_argument)
  290. << DefaultArg->getSourceRange();
  291. return Fail();
  292. }
  293. // Check for unexpanded parameter packs.
  294. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  295. return Fail();
  296. }
  297. // C++11 [dcl.fct.default]p3
  298. // A default argument expression [...] shall not be specified for a
  299. // parameter pack.
  300. if (Param->isParameterPack()) {
  301. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  302. << DefaultArg->getSourceRange();
  303. // Recover by discarding the default argument.
  304. Param->setDefaultArg(nullptr);
  305. return;
  306. }
  307. ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
  308. if (Result.isInvalid())
  309. return Fail();
  310. DefaultArg = Result.getAs<Expr>();
  311. // Check that the default argument is well-formed
  312. CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
  313. if (DefaultArgChecker.Visit(DefaultArg))
  314. return Fail();
  315. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  316. }
  317. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  318. /// argument for a function parameter, but we can't parse it yet
  319. /// because we're inside a class definition. Note that this default
  320. /// argument will be parsed later.
  321. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  322. SourceLocation EqualLoc,
  323. SourceLocation ArgLoc) {
  324. if (!param)
  325. return;
  326. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  327. Param->setUnparsedDefaultArg();
  328. UnparsedDefaultArgLocs[Param] = ArgLoc;
  329. }
  330. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  331. /// the default argument for the parameter param failed.
  332. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  333. SourceLocation EqualLoc) {
  334. if (!param)
  335. return;
  336. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  337. Param->setInvalidDecl();
  338. UnparsedDefaultArgLocs.erase(Param);
  339. Param->setDefaultArg(new (Context) OpaqueValueExpr(
  340. EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
  341. }
  342. /// CheckExtraCXXDefaultArguments - Check for any extra default
  343. /// arguments in the declarator, which is not a function declaration
  344. /// or definition and therefore is not permitted to have default
  345. /// arguments. This routine should be invoked for every declarator
  346. /// that is not a function declaration or definition.
  347. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  348. // C++ [dcl.fct.default]p3
  349. // A default argument expression shall be specified only in the
  350. // parameter-declaration-clause of a function declaration or in a
  351. // template-parameter (14.1). It shall not be specified for a
  352. // parameter pack. If it is specified in a
  353. // parameter-declaration-clause, it shall not occur within a
  354. // declarator or abstract-declarator of a parameter-declaration.
  355. bool MightBeFunction = D.isFunctionDeclarationContext();
  356. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  357. DeclaratorChunk &chunk = D.getTypeObject(i);
  358. if (chunk.Kind == DeclaratorChunk::Function) {
  359. if (MightBeFunction) {
  360. // This is a function declaration. It can have default arguments, but
  361. // keep looking in case its return type is a function type with default
  362. // arguments.
  363. MightBeFunction = false;
  364. continue;
  365. }
  366. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  367. ++argIdx) {
  368. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  369. if (Param->hasUnparsedDefaultArg()) {
  370. std::unique_ptr<CachedTokens> Toks =
  371. std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
  372. SourceRange SR;
  373. if (Toks->size() > 1)
  374. SR = SourceRange((*Toks)[1].getLocation(),
  375. Toks->back().getLocation());
  376. else
  377. SR = UnparsedDefaultArgLocs[Param];
  378. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  379. << SR;
  380. } else if (Param->getDefaultArg()) {
  381. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  382. << Param->getDefaultArg()->getSourceRange();
  383. Param->setDefaultArg(nullptr);
  384. }
  385. }
  386. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  387. MightBeFunction = false;
  388. }
  389. }
  390. }
  391. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  392. return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
  393. return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
  394. });
  395. }
  396. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  397. /// function, once we already know that they have the same
  398. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  399. /// error, false otherwise.
  400. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  401. Scope *S) {
  402. bool Invalid = false;
  403. // The declaration context corresponding to the scope is the semantic
  404. // parent, unless this is a local function declaration, in which case
  405. // it is that surrounding function.
  406. DeclContext *ScopeDC = New->isLocalExternDecl()
  407. ? New->getLexicalDeclContext()
  408. : New->getDeclContext();
  409. // Find the previous declaration for the purpose of default arguments.
  410. FunctionDecl *PrevForDefaultArgs = Old;
  411. for (/**/; PrevForDefaultArgs;
  412. // Don't bother looking back past the latest decl if this is a local
  413. // extern declaration; nothing else could work.
  414. PrevForDefaultArgs = New->isLocalExternDecl()
  415. ? nullptr
  416. : PrevForDefaultArgs->getPreviousDecl()) {
  417. // Ignore hidden declarations.
  418. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  419. continue;
  420. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  421. !New->isCXXClassMember()) {
  422. // Ignore default arguments of old decl if they are not in
  423. // the same scope and this is not an out-of-line definition of
  424. // a member function.
  425. continue;
  426. }
  427. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  428. // If only one of these is a local function declaration, then they are
  429. // declared in different scopes, even though isDeclInScope may think
  430. // they're in the same scope. (If both are local, the scope check is
  431. // sufficient, and if neither is local, then they are in the same scope.)
  432. continue;
  433. }
  434. // We found the right previous declaration.
  435. break;
  436. }
  437. // C++ [dcl.fct.default]p4:
  438. // For non-template functions, default arguments can be added in
  439. // later declarations of a function in the same
  440. // scope. Declarations in different scopes have completely
  441. // distinct sets of default arguments. That is, declarations in
  442. // inner scopes do not acquire default arguments from
  443. // declarations in outer scopes, and vice versa. In a given
  444. // function declaration, all parameters subsequent to a
  445. // parameter with a default argument shall have default
  446. // arguments supplied in this or previous declarations. A
  447. // default argument shall not be redefined by a later
  448. // declaration (not even to the same value).
  449. //
  450. // C++ [dcl.fct.default]p6:
  451. // Except for member functions of class templates, the default arguments
  452. // in a member function definition that appears outside of the class
  453. // definition are added to the set of default arguments provided by the
  454. // member function declaration in the class definition.
  455. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  456. ? PrevForDefaultArgs->getNumParams()
  457. : 0;
  458. p < NumParams; ++p) {
  459. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  460. ParmVarDecl *NewParam = New->getParamDecl(p);
  461. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  462. bool NewParamHasDfl = NewParam->hasDefaultArg();
  463. if (OldParamHasDfl && NewParamHasDfl) {
  464. unsigned DiagDefaultParamID =
  465. diag::err_param_default_argument_redefinition;
  466. // MSVC accepts that default parameters be redefined for member functions
  467. // of template class. The new default parameter's value is ignored.
  468. Invalid = true;
  469. if (getLangOpts().MicrosoftExt) {
  470. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  471. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  472. // Merge the old default argument into the new parameter.
  473. NewParam->setHasInheritedDefaultArg();
  474. if (OldParam->hasUninstantiatedDefaultArg())
  475. NewParam->setUninstantiatedDefaultArg(
  476. OldParam->getUninstantiatedDefaultArg());
  477. else
  478. NewParam->setDefaultArg(OldParam->getInit());
  479. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  480. Invalid = false;
  481. }
  482. }
  483. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  484. // hint here. Alternatively, we could walk the type-source information
  485. // for NewParam to find the last source location in the type... but it
  486. // isn't worth the effort right now. This is the kind of test case that
  487. // is hard to get right:
  488. // int f(int);
  489. // void g(int (*fp)(int) = f);
  490. // void g(int (*fp)(int) = &f);
  491. Diag(NewParam->getLocation(), DiagDefaultParamID)
  492. << NewParam->getDefaultArgRange();
  493. // Look for the function declaration where the default argument was
  494. // actually written, which may be a declaration prior to Old.
  495. for (auto Older = PrevForDefaultArgs;
  496. OldParam->hasInheritedDefaultArg(); /**/) {
  497. Older = Older->getPreviousDecl();
  498. OldParam = Older->getParamDecl(p);
  499. }
  500. Diag(OldParam->getLocation(), diag::note_previous_definition)
  501. << OldParam->getDefaultArgRange();
  502. } else if (OldParamHasDfl) {
  503. // Merge the old default argument into the new parameter unless the new
  504. // function is a friend declaration in a template class. In the latter
  505. // case the default arguments will be inherited when the friend
  506. // declaration will be instantiated.
  507. if (New->getFriendObjectKind() == Decl::FOK_None ||
  508. !New->getLexicalDeclContext()->isDependentContext()) {
  509. // It's important to use getInit() here; getDefaultArg()
  510. // strips off any top-level ExprWithCleanups.
  511. NewParam->setHasInheritedDefaultArg();
  512. if (OldParam->hasUnparsedDefaultArg())
  513. NewParam->setUnparsedDefaultArg();
  514. else if (OldParam->hasUninstantiatedDefaultArg())
  515. NewParam->setUninstantiatedDefaultArg(
  516. OldParam->getUninstantiatedDefaultArg());
  517. else
  518. NewParam->setDefaultArg(OldParam->getInit());
  519. }
  520. } else if (NewParamHasDfl) {
  521. if (New->getDescribedFunctionTemplate()) {
  522. // Paragraph 4, quoted above, only applies to non-template functions.
  523. Diag(NewParam->getLocation(),
  524. diag::err_param_default_argument_template_redecl)
  525. << NewParam->getDefaultArgRange();
  526. Diag(PrevForDefaultArgs->getLocation(),
  527. diag::note_template_prev_declaration)
  528. << false;
  529. } else if (New->getTemplateSpecializationKind()
  530. != TSK_ImplicitInstantiation &&
  531. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  532. // C++ [temp.expr.spec]p21:
  533. // Default function arguments shall not be specified in a declaration
  534. // or a definition for one of the following explicit specializations:
  535. // - the explicit specialization of a function template;
  536. // - the explicit specialization of a member function template;
  537. // - the explicit specialization of a member function of a class
  538. // template where the class template specialization to which the
  539. // member function specialization belongs is implicitly
  540. // instantiated.
  541. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  542. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  543. << New->getDeclName()
  544. << NewParam->getDefaultArgRange();
  545. } else if (New->getDeclContext()->isDependentContext()) {
  546. // C++ [dcl.fct.default]p6 (DR217):
  547. // Default arguments for a member function of a class template shall
  548. // be specified on the initial declaration of the member function
  549. // within the class template.
  550. //
  551. // Reading the tea leaves a bit in DR217 and its reference to DR205
  552. // leads me to the conclusion that one cannot add default function
  553. // arguments for an out-of-line definition of a member function of a
  554. // dependent type.
  555. int WhichKind = 2;
  556. if (CXXRecordDecl *Record
  557. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  558. if (Record->getDescribedClassTemplate())
  559. WhichKind = 0;
  560. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  561. WhichKind = 1;
  562. else
  563. WhichKind = 2;
  564. }
  565. Diag(NewParam->getLocation(),
  566. diag::err_param_default_argument_member_template_redecl)
  567. << WhichKind
  568. << NewParam->getDefaultArgRange();
  569. }
  570. }
  571. }
  572. // DR1344: If a default argument is added outside a class definition and that
  573. // default argument makes the function a special member function, the program
  574. // is ill-formed. This can only happen for constructors.
  575. if (isa<CXXConstructorDecl>(New) &&
  576. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  577. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  578. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  579. if (NewSM != OldSM) {
  580. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  581. assert(NewParam->hasDefaultArg());
  582. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  583. << NewParam->getDefaultArgRange() << NewSM;
  584. Diag(Old->getLocation(), diag::note_previous_declaration);
  585. }
  586. }
  587. const FunctionDecl *Def;
  588. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  589. // template has a constexpr specifier then all its declarations shall
  590. // contain the constexpr specifier.
  591. if (New->getConstexprKind() != Old->getConstexprKind()) {
  592. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  593. << New << static_cast<int>(New->getConstexprKind())
  594. << static_cast<int>(Old->getConstexprKind());
  595. Diag(Old->getLocation(), diag::note_previous_declaration);
  596. Invalid = true;
  597. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  598. Old->isDefined(Def) &&
  599. // If a friend function is inlined but does not have 'inline'
  600. // specifier, it is a definition. Do not report attribute conflict
  601. // in this case, redefinition will be diagnosed later.
  602. (New->isInlineSpecified() ||
  603. New->getFriendObjectKind() == Decl::FOK_None)) {
  604. // C++11 [dcl.fcn.spec]p4:
  605. // If the definition of a function appears in a translation unit before its
  606. // first declaration as inline, the program is ill-formed.
  607. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  608. Diag(Def->getLocation(), diag::note_previous_definition);
  609. Invalid = true;
  610. }
  611. // C++17 [temp.deduct.guide]p3:
  612. // Two deduction guide declarations in the same translation unit
  613. // for the same class template shall not have equivalent
  614. // parameter-declaration-clauses.
  615. if (isa<CXXDeductionGuideDecl>(New) &&
  616. !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
  617. Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
  618. Diag(Old->getLocation(), diag::note_previous_declaration);
  619. }
  620. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  621. // argument expression, that declaration shall be a definition and shall be
  622. // the only declaration of the function or function template in the
  623. // translation unit.
  624. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  625. functionDeclHasDefaultArgument(Old)) {
  626. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  627. Diag(Old->getLocation(), diag::note_previous_declaration);
  628. Invalid = true;
  629. }
  630. // C++11 [temp.friend]p4 (DR329):
  631. // When a function is defined in a friend function declaration in a class
  632. // template, the function is instantiated when the function is odr-used.
  633. // The same restrictions on multiple declarations and definitions that
  634. // apply to non-template function declarations and definitions also apply
  635. // to these implicit definitions.
  636. const FunctionDecl *OldDefinition = nullptr;
  637. if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
  638. Old->isDefined(OldDefinition, true))
  639. CheckForFunctionRedefinition(New, OldDefinition);
  640. return Invalid;
  641. }
  642. NamedDecl *
  643. Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
  644. MultiTemplateParamsArg TemplateParamLists) {
  645. assert(D.isDecompositionDeclarator());
  646. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  647. // The syntax only allows a decomposition declarator as a simple-declaration,
  648. // a for-range-declaration, or a condition in Clang, but we parse it in more
  649. // cases than that.
  650. if (!D.mayHaveDecompositionDeclarator()) {
  651. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  652. << Decomp.getSourceRange();
  653. return nullptr;
  654. }
  655. if (!TemplateParamLists.empty()) {
  656. // FIXME: There's no rule against this, but there are also no rules that
  657. // would actually make it usable, so we reject it for now.
  658. Diag(TemplateParamLists.front()->getTemplateLoc(),
  659. diag::err_decomp_decl_template);
  660. return nullptr;
  661. }
  662. Diag(Decomp.getLSquareLoc(),
  663. !getLangOpts().CPlusPlus17
  664. ? diag::ext_decomp_decl
  665. : D.getContext() == DeclaratorContext::Condition
  666. ? diag::ext_decomp_decl_cond
  667. : diag::warn_cxx14_compat_decomp_decl)
  668. << Decomp.getSourceRange();
  669. // The semantic context is always just the current context.
  670. DeclContext *const DC = CurContext;
  671. // C++17 [dcl.dcl]/8:
  672. // The decl-specifier-seq shall contain only the type-specifier auto
  673. // and cv-qualifiers.
  674. // C++2a [dcl.dcl]/8:
  675. // If decl-specifier-seq contains any decl-specifier other than static,
  676. // thread_local, auto, or cv-qualifiers, the program is ill-formed.
  677. auto &DS = D.getDeclSpec();
  678. {
  679. SmallVector<StringRef, 8> BadSpecifiers;
  680. SmallVector<SourceLocation, 8> BadSpecifierLocs;
  681. SmallVector<StringRef, 8> CPlusPlus20Specifiers;
  682. SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
  683. if (auto SCS = DS.getStorageClassSpec()) {
  684. if (SCS == DeclSpec::SCS_static) {
  685. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
  686. CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  687. } else {
  688. BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
  689. BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
  690. }
  691. }
  692. if (auto TSCS = DS.getThreadStorageClassSpec()) {
  693. CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
  694. CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
  695. }
  696. if (DS.hasConstexprSpecifier()) {
  697. BadSpecifiers.push_back(
  698. DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
  699. BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
  700. }
  701. if (DS.isInlineSpecified()) {
  702. BadSpecifiers.push_back("inline");
  703. BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
  704. }
  705. if (!BadSpecifiers.empty()) {
  706. auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
  707. Err << (int)BadSpecifiers.size()
  708. << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
  709. // Don't add FixItHints to remove the specifiers; we do still respect
  710. // them when building the underlying variable.
  711. for (auto Loc : BadSpecifierLocs)
  712. Err << SourceRange(Loc, Loc);
  713. } else if (!CPlusPlus20Specifiers.empty()) {
  714. auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
  715. getLangOpts().CPlusPlus20
  716. ? diag::warn_cxx17_compat_decomp_decl_spec
  717. : diag::ext_decomp_decl_spec);
  718. Warn << (int)CPlusPlus20Specifiers.size()
  719. << llvm::join(CPlusPlus20Specifiers.begin(),
  720. CPlusPlus20Specifiers.end(), " ");
  721. for (auto Loc : CPlusPlus20SpecifierLocs)
  722. Warn << SourceRange(Loc, Loc);
  723. }
  724. // We can't recover from it being declared as a typedef.
  725. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  726. return nullptr;
  727. }
  728. // C++2a [dcl.struct.bind]p1:
  729. // A cv that includes volatile is deprecated
  730. if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
  731. getLangOpts().CPlusPlus20)
  732. Diag(DS.getVolatileSpecLoc(),
  733. diag::warn_deprecated_volatile_structured_binding);
  734. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  735. QualType R = TInfo->getType();
  736. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  737. UPPC_DeclarationType))
  738. D.setInvalidType();
  739. // The syntax only allows a single ref-qualifier prior to the decomposition
  740. // declarator. No other declarator chunks are permitted. Also check the type
  741. // specifier here.
  742. if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
  743. D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
  744. (D.getNumTypeObjects() == 1 &&
  745. D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
  746. Diag(Decomp.getLSquareLoc(),
  747. (D.hasGroupingParens() ||
  748. (D.getNumTypeObjects() &&
  749. D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
  750. ? diag::err_decomp_decl_parens
  751. : diag::err_decomp_decl_type)
  752. << R;
  753. // In most cases, there's no actual problem with an explicitly-specified
  754. // type, but a function type won't work here, and ActOnVariableDeclarator
  755. // shouldn't be called for such a type.
  756. if (R->isFunctionType())
  757. D.setInvalidType();
  758. }
  759. // Build the BindingDecls.
  760. SmallVector<BindingDecl*, 8> Bindings;
  761. // Build the BindingDecls.
  762. for (auto &B : D.getDecompositionDeclarator().bindings()) {
  763. // Check for name conflicts.
  764. DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
  765. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  766. ForVisibleRedeclaration);
  767. LookupName(Previous, S,
  768. /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
  769. // It's not permitted to shadow a template parameter name.
  770. if (Previous.isSingleResult() &&
  771. Previous.getFoundDecl()->isTemplateParameter()) {
  772. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  773. Previous.getFoundDecl());
  774. Previous.clear();
  775. }
  776. auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
  777. // Find the shadowed declaration before filtering for scope.
  778. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  779. ? getShadowedDeclaration(BD, Previous)
  780. : nullptr;
  781. bool ConsiderLinkage = DC->isFunctionOrMethod() &&
  782. DS.getStorageClassSpec() == DeclSpec::SCS_extern;
  783. FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
  784. /*AllowInlineNamespace*/false);
  785. if (!Previous.empty()) {
  786. auto *Old = Previous.getRepresentativeDecl();
  787. Diag(B.NameLoc, diag::err_redefinition) << B.Name;
  788. Diag(Old->getLocation(), diag::note_previous_definition);
  789. } else if (ShadowedDecl && !D.isRedeclaration()) {
  790. CheckShadow(BD, ShadowedDecl, Previous);
  791. }
  792. PushOnScopeChains(BD, S, true);
  793. Bindings.push_back(BD);
  794. ParsingInitForAutoVars.insert(BD);
  795. }
  796. // There are no prior lookup results for the variable itself, because it
  797. // is unnamed.
  798. DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
  799. Decomp.getLSquareLoc());
  800. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  801. ForVisibleRedeclaration);
  802. // Build the variable that holds the non-decomposed object.
  803. bool AddToScope = true;
  804. NamedDecl *New =
  805. ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  806. MultiTemplateParamsArg(), AddToScope, Bindings);
  807. if (AddToScope) {
  808. S->AddDecl(New);
  809. CurContext->addHiddenDecl(New);
  810. }
  811. if (isInOpenMPDeclareTargetContext())
  812. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  813. return New;
  814. }
  815. static bool checkSimpleDecomposition(
  816. Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
  817. QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
  818. llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
  819. if ((int64_t)Bindings.size() != NumElems) {
  820. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  821. << DecompType << (unsigned)Bindings.size()
  822. << (unsigned)NumElems.getLimitedValue(UINT_MAX)
  823. << toString(NumElems, 10) << (NumElems < Bindings.size());
  824. return true;
  825. }
  826. unsigned I = 0;
  827. for (auto *B : Bindings) {
  828. SourceLocation Loc = B->getLocation();
  829. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  830. if (E.isInvalid())
  831. return true;
  832. E = GetInit(Loc, E.get(), I++);
  833. if (E.isInvalid())
  834. return true;
  835. B->setBinding(ElemType, E.get());
  836. }
  837. return false;
  838. }
  839. static bool checkArrayLikeDecomposition(Sema &S,
  840. ArrayRef<BindingDecl *> Bindings,
  841. ValueDecl *Src, QualType DecompType,
  842. const llvm::APSInt &NumElems,
  843. QualType ElemType) {
  844. return checkSimpleDecomposition(
  845. S, Bindings, Src, DecompType, NumElems, ElemType,
  846. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  847. ExprResult E = S.ActOnIntegerConstant(Loc, I);
  848. if (E.isInvalid())
  849. return ExprError();
  850. return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
  851. });
  852. }
  853. static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  854. ValueDecl *Src, QualType DecompType,
  855. const ConstantArrayType *CAT) {
  856. return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
  857. llvm::APSInt(CAT->getSize()),
  858. CAT->getElementType());
  859. }
  860. static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  861. ValueDecl *Src, QualType DecompType,
  862. const VectorType *VT) {
  863. return checkArrayLikeDecomposition(
  864. S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
  865. S.Context.getQualifiedType(VT->getElementType(),
  866. DecompType.getQualifiers()));
  867. }
  868. static bool checkComplexDecomposition(Sema &S,
  869. ArrayRef<BindingDecl *> Bindings,
  870. ValueDecl *Src, QualType DecompType,
  871. const ComplexType *CT) {
  872. return checkSimpleDecomposition(
  873. S, Bindings, Src, DecompType, llvm::APSInt::get(2),
  874. S.Context.getQualifiedType(CT->getElementType(),
  875. DecompType.getQualifiers()),
  876. [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
  877. return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
  878. });
  879. }
  880. static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
  881. TemplateArgumentListInfo &Args,
  882. const TemplateParameterList *Params) {
  883. SmallString<128> SS;
  884. llvm::raw_svector_ostream OS(SS);
  885. bool First = true;
  886. unsigned I = 0;
  887. for (auto &Arg : Args.arguments()) {
  888. if (!First)
  889. OS << ", ";
  890. Arg.getArgument().print(PrintingPolicy, OS,
  891. TemplateParameterList::shouldIncludeTypeForArgument(
  892. PrintingPolicy, Params, I));
  893. First = false;
  894. I++;
  895. }
  896. return std::string(OS.str());
  897. }
  898. static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
  899. SourceLocation Loc, StringRef Trait,
  900. TemplateArgumentListInfo &Args,
  901. unsigned DiagID) {
  902. auto DiagnoseMissing = [&] {
  903. if (DiagID)
  904. S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
  905. Args, /*Params*/ nullptr);
  906. return true;
  907. };
  908. // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
  909. NamespaceDecl *Std = S.getStdNamespace();
  910. if (!Std)
  911. return DiagnoseMissing();
  912. // Look up the trait itself, within namespace std. We can diagnose various
  913. // problems with this lookup even if we've been asked to not diagnose a
  914. // missing specialization, because this can only fail if the user has been
  915. // declaring their own names in namespace std or we don't support the
  916. // standard library implementation in use.
  917. LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
  918. Loc, Sema::LookupOrdinaryName);
  919. if (!S.LookupQualifiedName(Result, Std))
  920. return DiagnoseMissing();
  921. if (Result.isAmbiguous())
  922. return true;
  923. ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
  924. if (!TraitTD) {
  925. Result.suppressDiagnostics();
  926. NamedDecl *Found = *Result.begin();
  927. S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
  928. S.Diag(Found->getLocation(), diag::note_declared_at);
  929. return true;
  930. }
  931. // Build the template-id.
  932. QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
  933. if (TraitTy.isNull())
  934. return true;
  935. if (!S.isCompleteType(Loc, TraitTy)) {
  936. if (DiagID)
  937. S.RequireCompleteType(
  938. Loc, TraitTy, DiagID,
  939. printTemplateArgs(S.Context.getPrintingPolicy(), Args,
  940. TraitTD->getTemplateParameters()));
  941. return true;
  942. }
  943. CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
  944. assert(RD && "specialization of class template is not a class?");
  945. // Look up the member of the trait type.
  946. S.LookupQualifiedName(TraitMemberLookup, RD);
  947. return TraitMemberLookup.isAmbiguous();
  948. }
  949. static TemplateArgumentLoc
  950. getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
  951. uint64_t I) {
  952. TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
  953. return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
  954. }
  955. static TemplateArgumentLoc
  956. getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
  957. return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
  958. }
  959. namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
  960. static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
  961. llvm::APSInt &Size) {
  962. EnterExpressionEvaluationContext ContextRAII(
  963. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  964. DeclarationName Value = S.PP.getIdentifierInfo("value");
  965. LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
  966. // Form template argument list for tuple_size<T>.
  967. TemplateArgumentListInfo Args(Loc, Loc);
  968. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  969. // If there's no tuple_size specialization or the lookup of 'value' is empty,
  970. // it's not tuple-like.
  971. if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
  972. R.empty())
  973. return IsTupleLike::NotTupleLike;
  974. // If we get this far, we've committed to the tuple interpretation, but
  975. // we can still fail if there actually isn't a usable ::value.
  976. struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
  977. LookupResult &R;
  978. TemplateArgumentListInfo &Args;
  979. ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
  980. : R(R), Args(Args) {}
  981. Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
  982. SourceLocation Loc) override {
  983. return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
  984. << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
  985. /*Params*/ nullptr);
  986. }
  987. } Diagnoser(R, Args);
  988. ExprResult E =
  989. S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
  990. if (E.isInvalid())
  991. return IsTupleLike::Error;
  992. E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
  993. if (E.isInvalid())
  994. return IsTupleLike::Error;
  995. return IsTupleLike::TupleLike;
  996. }
  997. /// \return std::tuple_element<I, T>::type.
  998. static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
  999. unsigned I, QualType T) {
  1000. // Form template argument list for tuple_element<I, T>.
  1001. TemplateArgumentListInfo Args(Loc, Loc);
  1002. Args.addArgument(
  1003. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1004. Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
  1005. DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
  1006. LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
  1007. if (lookupStdTypeTraitMember(
  1008. S, R, Loc, "tuple_element", Args,
  1009. diag::err_decomp_decl_std_tuple_element_not_specialized))
  1010. return QualType();
  1011. auto *TD = R.getAsSingle<TypeDecl>();
  1012. if (!TD) {
  1013. R.suppressDiagnostics();
  1014. S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
  1015. << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
  1016. /*Params*/ nullptr);
  1017. if (!R.empty())
  1018. S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
  1019. return QualType();
  1020. }
  1021. return S.Context.getTypeDeclType(TD);
  1022. }
  1023. namespace {
  1024. struct InitializingBinding {
  1025. Sema &S;
  1026. InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
  1027. Sema::CodeSynthesisContext Ctx;
  1028. Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
  1029. Ctx.PointOfInstantiation = BD->getLocation();
  1030. Ctx.Entity = BD;
  1031. S.pushCodeSynthesisContext(Ctx);
  1032. }
  1033. ~InitializingBinding() {
  1034. S.popCodeSynthesisContext();
  1035. }
  1036. };
  1037. }
  1038. static bool checkTupleLikeDecomposition(Sema &S,
  1039. ArrayRef<BindingDecl *> Bindings,
  1040. VarDecl *Src, QualType DecompType,
  1041. const llvm::APSInt &TupleSize) {
  1042. if ((int64_t)Bindings.size() != TupleSize) {
  1043. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1044. << DecompType << (unsigned)Bindings.size()
  1045. << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
  1046. << toString(TupleSize, 10) << (TupleSize < Bindings.size());
  1047. return true;
  1048. }
  1049. if (Bindings.empty())
  1050. return false;
  1051. DeclarationName GetDN = S.PP.getIdentifierInfo("get");
  1052. // [dcl.decomp]p3:
  1053. // The unqualified-id get is looked up in the scope of E by class member
  1054. // access lookup ...
  1055. LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
  1056. bool UseMemberGet = false;
  1057. if (S.isCompleteType(Src->getLocation(), DecompType)) {
  1058. if (auto *RD = DecompType->getAsCXXRecordDecl())
  1059. S.LookupQualifiedName(MemberGet, RD);
  1060. if (MemberGet.isAmbiguous())
  1061. return true;
  1062. // ... and if that finds at least one declaration that is a function
  1063. // template whose first template parameter is a non-type parameter ...
  1064. for (NamedDecl *D : MemberGet) {
  1065. if (FunctionTemplateDecl *FTD =
  1066. dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
  1067. TemplateParameterList *TPL = FTD->getTemplateParameters();
  1068. if (TPL->size() != 0 &&
  1069. isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
  1070. // ... the initializer is e.get<i>().
  1071. UseMemberGet = true;
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. }
  1077. unsigned I = 0;
  1078. for (auto *B : Bindings) {
  1079. InitializingBinding InitContext(S, B);
  1080. SourceLocation Loc = B->getLocation();
  1081. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1082. if (E.isInvalid())
  1083. return true;
  1084. // e is an lvalue if the type of the entity is an lvalue reference and
  1085. // an xvalue otherwise
  1086. if (!Src->getType()->isLValueReferenceType())
  1087. E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
  1088. E.get(), nullptr, VK_XValue,
  1089. FPOptionsOverride());
  1090. TemplateArgumentListInfo Args(Loc, Loc);
  1091. Args.addArgument(
  1092. getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
  1093. if (UseMemberGet) {
  1094. // if [lookup of member get] finds at least one declaration, the
  1095. // initializer is e.get<i-1>().
  1096. E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
  1097. CXXScopeSpec(), SourceLocation(), nullptr,
  1098. MemberGet, &Args, nullptr);
  1099. if (E.isInvalid())
  1100. return true;
  1101. E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
  1102. } else {
  1103. // Otherwise, the initializer is get<i-1>(e), where get is looked up
  1104. // in the associated namespaces.
  1105. Expr *Get = UnresolvedLookupExpr::Create(
  1106. S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
  1107. DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
  1108. UnresolvedSetIterator(), UnresolvedSetIterator());
  1109. Expr *Arg = E.get();
  1110. E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
  1111. }
  1112. if (E.isInvalid())
  1113. return true;
  1114. Expr *Init = E.get();
  1115. // Given the type T designated by std::tuple_element<i - 1, E>::type,
  1116. QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
  1117. if (T.isNull())
  1118. return true;
  1119. // each vi is a variable of type "reference to T" initialized with the
  1120. // initializer, where the reference is an lvalue reference if the
  1121. // initializer is an lvalue and an rvalue reference otherwise
  1122. QualType RefType =
  1123. S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
  1124. if (RefType.isNull())
  1125. return true;
  1126. auto *RefVD = VarDecl::Create(
  1127. S.Context, Src->getDeclContext(), Loc, Loc,
  1128. B->getDeclName().getAsIdentifierInfo(), RefType,
  1129. S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
  1130. RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
  1131. RefVD->setTSCSpec(Src->getTSCSpec());
  1132. RefVD->setImplicit();
  1133. if (Src->isInlineSpecified())
  1134. RefVD->setInlineSpecified();
  1135. RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
  1136. InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
  1137. InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
  1138. InitializationSequence Seq(S, Entity, Kind, Init);
  1139. E = Seq.Perform(S, Entity, Kind, Init);
  1140. if (E.isInvalid())
  1141. return true;
  1142. E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
  1143. if (E.isInvalid())
  1144. return true;
  1145. RefVD->setInit(E.get());
  1146. S.CheckCompleteVariableDeclaration(RefVD);
  1147. E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
  1148. DeclarationNameInfo(B->getDeclName(), Loc),
  1149. RefVD);
  1150. if (E.isInvalid())
  1151. return true;
  1152. B->setBinding(T, E.get());
  1153. I++;
  1154. }
  1155. return false;
  1156. }
  1157. /// Find the base class to decompose in a built-in decomposition of a class type.
  1158. /// This base class search is, unfortunately, not quite like any other that we
  1159. /// perform anywhere else in C++.
  1160. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
  1161. const CXXRecordDecl *RD,
  1162. CXXCastPath &BasePath) {
  1163. auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
  1164. CXXBasePath &Path) {
  1165. return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
  1166. };
  1167. const CXXRecordDecl *ClassWithFields = nullptr;
  1168. AccessSpecifier AS = AS_public;
  1169. if (RD->hasDirectFields())
  1170. // [dcl.decomp]p4:
  1171. // Otherwise, all of E's non-static data members shall be public direct
  1172. // members of E ...
  1173. ClassWithFields = RD;
  1174. else {
  1175. // ... or of ...
  1176. CXXBasePaths Paths;
  1177. Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
  1178. if (!RD->lookupInBases(BaseHasFields, Paths)) {
  1179. // If no classes have fields, just decompose RD itself. (This will work
  1180. // if and only if zero bindings were provided.)
  1181. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
  1182. }
  1183. CXXBasePath *BestPath = nullptr;
  1184. for (auto &P : Paths) {
  1185. if (!BestPath)
  1186. BestPath = &P;
  1187. else if (!S.Context.hasSameType(P.back().Base->getType(),
  1188. BestPath->back().Base->getType())) {
  1189. // ... the same ...
  1190. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1191. << false << RD << BestPath->back().Base->getType()
  1192. << P.back().Base->getType();
  1193. return DeclAccessPair();
  1194. } else if (P.Access < BestPath->Access) {
  1195. BestPath = &P;
  1196. }
  1197. }
  1198. // ... unambiguous ...
  1199. QualType BaseType = BestPath->back().Base->getType();
  1200. if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
  1201. S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
  1202. << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
  1203. return DeclAccessPair();
  1204. }
  1205. // ... [accessible, implied by other rules] base class of E.
  1206. S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
  1207. *BestPath, diag::err_decomp_decl_inaccessible_base);
  1208. AS = BestPath->Access;
  1209. ClassWithFields = BaseType->getAsCXXRecordDecl();
  1210. S.BuildBasePathArray(Paths, BasePath);
  1211. }
  1212. // The above search did not check whether the selected class itself has base
  1213. // classes with fields, so check that now.
  1214. CXXBasePaths Paths;
  1215. if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
  1216. S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
  1217. << (ClassWithFields == RD) << RD << ClassWithFields
  1218. << Paths.front().back().Base->getType();
  1219. return DeclAccessPair();
  1220. }
  1221. return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
  1222. }
  1223. static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
  1224. ValueDecl *Src, QualType DecompType,
  1225. const CXXRecordDecl *OrigRD) {
  1226. if (S.RequireCompleteType(Src->getLocation(), DecompType,
  1227. diag::err_incomplete_type))
  1228. return true;
  1229. CXXCastPath BasePath;
  1230. DeclAccessPair BasePair =
  1231. findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
  1232. const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
  1233. if (!RD)
  1234. return true;
  1235. QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
  1236. DecompType.getQualifiers());
  1237. auto DiagnoseBadNumberOfBindings = [&]() -> bool {
  1238. unsigned NumFields = llvm::count_if(
  1239. RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
  1240. assert(Bindings.size() != NumFields);
  1241. S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
  1242. << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
  1243. << (NumFields < Bindings.size());
  1244. return true;
  1245. };
  1246. // all of E's non-static data members shall be [...] well-formed
  1247. // when named as e.name in the context of the structured binding,
  1248. // E shall not have an anonymous union member, ...
  1249. unsigned I = 0;
  1250. for (auto *FD : RD->fields()) {
  1251. if (FD->isUnnamedBitfield())
  1252. continue;
  1253. // All the non-static data members are required to be nameable, so they
  1254. // must all have names.
  1255. if (!FD->getDeclName()) {
  1256. if (RD->isLambda()) {
  1257. S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
  1258. S.Diag(RD->getLocation(), diag::note_lambda_decl);
  1259. return true;
  1260. }
  1261. if (FD->isAnonymousStructOrUnion()) {
  1262. S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
  1263. << DecompType << FD->getType()->isUnionType();
  1264. S.Diag(FD->getLocation(), diag::note_declared_at);
  1265. return true;
  1266. }
  1267. // FIXME: Are there any other ways we could have an anonymous member?
  1268. }
  1269. // We have a real field to bind.
  1270. if (I >= Bindings.size())
  1271. return DiagnoseBadNumberOfBindings();
  1272. auto *B = Bindings[I++];
  1273. SourceLocation Loc = B->getLocation();
  1274. // The field must be accessible in the context of the structured binding.
  1275. // We already checked that the base class is accessible.
  1276. // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
  1277. // const_cast here.
  1278. S.CheckStructuredBindingMemberAccess(
  1279. Loc, const_cast<CXXRecordDecl *>(OrigRD),
  1280. DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
  1281. BasePair.getAccess(), FD->getAccess())));
  1282. // Initialize the binding to Src.FD.
  1283. ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
  1284. if (E.isInvalid())
  1285. return true;
  1286. E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
  1287. VK_LValue, &BasePath);
  1288. if (E.isInvalid())
  1289. return true;
  1290. E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
  1291. CXXScopeSpec(), FD,
  1292. DeclAccessPair::make(FD, FD->getAccess()),
  1293. DeclarationNameInfo(FD->getDeclName(), Loc));
  1294. if (E.isInvalid())
  1295. return true;
  1296. // If the type of the member is T, the referenced type is cv T, where cv is
  1297. // the cv-qualification of the decomposition expression.
  1298. //
  1299. // FIXME: We resolve a defect here: if the field is mutable, we do not add
  1300. // 'const' to the type of the field.
  1301. Qualifiers Q = DecompType.getQualifiers();
  1302. if (FD->isMutable())
  1303. Q.removeConst();
  1304. B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
  1305. }
  1306. if (I != Bindings.size())
  1307. return DiagnoseBadNumberOfBindings();
  1308. return false;
  1309. }
  1310. void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
  1311. QualType DecompType = DD->getType();
  1312. // If the type of the decomposition is dependent, then so is the type of
  1313. // each binding.
  1314. if (DecompType->isDependentType()) {
  1315. for (auto *B : DD->bindings())
  1316. B->setType(Context.DependentTy);
  1317. return;
  1318. }
  1319. DecompType = DecompType.getNonReferenceType();
  1320. ArrayRef<BindingDecl*> Bindings = DD->bindings();
  1321. // C++1z [dcl.decomp]/2:
  1322. // If E is an array type [...]
  1323. // As an extension, we also support decomposition of built-in complex and
  1324. // vector types.
  1325. if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
  1326. if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
  1327. DD->setInvalidDecl();
  1328. return;
  1329. }
  1330. if (auto *VT = DecompType->getAs<VectorType>()) {
  1331. if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
  1332. DD->setInvalidDecl();
  1333. return;
  1334. }
  1335. if (auto *CT = DecompType->getAs<ComplexType>()) {
  1336. if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
  1337. DD->setInvalidDecl();
  1338. return;
  1339. }
  1340. // C++1z [dcl.decomp]/3:
  1341. // if the expression std::tuple_size<E>::value is a well-formed integral
  1342. // constant expression, [...]
  1343. llvm::APSInt TupleSize(32);
  1344. switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
  1345. case IsTupleLike::Error:
  1346. DD->setInvalidDecl();
  1347. return;
  1348. case IsTupleLike::TupleLike:
  1349. if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
  1350. DD->setInvalidDecl();
  1351. return;
  1352. case IsTupleLike::NotTupleLike:
  1353. break;
  1354. }
  1355. // C++1z [dcl.dcl]/8:
  1356. // [E shall be of array or non-union class type]
  1357. CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
  1358. if (!RD || RD->isUnion()) {
  1359. Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
  1360. << DD << !RD << DecompType;
  1361. DD->setInvalidDecl();
  1362. return;
  1363. }
  1364. // C++1z [dcl.decomp]/4:
  1365. // all of E's non-static data members shall be [...] direct members of
  1366. // E or of the same unambiguous public base class of E, ...
  1367. if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
  1368. DD->setInvalidDecl();
  1369. }
  1370. /// Merge the exception specifications of two variable declarations.
  1371. ///
  1372. /// This is called when there's a redeclaration of a VarDecl. The function
  1373. /// checks if the redeclaration might have an exception specification and
  1374. /// validates compatibility and merges the specs if necessary.
  1375. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  1376. // Shortcut if exceptions are disabled.
  1377. if (!getLangOpts().CXXExceptions)
  1378. return;
  1379. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  1380. "Should only be called if types are otherwise the same.");
  1381. QualType NewType = New->getType();
  1382. QualType OldType = Old->getType();
  1383. // We're only interested in pointers and references to functions, as well
  1384. // as pointers to member functions.
  1385. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  1386. NewType = R->getPointeeType();
  1387. OldType = OldType->castAs<ReferenceType>()->getPointeeType();
  1388. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  1389. NewType = P->getPointeeType();
  1390. OldType = OldType->castAs<PointerType>()->getPointeeType();
  1391. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  1392. NewType = M->getPointeeType();
  1393. OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
  1394. }
  1395. if (!NewType->isFunctionProtoType())
  1396. return;
  1397. // There's lots of special cases for functions. For function pointers, system
  1398. // libraries are hopefully not as broken so that we don't need these
  1399. // workarounds.
  1400. if (CheckEquivalentExceptionSpec(
  1401. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  1402. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  1403. New->setInvalidDecl();
  1404. }
  1405. }
  1406. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  1407. /// function declaration are well-formed according to C++
  1408. /// [dcl.fct.default].
  1409. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  1410. unsigned NumParams = FD->getNumParams();
  1411. unsigned ParamIdx = 0;
  1412. // This checking doesn't make sense for explicit specializations; their
  1413. // default arguments are determined by the declaration we're specializing,
  1414. // not by FD.
  1415. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  1416. return;
  1417. if (auto *FTD = FD->getDescribedFunctionTemplate())
  1418. if (FTD->isMemberSpecialization())
  1419. return;
  1420. // Find first parameter with a default argument
  1421. for (; ParamIdx < NumParams; ++ParamIdx) {
  1422. ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
  1423. if (Param->hasDefaultArg())
  1424. break;
  1425. }
  1426. // C++20 [dcl.fct.default]p4:
  1427. // In a given function declaration, each parameter subsequent to a parameter
  1428. // with a default argument shall have a default argument supplied in this or
  1429. // a previous declaration, unless the parameter was expanded from a
  1430. // parameter pack, or shall be a function parameter pack.
  1431. for (; ParamIdx < NumParams; ++ParamIdx) {
  1432. ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
  1433. if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
  1434. !(CurrentInstantiationScope &&
  1435. CurrentInstantiationScope->isLocalPackExpansion(Param))) {
  1436. if (Param->isInvalidDecl())
  1437. /* We already complained about this parameter. */;
  1438. else if (Param->getIdentifier())
  1439. Diag(Param->getLocation(),
  1440. diag::err_param_default_argument_missing_name)
  1441. << Param->getIdentifier();
  1442. else
  1443. Diag(Param->getLocation(),
  1444. diag::err_param_default_argument_missing);
  1445. }
  1446. }
  1447. }
  1448. /// Check that the given type is a literal type. Issue a diagnostic if not,
  1449. /// if Kind is Diagnose.
  1450. /// \return \c true if a problem has been found (and optionally diagnosed).
  1451. template <typename... Ts>
  1452. static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
  1453. SourceLocation Loc, QualType T, unsigned DiagID,
  1454. Ts &&...DiagArgs) {
  1455. if (T->isDependentType())
  1456. return false;
  1457. switch (Kind) {
  1458. case Sema::CheckConstexprKind::Diagnose:
  1459. return SemaRef.RequireLiteralType(Loc, T, DiagID,
  1460. std::forward<Ts>(DiagArgs)...);
  1461. case Sema::CheckConstexprKind::CheckValid:
  1462. return !T->isLiteralType(SemaRef.Context);
  1463. }
  1464. llvm_unreachable("unknown CheckConstexprKind");
  1465. }
  1466. /// Determine whether a destructor cannot be constexpr due to
  1467. static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
  1468. const CXXDestructorDecl *DD,
  1469. Sema::CheckConstexprKind Kind) {
  1470. auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
  1471. const CXXRecordDecl *RD =
  1472. T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1473. if (!RD || RD->hasConstexprDestructor())
  1474. return true;
  1475. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1476. SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
  1477. << static_cast<int>(DD->getConstexprKind()) << !FD
  1478. << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1479. SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
  1480. << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
  1481. }
  1482. return false;
  1483. };
  1484. const CXXRecordDecl *RD = DD->getParent();
  1485. for (const CXXBaseSpecifier &B : RD->bases())
  1486. if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
  1487. return false;
  1488. for (const FieldDecl *FD : RD->fields())
  1489. if (!Check(FD->getLocation(), FD->getType(), FD))
  1490. return false;
  1491. return true;
  1492. }
  1493. /// Check whether a function's parameter types are all literal types. If so,
  1494. /// return true. If not, produce a suitable diagnostic and return false.
  1495. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  1496. const FunctionDecl *FD,
  1497. Sema::CheckConstexprKind Kind) {
  1498. unsigned ArgIndex = 0;
  1499. const auto *FT = FD->getType()->castAs<FunctionProtoType>();
  1500. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  1501. e = FT->param_type_end();
  1502. i != e; ++i, ++ArgIndex) {
  1503. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  1504. SourceLocation ParamLoc = PD->getLocation();
  1505. if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
  1506. diag::err_constexpr_non_literal_param, ArgIndex + 1,
  1507. PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
  1508. FD->isConsteval()))
  1509. return false;
  1510. }
  1511. return true;
  1512. }
  1513. /// Check whether a function's return type is a literal type. If so, return
  1514. /// true. If not, produce a suitable diagnostic and return false.
  1515. static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
  1516. Sema::CheckConstexprKind Kind) {
  1517. if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
  1518. diag::err_constexpr_non_literal_return,
  1519. FD->isConsteval()))
  1520. return false;
  1521. return true;
  1522. }
  1523. /// Get diagnostic %select index for tag kind for
  1524. /// record diagnostic message.
  1525. /// WARNING: Indexes apply to particular diagnostics only!
  1526. ///
  1527. /// \returns diagnostic %select index.
  1528. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  1529. switch (Tag) {
  1530. case TTK_Struct: return 0;
  1531. case TTK_Interface: return 1;
  1532. case TTK_Class: return 2;
  1533. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  1534. }
  1535. }
  1536. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1537. Stmt *Body,
  1538. Sema::CheckConstexprKind Kind);
  1539. // Check whether a function declaration satisfies the requirements of a
  1540. // constexpr function definition or a constexpr constructor definition. If so,
  1541. // return true. If not, produce appropriate diagnostics (unless asked not to by
  1542. // Kind) and return false.
  1543. //
  1544. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  1545. bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
  1546. CheckConstexprKind Kind) {
  1547. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  1548. if (MD && MD->isInstance()) {
  1549. // C++11 [dcl.constexpr]p4:
  1550. // The definition of a constexpr constructor shall satisfy the following
  1551. // constraints:
  1552. // - the class shall not have any virtual base classes;
  1553. //
  1554. // FIXME: This only applies to constructors and destructors, not arbitrary
  1555. // member functions.
  1556. const CXXRecordDecl *RD = MD->getParent();
  1557. if (RD->getNumVBases()) {
  1558. if (Kind == CheckConstexprKind::CheckValid)
  1559. return false;
  1560. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  1561. << isa<CXXConstructorDecl>(NewFD)
  1562. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  1563. for (const auto &I : RD->vbases())
  1564. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  1565. << I.getSourceRange();
  1566. return false;
  1567. }
  1568. }
  1569. if (!isa<CXXConstructorDecl>(NewFD)) {
  1570. // C++11 [dcl.constexpr]p3:
  1571. // The definition of a constexpr function shall satisfy the following
  1572. // constraints:
  1573. // - it shall not be virtual; (removed in C++20)
  1574. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  1575. if (Method && Method->isVirtual()) {
  1576. if (getLangOpts().CPlusPlus20) {
  1577. if (Kind == CheckConstexprKind::Diagnose)
  1578. Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
  1579. } else {
  1580. if (Kind == CheckConstexprKind::CheckValid)
  1581. return false;
  1582. Method = Method->getCanonicalDecl();
  1583. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  1584. // If it's not obvious why this function is virtual, find an overridden
  1585. // function which uses the 'virtual' keyword.
  1586. const CXXMethodDecl *WrittenVirtual = Method;
  1587. while (!WrittenVirtual->isVirtualAsWritten())
  1588. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  1589. if (WrittenVirtual != Method)
  1590. Diag(WrittenVirtual->getLocation(),
  1591. diag::note_overridden_virtual_function);
  1592. return false;
  1593. }
  1594. }
  1595. // - its return type shall be a literal type;
  1596. if (!CheckConstexprReturnType(*this, NewFD, Kind))
  1597. return false;
  1598. }
  1599. if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
  1600. // A destructor can be constexpr only if the defaulted destructor could be;
  1601. // we don't need to check the members and bases if we already know they all
  1602. // have constexpr destructors.
  1603. if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
  1604. if (Kind == CheckConstexprKind::CheckValid)
  1605. return false;
  1606. if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
  1607. return false;
  1608. }
  1609. }
  1610. // - each of its parameter types shall be a literal type;
  1611. if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
  1612. return false;
  1613. Stmt *Body = NewFD->getBody();
  1614. assert(Body &&
  1615. "CheckConstexprFunctionDefinition called on function with no body");
  1616. return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
  1617. }
  1618. /// Check the given declaration statement is legal within a constexpr function
  1619. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  1620. ///
  1621. /// \return true if the body is OK (maybe only as an extension), false if we
  1622. /// have diagnosed a problem.
  1623. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  1624. DeclStmt *DS, SourceLocation &Cxx1yLoc,
  1625. Sema::CheckConstexprKind Kind) {
  1626. // C++11 [dcl.constexpr]p3 and p4:
  1627. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  1628. // contain only
  1629. for (const auto *DclIt : DS->decls()) {
  1630. switch (DclIt->getKind()) {
  1631. case Decl::StaticAssert:
  1632. case Decl::Using:
  1633. case Decl::UsingShadow:
  1634. case Decl::UsingDirective:
  1635. case Decl::UnresolvedUsingTypename:
  1636. case Decl::UnresolvedUsingValue:
  1637. case Decl::UsingEnum:
  1638. // - static_assert-declarations
  1639. // - using-declarations,
  1640. // - using-directives,
  1641. // - using-enum-declaration
  1642. continue;
  1643. case Decl::Typedef:
  1644. case Decl::TypeAlias: {
  1645. // - typedef declarations and alias-declarations that do not define
  1646. // classes or enumerations,
  1647. const auto *TN = cast<TypedefNameDecl>(DclIt);
  1648. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  1649. // Don't allow variably-modified types in constexpr functions.
  1650. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1651. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  1652. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  1653. << TL.getSourceRange() << TL.getType()
  1654. << isa<CXXConstructorDecl>(Dcl);
  1655. }
  1656. return false;
  1657. }
  1658. continue;
  1659. }
  1660. case Decl::Enum:
  1661. case Decl::CXXRecord:
  1662. // C++1y allows types to be defined, not just declared.
  1663. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
  1664. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1665. SemaRef.Diag(DS->getBeginLoc(),
  1666. SemaRef.getLangOpts().CPlusPlus14
  1667. ? diag::warn_cxx11_compat_constexpr_type_definition
  1668. : diag::ext_constexpr_type_definition)
  1669. << isa<CXXConstructorDecl>(Dcl);
  1670. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1671. return false;
  1672. }
  1673. }
  1674. continue;
  1675. case Decl::EnumConstant:
  1676. case Decl::IndirectField:
  1677. case Decl::ParmVar:
  1678. // These can only appear with other declarations which are banned in
  1679. // C++11 and permitted in C++1y, so ignore them.
  1680. continue;
  1681. case Decl::Var:
  1682. case Decl::Decomposition: {
  1683. // C++1y [dcl.constexpr]p3 allows anything except:
  1684. // a definition of a variable of non-literal type or of static or
  1685. // thread storage duration or [before C++2a] for which no
  1686. // initialization is performed.
  1687. const auto *VD = cast<VarDecl>(DclIt);
  1688. if (VD->isThisDeclarationADefinition()) {
  1689. if (VD->isStaticLocal()) {
  1690. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1691. SemaRef.Diag(VD->getLocation(),
  1692. diag::err_constexpr_local_var_static)
  1693. << isa<CXXConstructorDecl>(Dcl)
  1694. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  1695. }
  1696. return false;
  1697. }
  1698. if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
  1699. diag::err_constexpr_local_var_non_literal_type,
  1700. isa<CXXConstructorDecl>(Dcl)))
  1701. return false;
  1702. if (!VD->getType()->isDependentType() &&
  1703. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  1704. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1705. SemaRef.Diag(
  1706. VD->getLocation(),
  1707. SemaRef.getLangOpts().CPlusPlus20
  1708. ? diag::warn_cxx17_compat_constexpr_local_var_no_init
  1709. : diag::ext_constexpr_local_var_no_init)
  1710. << isa<CXXConstructorDecl>(Dcl);
  1711. } else if (!SemaRef.getLangOpts().CPlusPlus20) {
  1712. return false;
  1713. }
  1714. continue;
  1715. }
  1716. }
  1717. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1718. SemaRef.Diag(VD->getLocation(),
  1719. SemaRef.getLangOpts().CPlusPlus14
  1720. ? diag::warn_cxx11_compat_constexpr_local_var
  1721. : diag::ext_constexpr_local_var)
  1722. << isa<CXXConstructorDecl>(Dcl);
  1723. } else if (!SemaRef.getLangOpts().CPlusPlus14) {
  1724. return false;
  1725. }
  1726. continue;
  1727. }
  1728. case Decl::NamespaceAlias:
  1729. case Decl::Function:
  1730. // These are disallowed in C++11 and permitted in C++1y. Allow them
  1731. // everywhere as an extension.
  1732. if (!Cxx1yLoc.isValid())
  1733. Cxx1yLoc = DS->getBeginLoc();
  1734. continue;
  1735. default:
  1736. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1737. SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1738. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1739. }
  1740. return false;
  1741. }
  1742. }
  1743. return true;
  1744. }
  1745. /// Check that the given field is initialized within a constexpr constructor.
  1746. ///
  1747. /// \param Dcl The constexpr constructor being checked.
  1748. /// \param Field The field being checked. This may be a member of an anonymous
  1749. /// struct or union nested within the class being checked.
  1750. /// \param Inits All declarations, including anonymous struct/union members and
  1751. /// indirect members, for which any initialization was provided.
  1752. /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
  1753. /// multiple notes for different members to the same error.
  1754. /// \param Kind Whether we're diagnosing a constructor as written or determining
  1755. /// whether the formal requirements are satisfied.
  1756. /// \return \c false if we're checking for validity and the constructor does
  1757. /// not satisfy the requirements on a constexpr constructor.
  1758. static bool CheckConstexprCtorInitializer(Sema &SemaRef,
  1759. const FunctionDecl *Dcl,
  1760. FieldDecl *Field,
  1761. llvm::SmallSet<Decl*, 16> &Inits,
  1762. bool &Diagnosed,
  1763. Sema::CheckConstexprKind Kind) {
  1764. // In C++20 onwards, there's nothing to check for validity.
  1765. if (Kind == Sema::CheckConstexprKind::CheckValid &&
  1766. SemaRef.getLangOpts().CPlusPlus20)
  1767. return true;
  1768. if (Field->isInvalidDecl())
  1769. return true;
  1770. if (Field->isUnnamedBitfield())
  1771. return true;
  1772. // Anonymous unions with no variant members and empty anonymous structs do not
  1773. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  1774. // indirect fields don't need initializing.
  1775. if (Field->isAnonymousStructOrUnion() &&
  1776. (Field->getType()->isUnionType()
  1777. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  1778. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  1779. return true;
  1780. if (!Inits.count(Field)) {
  1781. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1782. if (!Diagnosed) {
  1783. SemaRef.Diag(Dcl->getLocation(),
  1784. SemaRef.getLangOpts().CPlusPlus20
  1785. ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
  1786. : diag::ext_constexpr_ctor_missing_init);
  1787. Diagnosed = true;
  1788. }
  1789. SemaRef.Diag(Field->getLocation(),
  1790. diag::note_constexpr_ctor_missing_init);
  1791. } else if (!SemaRef.getLangOpts().CPlusPlus20) {
  1792. return false;
  1793. }
  1794. } else if (Field->isAnonymousStructOrUnion()) {
  1795. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  1796. for (auto *I : RD->fields())
  1797. // If an anonymous union contains an anonymous struct of which any member
  1798. // is initialized, all members must be initialized.
  1799. if (!RD->isUnion() || Inits.count(I))
  1800. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  1801. Kind))
  1802. return false;
  1803. }
  1804. return true;
  1805. }
  1806. /// Check the provided statement is allowed in a constexpr function
  1807. /// definition.
  1808. static bool
  1809. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  1810. SmallVectorImpl<SourceLocation> &ReturnStmts,
  1811. SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
  1812. Sema::CheckConstexprKind Kind) {
  1813. // - its function-body shall be [...] a compound-statement that contains only
  1814. switch (S->getStmtClass()) {
  1815. case Stmt::NullStmtClass:
  1816. // - null statements,
  1817. return true;
  1818. case Stmt::DeclStmtClass:
  1819. // - static_assert-declarations
  1820. // - using-declarations,
  1821. // - using-directives,
  1822. // - typedef declarations and alias-declarations that do not define
  1823. // classes or enumerations,
  1824. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
  1825. return false;
  1826. return true;
  1827. case Stmt::ReturnStmtClass:
  1828. // - and exactly one return statement;
  1829. if (isa<CXXConstructorDecl>(Dcl)) {
  1830. // C++1y allows return statements in constexpr constructors.
  1831. if (!Cxx1yLoc.isValid())
  1832. Cxx1yLoc = S->getBeginLoc();
  1833. return true;
  1834. }
  1835. ReturnStmts.push_back(S->getBeginLoc());
  1836. return true;
  1837. case Stmt::AttributedStmtClass:
  1838. // Attributes on a statement don't affect its formal kind and hence don't
  1839. // affect its validity in a constexpr function.
  1840. return CheckConstexprFunctionStmt(SemaRef, Dcl,
  1841. cast<AttributedStmt>(S)->getSubStmt(),
  1842. ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind);
  1843. case Stmt::CompoundStmtClass: {
  1844. // C++1y allows compound-statements.
  1845. if (!Cxx1yLoc.isValid())
  1846. Cxx1yLoc = S->getBeginLoc();
  1847. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  1848. for (auto *BodyIt : CompStmt->body()) {
  1849. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  1850. Cxx1yLoc, Cxx2aLoc, Kind))
  1851. return false;
  1852. }
  1853. return true;
  1854. }
  1855. case Stmt::IfStmtClass: {
  1856. // C++1y allows if-statements.
  1857. if (!Cxx1yLoc.isValid())
  1858. Cxx1yLoc = S->getBeginLoc();
  1859. IfStmt *If = cast<IfStmt>(S);
  1860. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  1861. Cxx1yLoc, Cxx2aLoc, Kind))
  1862. return false;
  1863. if (If->getElse() &&
  1864. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  1865. Cxx1yLoc, Cxx2aLoc, Kind))
  1866. return false;
  1867. return true;
  1868. }
  1869. case Stmt::WhileStmtClass:
  1870. case Stmt::DoStmtClass:
  1871. case Stmt::ForStmtClass:
  1872. case Stmt::CXXForRangeStmtClass:
  1873. case Stmt::ContinueStmtClass:
  1874. // C++1y allows all of these. We don't allow them as extensions in C++11,
  1875. // because they don't make sense without variable mutation.
  1876. if (!SemaRef.getLangOpts().CPlusPlus14)
  1877. break;
  1878. if (!Cxx1yLoc.isValid())
  1879. Cxx1yLoc = S->getBeginLoc();
  1880. for (Stmt *SubStmt : S->children())
  1881. if (SubStmt &&
  1882. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1883. Cxx1yLoc, Cxx2aLoc, Kind))
  1884. return false;
  1885. return true;
  1886. case Stmt::SwitchStmtClass:
  1887. case Stmt::CaseStmtClass:
  1888. case Stmt::DefaultStmtClass:
  1889. case Stmt::BreakStmtClass:
  1890. // C++1y allows switch-statements, and since they don't need variable
  1891. // mutation, we can reasonably allow them in C++11 as an extension.
  1892. if (!Cxx1yLoc.isValid())
  1893. Cxx1yLoc = S->getBeginLoc();
  1894. for (Stmt *SubStmt : S->children())
  1895. if (SubStmt &&
  1896. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1897. Cxx1yLoc, Cxx2aLoc, Kind))
  1898. return false;
  1899. return true;
  1900. case Stmt::GCCAsmStmtClass:
  1901. case Stmt::MSAsmStmtClass:
  1902. // C++2a allows inline assembly statements.
  1903. case Stmt::CXXTryStmtClass:
  1904. if (Cxx2aLoc.isInvalid())
  1905. Cxx2aLoc = S->getBeginLoc();
  1906. for (Stmt *SubStmt : S->children()) {
  1907. if (SubStmt &&
  1908. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1909. Cxx1yLoc, Cxx2aLoc, Kind))
  1910. return false;
  1911. }
  1912. return true;
  1913. case Stmt::CXXCatchStmtClass:
  1914. // Do not bother checking the language mode (already covered by the
  1915. // try block check).
  1916. if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
  1917. cast<CXXCatchStmt>(S)->getHandlerBlock(),
  1918. ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
  1919. return false;
  1920. return true;
  1921. default:
  1922. if (!isa<Expr>(S))
  1923. break;
  1924. // C++1y allows expression-statements.
  1925. if (!Cxx1yLoc.isValid())
  1926. Cxx1yLoc = S->getBeginLoc();
  1927. return true;
  1928. }
  1929. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  1930. SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
  1931. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  1932. }
  1933. return false;
  1934. }
  1935. /// Check the body for the given constexpr function declaration only contains
  1936. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1937. ///
  1938. /// \return true if the body is OK, false if we have found or diagnosed a
  1939. /// problem.
  1940. static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
  1941. Stmt *Body,
  1942. Sema::CheckConstexprKind Kind) {
  1943. SmallVector<SourceLocation, 4> ReturnStmts;
  1944. if (isa<CXXTryStmt>(Body)) {
  1945. // C++11 [dcl.constexpr]p3:
  1946. // The definition of a constexpr function shall satisfy the following
  1947. // constraints: [...]
  1948. // - its function-body shall be = delete, = default, or a
  1949. // compound-statement
  1950. //
  1951. // C++11 [dcl.constexpr]p4:
  1952. // In the definition of a constexpr constructor, [...]
  1953. // - its function-body shall not be a function-try-block;
  1954. //
  1955. // This restriction is lifted in C++2a, as long as inner statements also
  1956. // apply the general constexpr rules.
  1957. switch (Kind) {
  1958. case Sema::CheckConstexprKind::CheckValid:
  1959. if (!SemaRef.getLangOpts().CPlusPlus20)
  1960. return false;
  1961. break;
  1962. case Sema::CheckConstexprKind::Diagnose:
  1963. SemaRef.Diag(Body->getBeginLoc(),
  1964. !SemaRef.getLangOpts().CPlusPlus20
  1965. ? diag::ext_constexpr_function_try_block_cxx20
  1966. : diag::warn_cxx17_compat_constexpr_function_try_block)
  1967. << isa<CXXConstructorDecl>(Dcl);
  1968. break;
  1969. }
  1970. }
  1971. // - its function-body shall be [...] a compound-statement that contains only
  1972. // [... list of cases ...]
  1973. //
  1974. // Note that walking the children here is enough to properly check for
  1975. // CompoundStmt and CXXTryStmt body.
  1976. SourceLocation Cxx1yLoc, Cxx2aLoc;
  1977. for (Stmt *SubStmt : Body->children()) {
  1978. if (SubStmt &&
  1979. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1980. Cxx1yLoc, Cxx2aLoc, Kind))
  1981. return false;
  1982. }
  1983. if (Kind == Sema::CheckConstexprKind::CheckValid) {
  1984. // If this is only valid as an extension, report that we don't satisfy the
  1985. // constraints of the current language.
  1986. if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
  1987. (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
  1988. return false;
  1989. } else if (Cxx2aLoc.isValid()) {
  1990. SemaRef.Diag(Cxx2aLoc,
  1991. SemaRef.getLangOpts().CPlusPlus20
  1992. ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
  1993. : diag::ext_constexpr_body_invalid_stmt_cxx20)
  1994. << isa<CXXConstructorDecl>(Dcl);
  1995. } else if (Cxx1yLoc.isValid()) {
  1996. SemaRef.Diag(Cxx1yLoc,
  1997. SemaRef.getLangOpts().CPlusPlus14
  1998. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1999. : diag::ext_constexpr_body_invalid_stmt)
  2000. << isa<CXXConstructorDecl>(Dcl);
  2001. }
  2002. if (const CXXConstructorDecl *Constructor
  2003. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  2004. const CXXRecordDecl *RD = Constructor->getParent();
  2005. // DR1359:
  2006. // - every non-variant non-static data member and base class sub-object
  2007. // shall be initialized;
  2008. // DR1460:
  2009. // - if the class is a union having variant members, exactly one of them
  2010. // shall be initialized;
  2011. if (RD->isUnion()) {
  2012. if (Constructor->getNumCtorInitializers() == 0 &&
  2013. RD->hasVariantMembers()) {
  2014. if (Kind == Sema::CheckConstexprKind::Diagnose) {
  2015. SemaRef.Diag(
  2016. Dcl->getLocation(),
  2017. SemaRef.getLangOpts().CPlusPlus20
  2018. ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
  2019. : diag::ext_constexpr_union_ctor_no_init);
  2020. } else if (!SemaRef.getLangOpts().CPlusPlus20) {
  2021. return false;
  2022. }
  2023. }
  2024. } else if (!Constructor->isDependentContext() &&
  2025. !Constructor->isDelegatingConstructor()) {
  2026. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  2027. // Skip detailed checking if we have enough initializers, and we would
  2028. // allow at most one initializer per member.
  2029. bool AnyAnonStructUnionMembers = false;
  2030. unsigned Fields = 0;
  2031. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  2032. E = RD->field_end(); I != E; ++I, ++Fields) {
  2033. if (I->isAnonymousStructOrUnion()) {
  2034. AnyAnonStructUnionMembers = true;
  2035. break;
  2036. }
  2037. }
  2038. // DR1460:
  2039. // - if the class is a union-like class, but is not a union, for each of
  2040. // its anonymous union members having variant members, exactly one of
  2041. // them shall be initialized;
  2042. if (AnyAnonStructUnionMembers ||
  2043. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  2044. // Check initialization of non-static data members. Base classes are
  2045. // always initialized so do not need to be checked. Dependent bases
  2046. // might not have initializers in the member initializer list.
  2047. llvm::SmallSet<Decl*, 16> Inits;
  2048. for (const auto *I: Constructor->inits()) {
  2049. if (FieldDecl *FD = I->getMember())
  2050. Inits.insert(FD);
  2051. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  2052. Inits.insert(ID->chain_begin(), ID->chain_end());
  2053. }
  2054. bool Diagnosed = false;
  2055. for (auto *I : RD->fields())
  2056. if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
  2057. Kind))
  2058. return false;
  2059. }
  2060. }
  2061. } else {
  2062. if (ReturnStmts.empty()) {
  2063. // C++1y doesn't require constexpr functions to contain a 'return'
  2064. // statement. We still do, unless the return type might be void, because
  2065. // otherwise if there's no return statement, the function cannot
  2066. // be used in a core constant expression.
  2067. bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
  2068. (Dcl->getReturnType()->isVoidType() ||
  2069. Dcl->getReturnType()->isDependentType());
  2070. switch (Kind) {
  2071. case Sema::CheckConstexprKind::Diagnose:
  2072. SemaRef.Diag(Dcl->getLocation(),
  2073. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  2074. : diag::err_constexpr_body_no_return)
  2075. << Dcl->isConsteval();
  2076. if (!OK)
  2077. return false;
  2078. break;
  2079. case Sema::CheckConstexprKind::CheckValid:
  2080. // The formal requirements don't include this rule in C++14, even
  2081. // though the "must be able to produce a constant expression" rules
  2082. // still imply it in some cases.
  2083. if (!SemaRef.getLangOpts().CPlusPlus14)
  2084. return false;
  2085. break;
  2086. }
  2087. } else if (ReturnStmts.size() > 1) {
  2088. switch (Kind) {
  2089. case Sema::CheckConstexprKind::Diagnose:
  2090. SemaRef.Diag(
  2091. ReturnStmts.back(),
  2092. SemaRef.getLangOpts().CPlusPlus14
  2093. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  2094. : diag::ext_constexpr_body_multiple_return);
  2095. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  2096. SemaRef.Diag(ReturnStmts[I],
  2097. diag::note_constexpr_body_previous_return);
  2098. break;
  2099. case Sema::CheckConstexprKind::CheckValid:
  2100. if (!SemaRef.getLangOpts().CPlusPlus14)
  2101. return false;
  2102. break;
  2103. }
  2104. }
  2105. }
  2106. // C++11 [dcl.constexpr]p5:
  2107. // if no function argument values exist such that the function invocation
  2108. // substitution would produce a constant expression, the program is
  2109. // ill-formed; no diagnostic required.
  2110. // C++11 [dcl.constexpr]p3:
  2111. // - every constructor call and implicit conversion used in initializing the
  2112. // return value shall be one of those allowed in a constant expression.
  2113. // C++11 [dcl.constexpr]p4:
  2114. // - every constructor involved in initializing non-static data members and
  2115. // base class sub-objects shall be a constexpr constructor.
  2116. //
  2117. // Note that this rule is distinct from the "requirements for a constexpr
  2118. // function", so is not checked in CheckValid mode.
  2119. SmallVector<PartialDiagnosticAt, 8> Diags;
  2120. if (Kind == Sema::CheckConstexprKind::Diagnose &&
  2121. !Expr::isPotentialConstantExpr(Dcl, Diags)) {
  2122. SemaRef.Diag(Dcl->getLocation(),
  2123. diag::ext_constexpr_function_never_constant_expr)
  2124. << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
  2125. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  2126. SemaRef.Diag(Diags[I].first, Diags[I].second);
  2127. // Don't return false here: we allow this for compatibility in
  2128. // system headers.
  2129. }
  2130. return true;
  2131. }
  2132. /// Get the class that is directly named by the current context. This is the
  2133. /// class for which an unqualified-id in this scope could name a constructor
  2134. /// or destructor.
  2135. ///
  2136. /// If the scope specifier denotes a class, this will be that class.
  2137. /// If the scope specifier is empty, this will be the class whose
  2138. /// member-specification we are currently within. Otherwise, there
  2139. /// is no such class.
  2140. CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
  2141. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2142. if (SS && SS->isInvalid())
  2143. return nullptr;
  2144. if (SS && SS->isNotEmpty()) {
  2145. DeclContext *DC = computeDeclContext(*SS, true);
  2146. return dyn_cast_or_null<CXXRecordDecl>(DC);
  2147. }
  2148. return dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2149. }
  2150. /// isCurrentClassName - Determine whether the identifier II is the
  2151. /// name of the class type currently being defined. In the case of
  2152. /// nested classes, this will only return true if II is the name of
  2153. /// the innermost class.
  2154. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
  2155. const CXXScopeSpec *SS) {
  2156. CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
  2157. return CurDecl && &II == CurDecl->getIdentifier();
  2158. }
  2159. /// Determine whether the identifier II is a typo for the name of
  2160. /// the class type currently being defined. If so, update it to the identifier
  2161. /// that should have been used.
  2162. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  2163. assert(getLangOpts().CPlusPlus && "No class names in C!");
  2164. if (!getLangOpts().SpellChecking)
  2165. return false;
  2166. CXXRecordDecl *CurDecl;
  2167. if (SS && SS->isSet() && !SS->isInvalid()) {
  2168. DeclContext *DC = computeDeclContext(*SS, true);
  2169. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  2170. } else
  2171. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  2172. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  2173. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  2174. < II->getLength()) {
  2175. II = CurDecl->getIdentifier();
  2176. return true;
  2177. }
  2178. return false;
  2179. }
  2180. /// Determine whether the given class is a base class of the given
  2181. /// class, including looking at dependent bases.
  2182. static bool findCircularInheritance(const CXXRecordDecl *Class,
  2183. const CXXRecordDecl *Current) {
  2184. SmallVector<const CXXRecordDecl*, 8> Queue;
  2185. Class = Class->getCanonicalDecl();
  2186. while (true) {
  2187. for (const auto &I : Current->bases()) {
  2188. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  2189. if (!Base)
  2190. continue;
  2191. Base = Base->getDefinition();
  2192. if (!Base)
  2193. continue;
  2194. if (Base->getCanonicalDecl() == Class)
  2195. return true;
  2196. Queue.push_back(Base);
  2197. }
  2198. if (Queue.empty())
  2199. return false;
  2200. Current = Queue.pop_back_val();
  2201. }
  2202. return false;
  2203. }
  2204. /// Check the validity of a C++ base class specifier.
  2205. ///
  2206. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  2207. /// and returns NULL otherwise.
  2208. CXXBaseSpecifier *
  2209. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  2210. SourceRange SpecifierRange,
  2211. bool Virtual, AccessSpecifier Access,
  2212. TypeSourceInfo *TInfo,
  2213. SourceLocation EllipsisLoc) {
  2214. QualType BaseType = TInfo->getType();
  2215. if (BaseType->containsErrors()) {
  2216. // Already emitted a diagnostic when parsing the error type.
  2217. return nullptr;
  2218. }
  2219. // C++ [class.union]p1:
  2220. // A union shall not have base classes.
  2221. if (Class->isUnion()) {
  2222. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  2223. << SpecifierRange;
  2224. return nullptr;
  2225. }
  2226. if (EllipsisLoc.isValid() &&
  2227. !TInfo->getType()->containsUnexpandedParameterPack()) {
  2228. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2229. << TInfo->getTypeLoc().getSourceRange();
  2230. EllipsisLoc = SourceLocation();
  2231. }
  2232. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  2233. if (BaseType->isDependentType()) {
  2234. // Make sure that we don't have circular inheritance among our dependent
  2235. // bases. For non-dependent bases, the check for completeness below handles
  2236. // this.
  2237. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  2238. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  2239. ((BaseDecl = BaseDecl->getDefinition()) &&
  2240. findCircularInheritance(Class, BaseDecl))) {
  2241. Diag(BaseLoc, diag::err_circular_inheritance)
  2242. << BaseType << Context.getTypeDeclType(Class);
  2243. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  2244. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  2245. << BaseType;
  2246. return nullptr;
  2247. }
  2248. }
  2249. // Make sure that we don't make an ill-formed AST where the type of the
  2250. // Class is non-dependent and its attached base class specifier is an
  2251. // dependent type, which violates invariants in many clang code paths (e.g.
  2252. // constexpr evaluator). If this case happens (in errory-recovery mode), we
  2253. // explicitly mark the Class decl invalid. The diagnostic was already
  2254. // emitted.
  2255. if (!Class->getTypeForDecl()->isDependentType())
  2256. Class->setInvalidDecl();
  2257. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2258. Class->getTagKind() == TTK_Class,
  2259. Access, TInfo, EllipsisLoc);
  2260. }
  2261. // Base specifiers must be record types.
  2262. if (!BaseType->isRecordType()) {
  2263. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  2264. return nullptr;
  2265. }
  2266. // C++ [class.union]p1:
  2267. // A union shall not be used as a base class.
  2268. if (BaseType->isUnionType()) {
  2269. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  2270. return nullptr;
  2271. }
  2272. // For the MS ABI, propagate DLL attributes to base class templates.
  2273. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2274. if (Attr *ClassAttr = getDLLAttr(Class)) {
  2275. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  2276. BaseType->getAsCXXRecordDecl())) {
  2277. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  2278. BaseLoc);
  2279. }
  2280. }
  2281. }
  2282. // C++ [class.derived]p2:
  2283. // The class-name in a base-specifier shall not be an incompletely
  2284. // defined class.
  2285. if (RequireCompleteType(BaseLoc, BaseType,
  2286. diag::err_incomplete_base_class, SpecifierRange)) {
  2287. Class->setInvalidDecl();
  2288. return nullptr;
  2289. }
  2290. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  2291. RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
  2292. assert(BaseDecl && "Record type has no declaration");
  2293. BaseDecl = BaseDecl->getDefinition();
  2294. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  2295. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  2296. assert(CXXBaseDecl && "Base type is not a C++ type");
  2297. // Microsoft docs say:
  2298. // "If a base-class has a code_seg attribute, derived classes must have the
  2299. // same attribute."
  2300. const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
  2301. const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
  2302. if ((DerivedCSA || BaseCSA) &&
  2303. (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
  2304. Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
  2305. Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
  2306. << CXXBaseDecl;
  2307. return nullptr;
  2308. }
  2309. // A class which contains a flexible array member is not suitable for use as a
  2310. // base class:
  2311. // - If the layout determines that a base comes before another base,
  2312. // the flexible array member would index into the subsequent base.
  2313. // - If the layout determines that base comes before the derived class,
  2314. // the flexible array member would index into the derived class.
  2315. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  2316. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  2317. << CXXBaseDecl->getDeclName();
  2318. return nullptr;
  2319. }
  2320. // C++ [class]p3:
  2321. // If a class is marked final and it appears as a base-type-specifier in
  2322. // base-clause, the program is ill-formed.
  2323. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  2324. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  2325. << CXXBaseDecl->getDeclName()
  2326. << FA->isSpelledAsSealed();
  2327. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  2328. << CXXBaseDecl->getDeclName() << FA->getRange();
  2329. return nullptr;
  2330. }
  2331. if (BaseDecl->isInvalidDecl())
  2332. Class->setInvalidDecl();
  2333. // Create the base specifier.
  2334. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  2335. Class->getTagKind() == TTK_Class,
  2336. Access, TInfo, EllipsisLoc);
  2337. }
  2338. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  2339. /// one entry in the base class list of a class specifier, for
  2340. /// example:
  2341. /// class foo : public bar, virtual private baz {
  2342. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  2343. BaseResult
  2344. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  2345. ParsedAttributes &Attributes,
  2346. bool Virtual, AccessSpecifier Access,
  2347. ParsedType basetype, SourceLocation BaseLoc,
  2348. SourceLocation EllipsisLoc) {
  2349. if (!classdecl)
  2350. return true;
  2351. AdjustDeclIfTemplate(classdecl);
  2352. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  2353. if (!Class)
  2354. return true;
  2355. // We haven't yet attached the base specifiers.
  2356. Class->setIsParsingBaseSpecifiers();
  2357. // We do not support any C++11 attributes on base-specifiers yet.
  2358. // Diagnose any attributes we see.
  2359. for (const ParsedAttr &AL : Attributes) {
  2360. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  2361. continue;
  2362. Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
  2363. ? (unsigned)diag::warn_unknown_attribute_ignored
  2364. : (unsigned)diag::err_base_specifier_attribute)
  2365. << AL << AL.getRange();
  2366. }
  2367. TypeSourceInfo *TInfo = nullptr;
  2368. GetTypeFromParser(basetype, &TInfo);
  2369. if (EllipsisLoc.isInvalid() &&
  2370. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  2371. UPPC_BaseType))
  2372. return true;
  2373. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  2374. Virtual, Access, TInfo,
  2375. EllipsisLoc))
  2376. return BaseSpec;
  2377. else
  2378. Class->setInvalidDecl();
  2379. return true;
  2380. }
  2381. /// Use small set to collect indirect bases. As this is only used
  2382. /// locally, there's no need to abstract the small size parameter.
  2383. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  2384. /// Recursively add the bases of Type. Don't add Type itself.
  2385. static void
  2386. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  2387. const QualType &Type)
  2388. {
  2389. // Even though the incoming type is a base, it might not be
  2390. // a class -- it could be a template parm, for instance.
  2391. if (auto Rec = Type->getAs<RecordType>()) {
  2392. auto Decl = Rec->getAsCXXRecordDecl();
  2393. // Iterate over its bases.
  2394. for (const auto &BaseSpec : Decl->bases()) {
  2395. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  2396. .getUnqualifiedType();
  2397. if (Set.insert(Base).second)
  2398. // If we've not already seen it, recurse.
  2399. NoteIndirectBases(Context, Set, Base);
  2400. }
  2401. }
  2402. }
  2403. /// Performs the actual work of attaching the given base class
  2404. /// specifiers to a C++ class.
  2405. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
  2406. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2407. if (Bases.empty())
  2408. return false;
  2409. // Used to keep track of which base types we have already seen, so
  2410. // that we can properly diagnose redundant direct base types. Note
  2411. // that the key is always the unqualified canonical type of the base
  2412. // class.
  2413. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  2414. // Used to track indirect bases so we can see if a direct base is
  2415. // ambiguous.
  2416. IndirectBaseSet IndirectBaseTypes;
  2417. // Copy non-redundant base specifiers into permanent storage.
  2418. unsigned NumGoodBases = 0;
  2419. bool Invalid = false;
  2420. for (unsigned idx = 0; idx < Bases.size(); ++idx) {
  2421. QualType NewBaseType
  2422. = Context.getCanonicalType(Bases[idx]->getType());
  2423. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  2424. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  2425. if (KnownBase) {
  2426. // C++ [class.mi]p3:
  2427. // A class shall not be specified as a direct base class of a
  2428. // derived class more than once.
  2429. Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
  2430. << KnownBase->getType() << Bases[idx]->getSourceRange();
  2431. // Delete the duplicate base class specifier; we're going to
  2432. // overwrite its pointer later.
  2433. Context.Deallocate(Bases[idx]);
  2434. Invalid = true;
  2435. } else {
  2436. // Okay, add this new base class.
  2437. KnownBase = Bases[idx];
  2438. Bases[NumGoodBases++] = Bases[idx];
  2439. if (NewBaseType->isDependentType())
  2440. continue;
  2441. // Note this base's direct & indirect bases, if there could be ambiguity.
  2442. if (Bases.size() > 1)
  2443. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  2444. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  2445. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  2446. if (Class->isInterface() &&
  2447. (!RD->isInterfaceLike() ||
  2448. KnownBase->getAccessSpecifier() != AS_public)) {
  2449. // The Microsoft extension __interface does not permit bases that
  2450. // are not themselves public interfaces.
  2451. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
  2452. << getRecordDiagFromTagKind(RD->getTagKind()) << RD
  2453. << RD->getSourceRange();
  2454. Invalid = true;
  2455. }
  2456. if (RD->hasAttr<WeakAttr>())
  2457. Class->addAttr(WeakAttr::CreateImplicit(Context));
  2458. }
  2459. }
  2460. }
  2461. // Attach the remaining base class specifiers to the derived class.
  2462. Class->setBases(Bases.data(), NumGoodBases);
  2463. // Check that the only base classes that are duplicate are virtual.
  2464. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  2465. // Check whether this direct base is inaccessible due to ambiguity.
  2466. QualType BaseType = Bases[idx]->getType();
  2467. // Skip all dependent types in templates being used as base specifiers.
  2468. // Checks below assume that the base specifier is a CXXRecord.
  2469. if (BaseType->isDependentType())
  2470. continue;
  2471. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  2472. .getUnqualifiedType();
  2473. if (IndirectBaseTypes.count(CanonicalBase)) {
  2474. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2475. /*DetectVirtual=*/true);
  2476. bool found
  2477. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  2478. assert(found);
  2479. (void)found;
  2480. if (Paths.isAmbiguous(CanonicalBase))
  2481. Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
  2482. << BaseType << getAmbiguousPathsDisplayString(Paths)
  2483. << Bases[idx]->getSourceRange();
  2484. else
  2485. assert(Bases[idx]->isVirtual());
  2486. }
  2487. // Delete the base class specifier, since its data has been copied
  2488. // into the CXXRecordDecl.
  2489. Context.Deallocate(Bases[idx]);
  2490. }
  2491. return Invalid;
  2492. }
  2493. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  2494. /// class, after checking whether there are any duplicate base
  2495. /// classes.
  2496. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
  2497. MutableArrayRef<CXXBaseSpecifier *> Bases) {
  2498. if (!ClassDecl || Bases.empty())
  2499. return;
  2500. AdjustDeclIfTemplate(ClassDecl);
  2501. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
  2502. }
  2503. /// Determine whether the type \p Derived is a C++ class that is
  2504. /// derived from the type \p Base.
  2505. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
  2506. if (!getLangOpts().CPlusPlus)
  2507. return false;
  2508. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2509. if (!DerivedRD)
  2510. return false;
  2511. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2512. if (!BaseRD)
  2513. return false;
  2514. // If either the base or the derived type is invalid, don't try to
  2515. // check whether one is derived from the other.
  2516. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  2517. return false;
  2518. // FIXME: In a modules build, do we need the entire path to be visible for us
  2519. // to be able to use the inheritance relationship?
  2520. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2521. return false;
  2522. return DerivedRD->isDerivedFrom(BaseRD);
  2523. }
  2524. /// Determine whether the type \p Derived is a C++ class that is
  2525. /// derived from the type \p Base.
  2526. bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
  2527. CXXBasePaths &Paths) {
  2528. if (!getLangOpts().CPlusPlus)
  2529. return false;
  2530. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  2531. if (!DerivedRD)
  2532. return false;
  2533. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  2534. if (!BaseRD)
  2535. return false;
  2536. if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
  2537. return false;
  2538. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  2539. }
  2540. static void BuildBasePathArray(const CXXBasePath &Path,
  2541. CXXCastPath &BasePathArray) {
  2542. // We first go backward and check if we have a virtual base.
  2543. // FIXME: It would be better if CXXBasePath had the base specifier for
  2544. // the nearest virtual base.
  2545. unsigned Start = 0;
  2546. for (unsigned I = Path.size(); I != 0; --I) {
  2547. if (Path[I - 1].Base->isVirtual()) {
  2548. Start = I - 1;
  2549. break;
  2550. }
  2551. }
  2552. // Now add all bases.
  2553. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  2554. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  2555. }
  2556. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  2557. CXXCastPath &BasePathArray) {
  2558. assert(BasePathArray.empty() && "Base path array must be empty!");
  2559. assert(Paths.isRecordingPaths() && "Must record paths!");
  2560. return ::BuildBasePathArray(Paths.front(), BasePathArray);
  2561. }
  2562. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  2563. /// conversion (where Derived and Base are class types) is
  2564. /// well-formed, meaning that the conversion is unambiguous (and
  2565. /// that all of the base classes are accessible). Returns true
  2566. /// and emits a diagnostic if the code is ill-formed, returns false
  2567. /// otherwise. Loc is the location where this routine should point to
  2568. /// if there is an error, and Range is the source range to highlight
  2569. /// if there is an error.
  2570. ///
  2571. /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
  2572. /// diagnostic for the respective type of error will be suppressed, but the
  2573. /// check for ill-formed code will still be performed.
  2574. bool
  2575. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2576. unsigned InaccessibleBaseID,
  2577. unsigned AmbiguousBaseConvID,
  2578. SourceLocation Loc, SourceRange Range,
  2579. DeclarationName Name,
  2580. CXXCastPath *BasePath,
  2581. bool IgnoreAccess) {
  2582. // First, determine whether the path from Derived to Base is
  2583. // ambiguous. This is slightly more expensive than checking whether
  2584. // the Derived to Base conversion exists, because here we need to
  2585. // explore multiple paths to determine if there is an ambiguity.
  2586. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2587. /*DetectVirtual=*/false);
  2588. bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2589. if (!DerivationOkay)
  2590. return true;
  2591. const CXXBasePath *Path = nullptr;
  2592. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
  2593. Path = &Paths.front();
  2594. // For MSVC compatibility, check if Derived directly inherits from Base. Clang
  2595. // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
  2596. // user to access such bases.
  2597. if (!Path && getLangOpts().MSVCCompat) {
  2598. for (const CXXBasePath &PossiblePath : Paths) {
  2599. if (PossiblePath.size() == 1) {
  2600. Path = &PossiblePath;
  2601. if (AmbiguousBaseConvID)
  2602. Diag(Loc, diag::ext_ms_ambiguous_direct_base)
  2603. << Base << Derived << Range;
  2604. break;
  2605. }
  2606. }
  2607. }
  2608. if (Path) {
  2609. if (!IgnoreAccess) {
  2610. // Check that the base class can be accessed.
  2611. switch (
  2612. CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
  2613. case AR_inaccessible:
  2614. return true;
  2615. case AR_accessible:
  2616. case AR_dependent:
  2617. case AR_delayed:
  2618. break;
  2619. }
  2620. }
  2621. // Build a base path if necessary.
  2622. if (BasePath)
  2623. ::BuildBasePathArray(*Path, *BasePath);
  2624. return false;
  2625. }
  2626. if (AmbiguousBaseConvID) {
  2627. // We know that the derived-to-base conversion is ambiguous, and
  2628. // we're going to produce a diagnostic. Perform the derived-to-base
  2629. // search just one more time to compute all of the possible paths so
  2630. // that we can print them out. This is more expensive than any of
  2631. // the previous derived-to-base checks we've done, but at this point
  2632. // performance isn't as much of an issue.
  2633. Paths.clear();
  2634. Paths.setRecordingPaths(true);
  2635. bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
  2636. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  2637. (void)StillOkay;
  2638. // Build up a textual representation of the ambiguous paths, e.g.,
  2639. // D -> B -> A, that will be used to illustrate the ambiguous
  2640. // conversions in the diagnostic. We only print one of the paths
  2641. // to each base class subobject.
  2642. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  2643. Diag(Loc, AmbiguousBaseConvID)
  2644. << Derived << Base << PathDisplayStr << Range << Name;
  2645. }
  2646. return true;
  2647. }
  2648. bool
  2649. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  2650. SourceLocation Loc, SourceRange Range,
  2651. CXXCastPath *BasePath,
  2652. bool IgnoreAccess) {
  2653. return CheckDerivedToBaseConversion(
  2654. Derived, Base, diag::err_upcast_to_inaccessible_base,
  2655. diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
  2656. BasePath, IgnoreAccess);
  2657. }
  2658. /// Builds a string representing ambiguous paths from a
  2659. /// specific derived class to different subobjects of the same base
  2660. /// class.
  2661. ///
  2662. /// This function builds a string that can be used in error messages
  2663. /// to show the different paths that one can take through the
  2664. /// inheritance hierarchy to go from the derived class to different
  2665. /// subobjects of a base class. The result looks something like this:
  2666. /// @code
  2667. /// struct D -> struct B -> struct A
  2668. /// struct D -> struct C -> struct A
  2669. /// @endcode
  2670. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  2671. std::string PathDisplayStr;
  2672. std::set<unsigned> DisplayedPaths;
  2673. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2674. Path != Paths.end(); ++Path) {
  2675. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  2676. // We haven't displayed a path to this particular base
  2677. // class subobject yet.
  2678. PathDisplayStr += "\n ";
  2679. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  2680. for (CXXBasePath::const_iterator Element = Path->begin();
  2681. Element != Path->end(); ++Element)
  2682. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  2683. }
  2684. }
  2685. return PathDisplayStr;
  2686. }
  2687. //===----------------------------------------------------------------------===//
  2688. // C++ class member Handling
  2689. //===----------------------------------------------------------------------===//
  2690. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  2691. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
  2692. SourceLocation ColonLoc,
  2693. const ParsedAttributesView &Attrs) {
  2694. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  2695. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  2696. ASLoc, ColonLoc);
  2697. CurContext->addHiddenDecl(ASDecl);
  2698. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  2699. }
  2700. /// CheckOverrideControl - Check C++11 override control semantics.
  2701. void Sema::CheckOverrideControl(NamedDecl *D) {
  2702. if (D->isInvalidDecl())
  2703. return;
  2704. // We only care about "override" and "final" declarations.
  2705. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  2706. return;
  2707. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2708. // We can't check dependent instance methods.
  2709. if (MD && MD->isInstance() &&
  2710. (MD->getParent()->hasAnyDependentBases() ||
  2711. MD->getType()->isDependentType()))
  2712. return;
  2713. if (MD && !MD->isVirtual()) {
  2714. // If we have a non-virtual method, check if if hides a virtual method.
  2715. // (In that case, it's most likely the method has the wrong type.)
  2716. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  2717. FindHiddenVirtualMethods(MD, OverloadedMethods);
  2718. if (!OverloadedMethods.empty()) {
  2719. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2720. Diag(OA->getLocation(),
  2721. diag::override_keyword_hides_virtual_member_function)
  2722. << "override" << (OverloadedMethods.size() > 1);
  2723. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2724. Diag(FA->getLocation(),
  2725. diag::override_keyword_hides_virtual_member_function)
  2726. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2727. << (OverloadedMethods.size() > 1);
  2728. }
  2729. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  2730. MD->setInvalidDecl();
  2731. return;
  2732. }
  2733. // Fall through into the general case diagnostic.
  2734. // FIXME: We might want to attempt typo correction here.
  2735. }
  2736. if (!MD || !MD->isVirtual()) {
  2737. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  2738. Diag(OA->getLocation(),
  2739. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2740. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  2741. D->dropAttr<OverrideAttr>();
  2742. }
  2743. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  2744. Diag(FA->getLocation(),
  2745. diag::override_keyword_only_allowed_on_virtual_member_functions)
  2746. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  2747. << FixItHint::CreateRemoval(FA->getLocation());
  2748. D->dropAttr<FinalAttr>();
  2749. }
  2750. return;
  2751. }
  2752. // C++11 [class.virtual]p5:
  2753. // If a function is marked with the virt-specifier override and
  2754. // does not override a member function of a base class, the program is
  2755. // ill-formed.
  2756. bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
  2757. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  2758. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  2759. << MD->getDeclName();
  2760. }
  2761. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
  2762. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  2763. return;
  2764. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  2765. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
  2766. return;
  2767. SourceLocation Loc = MD->getLocation();
  2768. SourceLocation SpellingLoc = Loc;
  2769. if (getSourceManager().isMacroArgExpansion(Loc))
  2770. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
  2771. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  2772. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  2773. return;
  2774. if (MD->size_overridden_methods() > 0) {
  2775. auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
  2776. unsigned DiagID =
  2777. Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
  2778. ? DiagInconsistent
  2779. : DiagSuggest;
  2780. Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  2781. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  2782. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  2783. };
  2784. if (isa<CXXDestructorDecl>(MD))
  2785. EmitDiag(
  2786. diag::warn_inconsistent_destructor_marked_not_override_overriding,
  2787. diag::warn_suggest_destructor_marked_not_override_overriding);
  2788. else
  2789. EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
  2790. diag::warn_suggest_function_marked_not_override_overriding);
  2791. }
  2792. }
  2793. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  2794. /// function overrides a virtual member function marked 'final', according to
  2795. /// C++11 [class.virtual]p4.
  2796. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  2797. const CXXMethodDecl *Old) {
  2798. FinalAttr *FA = Old->getAttr<FinalAttr>();
  2799. if (!FA)
  2800. return false;
  2801. Diag(New->getLocation(), diag::err_final_function_overridden)
  2802. << New->getDeclName()
  2803. << FA->isSpelledAsSealed();
  2804. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  2805. return true;
  2806. }
  2807. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  2808. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  2809. // FIXME: Destruction of ObjC lifetime types has side-effects.
  2810. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  2811. return !RD->isCompleteDefinition() ||
  2812. !RD->hasTrivialDefaultConstructor() ||
  2813. !RD->hasTrivialDestructor();
  2814. return false;
  2815. }
  2816. static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
  2817. ParsedAttributesView::const_iterator Itr =
  2818. llvm::find_if(list, [](const ParsedAttr &AL) {
  2819. return AL.isDeclspecPropertyAttribute();
  2820. });
  2821. if (Itr != list.end())
  2822. return &*Itr;
  2823. return nullptr;
  2824. }
  2825. // Check if there is a field shadowing.
  2826. void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
  2827. DeclarationName FieldName,
  2828. const CXXRecordDecl *RD,
  2829. bool DeclIsField) {
  2830. if (Diags.isIgnored(diag::warn_shadow_field, Loc))
  2831. return;
  2832. // To record a shadowed field in a base
  2833. std::map<CXXRecordDecl*, NamedDecl*> Bases;
  2834. auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
  2835. CXXBasePath &Path) {
  2836. const auto Base = Specifier->getType()->getAsCXXRecordDecl();
  2837. // Record an ambiguous path directly
  2838. if (Bases.find(Base) != Bases.end())
  2839. return true;
  2840. for (const auto Field : Base->lookup(FieldName)) {
  2841. if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
  2842. Field->getAccess() != AS_private) {
  2843. assert(Field->getAccess() != AS_none);
  2844. assert(Bases.find(Base) == Bases.end());
  2845. Bases[Base] = Field;
  2846. return true;
  2847. }
  2848. }
  2849. return false;
  2850. };
  2851. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2852. /*DetectVirtual=*/true);
  2853. if (!RD->lookupInBases(FieldShadowed, Paths))
  2854. return;
  2855. for (const auto &P : Paths) {
  2856. auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
  2857. auto It = Bases.find(Base);
  2858. // Skip duplicated bases
  2859. if (It == Bases.end())
  2860. continue;
  2861. auto BaseField = It->second;
  2862. assert(BaseField->getAccess() != AS_private);
  2863. if (AS_none !=
  2864. CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
  2865. Diag(Loc, diag::warn_shadow_field)
  2866. << FieldName << RD << Base << DeclIsField;
  2867. Diag(BaseField->getLocation(), diag::note_shadow_field);
  2868. Bases.erase(It);
  2869. }
  2870. }
  2871. }
  2872. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  2873. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  2874. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  2875. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  2876. /// present (but parsing it has been deferred).
  2877. NamedDecl *
  2878. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  2879. MultiTemplateParamsArg TemplateParameterLists,
  2880. Expr *BW, const VirtSpecifiers &VS,
  2881. InClassInitStyle InitStyle) {
  2882. const DeclSpec &DS = D.getDeclSpec();
  2883. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  2884. DeclarationName Name = NameInfo.getName();
  2885. SourceLocation Loc = NameInfo.getLoc();
  2886. // For anonymous bitfields, the location should point to the type.
  2887. if (Loc.isInvalid())
  2888. Loc = D.getBeginLoc();
  2889. Expr *BitWidth = static_cast<Expr*>(BW);
  2890. assert(isa<CXXRecordDecl>(CurContext));
  2891. assert(!DS.isFriendSpecified());
  2892. bool isFunc = D.isDeclarationOfFunction();
  2893. const ParsedAttr *MSPropertyAttr =
  2894. getMSPropertyAttr(D.getDeclSpec().getAttributes());
  2895. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  2896. // The Microsoft extension __interface only permits public member functions
  2897. // and prohibits constructors, destructors, operators, non-public member
  2898. // functions, static methods and data members.
  2899. unsigned InvalidDecl;
  2900. bool ShowDeclName = true;
  2901. if (!isFunc &&
  2902. (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
  2903. InvalidDecl = 0;
  2904. else if (!isFunc)
  2905. InvalidDecl = 1;
  2906. else if (AS != AS_public)
  2907. InvalidDecl = 2;
  2908. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2909. InvalidDecl = 3;
  2910. else switch (Name.getNameKind()) {
  2911. case DeclarationName::CXXConstructorName:
  2912. InvalidDecl = 4;
  2913. ShowDeclName = false;
  2914. break;
  2915. case DeclarationName::CXXDestructorName:
  2916. InvalidDecl = 5;
  2917. ShowDeclName = false;
  2918. break;
  2919. case DeclarationName::CXXOperatorName:
  2920. case DeclarationName::CXXConversionFunctionName:
  2921. InvalidDecl = 6;
  2922. break;
  2923. default:
  2924. InvalidDecl = 0;
  2925. break;
  2926. }
  2927. if (InvalidDecl) {
  2928. if (ShowDeclName)
  2929. Diag(Loc, diag::err_invalid_member_in_interface)
  2930. << (InvalidDecl-1) << Name;
  2931. else
  2932. Diag(Loc, diag::err_invalid_member_in_interface)
  2933. << (InvalidDecl-1) << "";
  2934. return nullptr;
  2935. }
  2936. }
  2937. // C++ 9.2p6: A member shall not be declared to have automatic storage
  2938. // duration (auto, register) or with the extern storage-class-specifier.
  2939. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  2940. // data members and cannot be applied to names declared const or static,
  2941. // and cannot be applied to reference members.
  2942. switch (DS.getStorageClassSpec()) {
  2943. case DeclSpec::SCS_unspecified:
  2944. case DeclSpec::SCS_typedef:
  2945. case DeclSpec::SCS_static:
  2946. break;
  2947. case DeclSpec::SCS_mutable:
  2948. if (isFunc) {
  2949. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  2950. // FIXME: It would be nicer if the keyword was ignored only for this
  2951. // declarator. Otherwise we could get follow-up errors.
  2952. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2953. }
  2954. break;
  2955. default:
  2956. Diag(DS.getStorageClassSpecLoc(),
  2957. diag::err_storageclass_invalid_for_member);
  2958. D.getMutableDeclSpec().ClearStorageClassSpecs();
  2959. break;
  2960. }
  2961. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  2962. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  2963. !isFunc);
  2964. if (DS.hasConstexprSpecifier() && isInstField) {
  2965. SemaDiagnosticBuilder B =
  2966. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  2967. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  2968. if (InitStyle == ICIS_NoInit) {
  2969. B << 0 << 0;
  2970. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  2971. B << FixItHint::CreateRemoval(ConstexprLoc);
  2972. else {
  2973. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  2974. D.getMutableDeclSpec().ClearConstexprSpec();
  2975. const char *PrevSpec;
  2976. unsigned DiagID;
  2977. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  2978. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  2979. (void)Failed;
  2980. assert(!Failed && "Making a constexpr member const shouldn't fail");
  2981. }
  2982. } else {
  2983. B << 1;
  2984. const char *PrevSpec;
  2985. unsigned DiagID;
  2986. if (D.getMutableDeclSpec().SetStorageClassSpec(
  2987. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  2988. Context.getPrintingPolicy())) {
  2989. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  2990. "This is the only DeclSpec that should fail to be applied");
  2991. B << 1;
  2992. } else {
  2993. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  2994. isInstField = false;
  2995. }
  2996. }
  2997. }
  2998. NamedDecl *Member;
  2999. if (isInstField) {
  3000. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3001. // Data members must have identifiers for names.
  3002. if (!Name.isIdentifier()) {
  3003. Diag(Loc, diag::err_bad_variable_name)
  3004. << Name;
  3005. return nullptr;
  3006. }
  3007. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3008. // Member field could not be with "template" keyword.
  3009. // So TemplateParameterLists should be empty in this case.
  3010. if (TemplateParameterLists.size()) {
  3011. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  3012. if (TemplateParams->size()) {
  3013. // There is no such thing as a member field template.
  3014. Diag(D.getIdentifierLoc(), diag::err_template_member)
  3015. << II
  3016. << SourceRange(TemplateParams->getTemplateLoc(),
  3017. TemplateParams->getRAngleLoc());
  3018. } else {
  3019. // There is an extraneous 'template<>' for this member.
  3020. Diag(TemplateParams->getTemplateLoc(),
  3021. diag::err_template_member_noparams)
  3022. << II
  3023. << SourceRange(TemplateParams->getTemplateLoc(),
  3024. TemplateParams->getRAngleLoc());
  3025. }
  3026. return nullptr;
  3027. }
  3028. if (SS.isSet() && !SS.isInvalid()) {
  3029. // The user provided a superfluous scope specifier inside a class
  3030. // definition:
  3031. //
  3032. // class X {
  3033. // int X::member;
  3034. // };
  3035. if (DeclContext *DC = computeDeclContext(SS, false))
  3036. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
  3037. D.getName().getKind() ==
  3038. UnqualifiedIdKind::IK_TemplateId);
  3039. else
  3040. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  3041. << Name << SS.getRange();
  3042. SS.clear();
  3043. }
  3044. if (MSPropertyAttr) {
  3045. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  3046. BitWidth, InitStyle, AS, *MSPropertyAttr);
  3047. if (!Member)
  3048. return nullptr;
  3049. isInstField = false;
  3050. } else {
  3051. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  3052. BitWidth, InitStyle, AS);
  3053. if (!Member)
  3054. return nullptr;
  3055. }
  3056. CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
  3057. } else {
  3058. Member = HandleDeclarator(S, D, TemplateParameterLists);
  3059. if (!Member)
  3060. return nullptr;
  3061. // Non-instance-fields can't have a bitfield.
  3062. if (BitWidth) {
  3063. if (Member->isInvalidDecl()) {
  3064. // don't emit another diagnostic.
  3065. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  3066. // C++ 9.6p3: A bit-field shall not be a static member.
  3067. // "static member 'A' cannot be a bit-field"
  3068. Diag(Loc, diag::err_static_not_bitfield)
  3069. << Name << BitWidth->getSourceRange();
  3070. } else if (isa<TypedefDecl>(Member)) {
  3071. // "typedef member 'x' cannot be a bit-field"
  3072. Diag(Loc, diag::err_typedef_not_bitfield)
  3073. << Name << BitWidth->getSourceRange();
  3074. } else {
  3075. // A function typedef ("typedef int f(); f a;").
  3076. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  3077. Diag(Loc, diag::err_not_integral_type_bitfield)
  3078. << Name << cast<ValueDecl>(Member)->getType()
  3079. << BitWidth->getSourceRange();
  3080. }
  3081. BitWidth = nullptr;
  3082. Member->setInvalidDecl();
  3083. }
  3084. NamedDecl *NonTemplateMember = Member;
  3085. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  3086. NonTemplateMember = FunTmpl->getTemplatedDecl();
  3087. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  3088. NonTemplateMember = VarTmpl->getTemplatedDecl();
  3089. Member->setAccess(AS);
  3090. // If we have declared a member function template or static data member
  3091. // template, set the access of the templated declaration as well.
  3092. if (NonTemplateMember != Member)
  3093. NonTemplateMember->setAccess(AS);
  3094. // C++ [temp.deduct.guide]p3:
  3095. // A deduction guide [...] for a member class template [shall be
  3096. // declared] with the same access [as the template].
  3097. if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
  3098. auto *TD = DG->getDeducedTemplate();
  3099. // Access specifiers are only meaningful if both the template and the
  3100. // deduction guide are from the same scope.
  3101. if (AS != TD->getAccess() &&
  3102. TD->getDeclContext()->getRedeclContext()->Equals(
  3103. DG->getDeclContext()->getRedeclContext())) {
  3104. Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
  3105. Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
  3106. << TD->getAccess();
  3107. const AccessSpecDecl *LastAccessSpec = nullptr;
  3108. for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
  3109. if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
  3110. LastAccessSpec = AccessSpec;
  3111. }
  3112. assert(LastAccessSpec && "differing access with no access specifier");
  3113. Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
  3114. << AS;
  3115. }
  3116. }
  3117. }
  3118. if (VS.isOverrideSpecified())
  3119. Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
  3120. AttributeCommonInfo::AS_Keyword));
  3121. if (VS.isFinalSpecified())
  3122. Member->addAttr(FinalAttr::Create(
  3123. Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
  3124. static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
  3125. if (VS.getLastLocation().isValid()) {
  3126. // Update the end location of a method that has a virt-specifiers.
  3127. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  3128. MD->setRangeEnd(VS.getLastLocation());
  3129. }
  3130. CheckOverrideControl(Member);
  3131. assert((Name || isInstField) && "No identifier for non-field ?");
  3132. if (isInstField) {
  3133. FieldDecl *FD = cast<FieldDecl>(Member);
  3134. FieldCollector->Add(FD);
  3135. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  3136. // Remember all explicit private FieldDecls that have a name, no side
  3137. // effects and are not part of a dependent type declaration.
  3138. if (!FD->isImplicit() && FD->getDeclName() &&
  3139. FD->getAccess() == AS_private &&
  3140. !FD->hasAttr<UnusedAttr>() &&
  3141. !FD->getParent()->isDependentContext() &&
  3142. !InitializationHasSideEffects(*FD))
  3143. UnusedPrivateFields.insert(FD);
  3144. }
  3145. }
  3146. return Member;
  3147. }
  3148. namespace {
  3149. class UninitializedFieldVisitor
  3150. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  3151. Sema &S;
  3152. // List of Decls to generate a warning on. Also remove Decls that become
  3153. // initialized.
  3154. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  3155. // List of base classes of the record. Classes are removed after their
  3156. // initializers.
  3157. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  3158. // Vector of decls to be removed from the Decl set prior to visiting the
  3159. // nodes. These Decls may have been initialized in the prior initializer.
  3160. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  3161. // If non-null, add a note to the warning pointing back to the constructor.
  3162. const CXXConstructorDecl *Constructor;
  3163. // Variables to hold state when processing an initializer list. When
  3164. // InitList is true, special case initialization of FieldDecls matching
  3165. // InitListFieldDecl.
  3166. bool InitList;
  3167. FieldDecl *InitListFieldDecl;
  3168. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  3169. public:
  3170. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  3171. UninitializedFieldVisitor(Sema &S,
  3172. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  3173. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  3174. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  3175. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  3176. // Returns true if the use of ME is not an uninitialized use.
  3177. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  3178. bool CheckReferenceOnly) {
  3179. llvm::SmallVector<FieldDecl*, 4> Fields;
  3180. bool ReferenceField = false;
  3181. while (ME) {
  3182. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  3183. if (!FD)
  3184. return false;
  3185. Fields.push_back(FD);
  3186. if (FD->getType()->isReferenceType())
  3187. ReferenceField = true;
  3188. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  3189. }
  3190. // Binding a reference to an uninitialized field is not an
  3191. // uninitialized use.
  3192. if (CheckReferenceOnly && !ReferenceField)
  3193. return true;
  3194. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  3195. // Discard the first field since it is the field decl that is being
  3196. // initialized.
  3197. for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
  3198. UsedFieldIndex.push_back(FD->getFieldIndex());
  3199. for (auto UsedIter = UsedFieldIndex.begin(),
  3200. UsedEnd = UsedFieldIndex.end(),
  3201. OrigIter = InitFieldIndex.begin(),
  3202. OrigEnd = InitFieldIndex.end();
  3203. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  3204. if (*UsedIter < *OrigIter)
  3205. return true;
  3206. if (*UsedIter > *OrigIter)
  3207. break;
  3208. }
  3209. return false;
  3210. }
  3211. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  3212. bool AddressOf) {
  3213. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  3214. return;
  3215. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  3216. // or union.
  3217. MemberExpr *FieldME = ME;
  3218. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  3219. Expr *Base = ME;
  3220. while (MemberExpr *SubME =
  3221. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  3222. if (isa<VarDecl>(SubME->getMemberDecl()))
  3223. return;
  3224. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  3225. if (!FD->isAnonymousStructOrUnion())
  3226. FieldME = SubME;
  3227. if (!FieldME->getType().isPODType(S.Context))
  3228. AllPODFields = false;
  3229. Base = SubME->getBase();
  3230. }
  3231. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
  3232. Visit(Base);
  3233. return;
  3234. }
  3235. if (AddressOf && AllPODFields)
  3236. return;
  3237. ValueDecl* FoundVD = FieldME->getMemberDecl();
  3238. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  3239. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  3240. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  3241. }
  3242. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  3243. QualType T = BaseCast->getType();
  3244. if (T->isPointerType() &&
  3245. BaseClasses.count(T->getPointeeType())) {
  3246. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  3247. << T->getPointeeType() << FoundVD;
  3248. }
  3249. }
  3250. }
  3251. if (!Decls.count(FoundVD))
  3252. return;
  3253. const bool IsReference = FoundVD->getType()->isReferenceType();
  3254. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  3255. // Special checking for initializer lists.
  3256. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  3257. return;
  3258. }
  3259. } else {
  3260. // Prevent double warnings on use of unbounded references.
  3261. if (CheckReferenceOnly && !IsReference)
  3262. return;
  3263. }
  3264. unsigned diag = IsReference
  3265. ? diag::warn_reference_field_is_uninit
  3266. : diag::warn_field_is_uninit;
  3267. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  3268. if (Constructor)
  3269. S.Diag(Constructor->getLocation(),
  3270. diag::note_uninit_in_this_constructor)
  3271. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  3272. }
  3273. void HandleValue(Expr *E, bool AddressOf) {
  3274. E = E->IgnoreParens();
  3275. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3276. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  3277. AddressOf /*AddressOf*/);
  3278. return;
  3279. }
  3280. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3281. Visit(CO->getCond());
  3282. HandleValue(CO->getTrueExpr(), AddressOf);
  3283. HandleValue(CO->getFalseExpr(), AddressOf);
  3284. return;
  3285. }
  3286. if (BinaryConditionalOperator *BCO =
  3287. dyn_cast<BinaryConditionalOperator>(E)) {
  3288. Visit(BCO->getCond());
  3289. HandleValue(BCO->getFalseExpr(), AddressOf);
  3290. return;
  3291. }
  3292. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  3293. HandleValue(OVE->getSourceExpr(), AddressOf);
  3294. return;
  3295. }
  3296. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3297. switch (BO->getOpcode()) {
  3298. default:
  3299. break;
  3300. case(BO_PtrMemD):
  3301. case(BO_PtrMemI):
  3302. HandleValue(BO->getLHS(), AddressOf);
  3303. Visit(BO->getRHS());
  3304. return;
  3305. case(BO_Comma):
  3306. Visit(BO->getLHS());
  3307. HandleValue(BO->getRHS(), AddressOf);
  3308. return;
  3309. }
  3310. }
  3311. Visit(E);
  3312. }
  3313. void CheckInitListExpr(InitListExpr *ILE) {
  3314. InitFieldIndex.push_back(0);
  3315. for (auto Child : ILE->children()) {
  3316. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  3317. CheckInitListExpr(SubList);
  3318. } else {
  3319. Visit(Child);
  3320. }
  3321. ++InitFieldIndex.back();
  3322. }
  3323. InitFieldIndex.pop_back();
  3324. }
  3325. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  3326. FieldDecl *Field, const Type *BaseClass) {
  3327. // Remove Decls that may have been initialized in the previous
  3328. // initializer.
  3329. for (ValueDecl* VD : DeclsToRemove)
  3330. Decls.erase(VD);
  3331. DeclsToRemove.clear();
  3332. Constructor = FieldConstructor;
  3333. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  3334. if (ILE && Field) {
  3335. InitList = true;
  3336. InitListFieldDecl = Field;
  3337. InitFieldIndex.clear();
  3338. CheckInitListExpr(ILE);
  3339. } else {
  3340. InitList = false;
  3341. Visit(E);
  3342. }
  3343. if (Field)
  3344. Decls.erase(Field);
  3345. if (BaseClass)
  3346. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  3347. }
  3348. void VisitMemberExpr(MemberExpr *ME) {
  3349. // All uses of unbounded reference fields will warn.
  3350. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  3351. }
  3352. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  3353. if (E->getCastKind() == CK_LValueToRValue) {
  3354. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3355. return;
  3356. }
  3357. Inherited::VisitImplicitCastExpr(E);
  3358. }
  3359. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  3360. if (E->getConstructor()->isCopyConstructor()) {
  3361. Expr *ArgExpr = E->getArg(0);
  3362. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  3363. if (ILE->getNumInits() == 1)
  3364. ArgExpr = ILE->getInit(0);
  3365. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  3366. if (ICE->getCastKind() == CK_NoOp)
  3367. ArgExpr = ICE->getSubExpr();
  3368. HandleValue(ArgExpr, false /*AddressOf*/);
  3369. return;
  3370. }
  3371. Inherited::VisitCXXConstructExpr(E);
  3372. }
  3373. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  3374. Expr *Callee = E->getCallee();
  3375. if (isa<MemberExpr>(Callee)) {
  3376. HandleValue(Callee, false /*AddressOf*/);
  3377. for (auto Arg : E->arguments())
  3378. Visit(Arg);
  3379. return;
  3380. }
  3381. Inherited::VisitCXXMemberCallExpr(E);
  3382. }
  3383. void VisitCallExpr(CallExpr *E) {
  3384. // Treat std::move as a use.
  3385. if (E->isCallToStdMove()) {
  3386. HandleValue(E->getArg(0), /*AddressOf=*/false);
  3387. return;
  3388. }
  3389. Inherited::VisitCallExpr(E);
  3390. }
  3391. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  3392. Expr *Callee = E->getCallee();
  3393. if (isa<UnresolvedLookupExpr>(Callee))
  3394. return Inherited::VisitCXXOperatorCallExpr(E);
  3395. Visit(Callee);
  3396. for (auto Arg : E->arguments())
  3397. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  3398. }
  3399. void VisitBinaryOperator(BinaryOperator *E) {
  3400. // If a field assignment is detected, remove the field from the
  3401. // uninitiailized field set.
  3402. if (E->getOpcode() == BO_Assign)
  3403. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  3404. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  3405. if (!FD->getType()->isReferenceType())
  3406. DeclsToRemove.push_back(FD);
  3407. if (E->isCompoundAssignmentOp()) {
  3408. HandleValue(E->getLHS(), false /*AddressOf*/);
  3409. Visit(E->getRHS());
  3410. return;
  3411. }
  3412. Inherited::VisitBinaryOperator(E);
  3413. }
  3414. void VisitUnaryOperator(UnaryOperator *E) {
  3415. if (E->isIncrementDecrementOp()) {
  3416. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  3417. return;
  3418. }
  3419. if (E->getOpcode() == UO_AddrOf) {
  3420. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  3421. HandleValue(ME->getBase(), true /*AddressOf*/);
  3422. return;
  3423. }
  3424. }
  3425. Inherited::VisitUnaryOperator(E);
  3426. }
  3427. };
  3428. // Diagnose value-uses of fields to initialize themselves, e.g.
  3429. // foo(foo)
  3430. // where foo is not also a parameter to the constructor.
  3431. // Also diagnose across field uninitialized use such as
  3432. // x(y), y(x)
  3433. // TODO: implement -Wuninitialized and fold this into that framework.
  3434. static void DiagnoseUninitializedFields(
  3435. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  3436. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  3437. Constructor->getLocation())) {
  3438. return;
  3439. }
  3440. if (Constructor->isInvalidDecl())
  3441. return;
  3442. const CXXRecordDecl *RD = Constructor->getParent();
  3443. if (RD->isDependentContext())
  3444. return;
  3445. // Holds fields that are uninitialized.
  3446. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  3447. // At the beginning, all fields are uninitialized.
  3448. for (auto *I : RD->decls()) {
  3449. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  3450. UninitializedFields.insert(FD);
  3451. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  3452. UninitializedFields.insert(IFD->getAnonField());
  3453. }
  3454. }
  3455. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  3456. for (auto I : RD->bases())
  3457. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  3458. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3459. return;
  3460. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  3461. UninitializedFields,
  3462. UninitializedBaseClasses);
  3463. for (const auto *FieldInit : Constructor->inits()) {
  3464. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  3465. break;
  3466. Expr *InitExpr = FieldInit->getInit();
  3467. if (!InitExpr)
  3468. continue;
  3469. if (CXXDefaultInitExpr *Default =
  3470. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  3471. InitExpr = Default->getExpr();
  3472. if (!InitExpr)
  3473. continue;
  3474. // In class initializers will point to the constructor.
  3475. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  3476. FieldInit->getAnyMember(),
  3477. FieldInit->getBaseClass());
  3478. } else {
  3479. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  3480. FieldInit->getAnyMember(),
  3481. FieldInit->getBaseClass());
  3482. }
  3483. }
  3484. }
  3485. } // namespace
  3486. /// Enter a new C++ default initializer scope. After calling this, the
  3487. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  3488. /// parsing or instantiating the initializer failed.
  3489. void Sema::ActOnStartCXXInClassMemberInitializer() {
  3490. // Create a synthetic function scope to represent the call to the constructor
  3491. // that notionally surrounds a use of this initializer.
  3492. PushFunctionScope();
  3493. }
  3494. void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
  3495. if (!D.isFunctionDeclarator())
  3496. return;
  3497. auto &FTI = D.getFunctionTypeInfo();
  3498. if (!FTI.Params)
  3499. return;
  3500. for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
  3501. FTI.NumParams)) {
  3502. auto *ParamDecl = cast<NamedDecl>(Param.Param);
  3503. if (ParamDecl->getDeclName())
  3504. PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
  3505. }
  3506. }
  3507. ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
  3508. return ActOnRequiresClause(ConstraintExpr);
  3509. }
  3510. ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
  3511. if (ConstraintExpr.isInvalid())
  3512. return ExprError();
  3513. ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
  3514. if (ConstraintExpr.isInvalid())
  3515. return ExprError();
  3516. if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
  3517. UPPC_RequiresClause))
  3518. return ExprError();
  3519. return ConstraintExpr;
  3520. }
  3521. /// This is invoked after parsing an in-class initializer for a
  3522. /// non-static C++ class member, and after instantiating an in-class initializer
  3523. /// in a class template. Such actions are deferred until the class is complete.
  3524. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  3525. SourceLocation InitLoc,
  3526. Expr *InitExpr) {
  3527. // Pop the notional constructor scope we created earlier.
  3528. PopFunctionScopeInfo(nullptr, D);
  3529. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  3530. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  3531. "must set init style when field is created");
  3532. if (!InitExpr) {
  3533. D->setInvalidDecl();
  3534. if (FD)
  3535. FD->removeInClassInitializer();
  3536. return;
  3537. }
  3538. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  3539. FD->setInvalidDecl();
  3540. FD->removeInClassInitializer();
  3541. return;
  3542. }
  3543. ExprResult Init = InitExpr;
  3544. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  3545. InitializedEntity Entity =
  3546. InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
  3547. InitializationKind Kind =
  3548. FD->getInClassInitStyle() == ICIS_ListInit
  3549. ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
  3550. InitExpr->getBeginLoc(),
  3551. InitExpr->getEndLoc())
  3552. : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
  3553. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  3554. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  3555. if (Init.isInvalid()) {
  3556. FD->setInvalidDecl();
  3557. return;
  3558. }
  3559. }
  3560. // C++11 [class.base.init]p7:
  3561. // The initialization of each base and member constitutes a
  3562. // full-expression.
  3563. Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
  3564. if (Init.isInvalid()) {
  3565. FD->setInvalidDecl();
  3566. return;
  3567. }
  3568. InitExpr = Init.get();
  3569. FD->setInClassInitializer(InitExpr);
  3570. }
  3571. /// Find the direct and/or virtual base specifiers that
  3572. /// correspond to the given base type, for use in base initialization
  3573. /// within a constructor.
  3574. static bool FindBaseInitializer(Sema &SemaRef,
  3575. CXXRecordDecl *ClassDecl,
  3576. QualType BaseType,
  3577. const CXXBaseSpecifier *&DirectBaseSpec,
  3578. const CXXBaseSpecifier *&VirtualBaseSpec) {
  3579. // First, check for a direct base class.
  3580. DirectBaseSpec = nullptr;
  3581. for (const auto &Base : ClassDecl->bases()) {
  3582. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  3583. // We found a direct base of this type. That's what we're
  3584. // initializing.
  3585. DirectBaseSpec = &Base;
  3586. break;
  3587. }
  3588. }
  3589. // Check for a virtual base class.
  3590. // FIXME: We might be able to short-circuit this if we know in advance that
  3591. // there are no virtual bases.
  3592. VirtualBaseSpec = nullptr;
  3593. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  3594. // We haven't found a base yet; search the class hierarchy for a
  3595. // virtual base class.
  3596. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  3597. /*DetectVirtual=*/false);
  3598. if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
  3599. SemaRef.Context.getTypeDeclType(ClassDecl),
  3600. BaseType, Paths)) {
  3601. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  3602. Path != Paths.end(); ++Path) {
  3603. if (Path->back().Base->isVirtual()) {
  3604. VirtualBaseSpec = Path->back().Base;
  3605. break;
  3606. }
  3607. }
  3608. }
  3609. }
  3610. return DirectBaseSpec || VirtualBaseSpec;
  3611. }
  3612. /// Handle a C++ member initializer using braced-init-list syntax.
  3613. MemInitResult
  3614. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3615. Scope *S,
  3616. CXXScopeSpec &SS,
  3617. IdentifierInfo *MemberOrBase,
  3618. ParsedType TemplateTypeTy,
  3619. const DeclSpec &DS,
  3620. SourceLocation IdLoc,
  3621. Expr *InitList,
  3622. SourceLocation EllipsisLoc) {
  3623. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3624. DS, IdLoc, InitList,
  3625. EllipsisLoc);
  3626. }
  3627. /// Handle a C++ member initializer using parentheses syntax.
  3628. MemInitResult
  3629. Sema::ActOnMemInitializer(Decl *ConstructorD,
  3630. Scope *S,
  3631. CXXScopeSpec &SS,
  3632. IdentifierInfo *MemberOrBase,
  3633. ParsedType TemplateTypeTy,
  3634. const DeclSpec &DS,
  3635. SourceLocation IdLoc,
  3636. SourceLocation LParenLoc,
  3637. ArrayRef<Expr *> Args,
  3638. SourceLocation RParenLoc,
  3639. SourceLocation EllipsisLoc) {
  3640. Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
  3641. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  3642. DS, IdLoc, List, EllipsisLoc);
  3643. }
  3644. namespace {
  3645. // Callback to only accept typo corrections that can be a valid C++ member
  3646. // initializer: either a non-static field member or a base class.
  3647. class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
  3648. public:
  3649. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  3650. : ClassDecl(ClassDecl) {}
  3651. bool ValidateCandidate(const TypoCorrection &candidate) override {
  3652. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  3653. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  3654. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  3655. return isa<TypeDecl>(ND);
  3656. }
  3657. return false;
  3658. }
  3659. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  3660. return std::make_unique<MemInitializerValidatorCCC>(*this);
  3661. }
  3662. private:
  3663. CXXRecordDecl *ClassDecl;
  3664. };
  3665. }
  3666. ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
  3667. CXXScopeSpec &SS,
  3668. ParsedType TemplateTypeTy,
  3669. IdentifierInfo *MemberOrBase) {
  3670. if (SS.getScopeRep() || TemplateTypeTy)
  3671. return nullptr;
  3672. for (auto *D : ClassDecl->lookup(MemberOrBase))
  3673. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
  3674. return cast<ValueDecl>(D);
  3675. return nullptr;
  3676. }
  3677. /// Handle a C++ member initializer.
  3678. MemInitResult
  3679. Sema::BuildMemInitializer(Decl *ConstructorD,
  3680. Scope *S,
  3681. CXXScopeSpec &SS,
  3682. IdentifierInfo *MemberOrBase,
  3683. ParsedType TemplateTypeTy,
  3684. const DeclSpec &DS,
  3685. SourceLocation IdLoc,
  3686. Expr *Init,
  3687. SourceLocation EllipsisLoc) {
  3688. ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
  3689. /*RecoverUncorrectedTypos=*/true);
  3690. if (!Res.isUsable())
  3691. return true;
  3692. Init = Res.get();
  3693. if (!ConstructorD)
  3694. return true;
  3695. AdjustDeclIfTemplate(ConstructorD);
  3696. CXXConstructorDecl *Constructor
  3697. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  3698. if (!Constructor) {
  3699. // The user wrote a constructor initializer on a function that is
  3700. // not a C++ constructor. Ignore the error for now, because we may
  3701. // have more member initializers coming; we'll diagnose it just
  3702. // once in ActOnMemInitializers.
  3703. return true;
  3704. }
  3705. CXXRecordDecl *ClassDecl = Constructor->getParent();
  3706. // C++ [class.base.init]p2:
  3707. // Names in a mem-initializer-id are looked up in the scope of the
  3708. // constructor's class and, if not found in that scope, are looked
  3709. // up in the scope containing the constructor's definition.
  3710. // [Note: if the constructor's class contains a member with the
  3711. // same name as a direct or virtual base class of the class, a
  3712. // mem-initializer-id naming the member or base class and composed
  3713. // of a single identifier refers to the class member. A
  3714. // mem-initializer-id for the hidden base class may be specified
  3715. // using a qualified name. ]
  3716. // Look for a member, first.
  3717. if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
  3718. ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
  3719. if (EllipsisLoc.isValid())
  3720. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  3721. << MemberOrBase
  3722. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  3723. return BuildMemberInitializer(Member, Init, IdLoc);
  3724. }
  3725. // It didn't name a member, so see if it names a class.
  3726. QualType BaseType;
  3727. TypeSourceInfo *TInfo = nullptr;
  3728. if (TemplateTypeTy) {
  3729. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  3730. if (BaseType.isNull())
  3731. return true;
  3732. } else if (DS.getTypeSpecType() == TST_decltype) {
  3733. BaseType = BuildDecltypeType(DS.getRepAsExpr());
  3734. } else if (DS.getTypeSpecType() == TST_decltype_auto) {
  3735. Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
  3736. return true;
  3737. } else {
  3738. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  3739. LookupParsedName(R, S, &SS);
  3740. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  3741. if (!TyD) {
  3742. if (R.isAmbiguous()) return true;
  3743. // We don't want access-control diagnostics here.
  3744. R.suppressDiagnostics();
  3745. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  3746. bool NotUnknownSpecialization = false;
  3747. DeclContext *DC = computeDeclContext(SS, false);
  3748. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  3749. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  3750. if (!NotUnknownSpecialization) {
  3751. // When the scope specifier can refer to a member of an unknown
  3752. // specialization, we take it as a type name.
  3753. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  3754. SS.getWithLocInContext(Context),
  3755. *MemberOrBase, IdLoc);
  3756. if (BaseType.isNull())
  3757. return true;
  3758. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3759. DependentNameTypeLoc TL =
  3760. TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
  3761. if (!TL.isNull()) {
  3762. TL.setNameLoc(IdLoc);
  3763. TL.setElaboratedKeywordLoc(SourceLocation());
  3764. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3765. }
  3766. R.clear();
  3767. R.setLookupName(MemberOrBase);
  3768. }
  3769. }
  3770. // If no results were found, try to correct typos.
  3771. TypoCorrection Corr;
  3772. MemInitializerValidatorCCC CCC(ClassDecl);
  3773. if (R.empty() && BaseType.isNull() &&
  3774. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  3775. CCC, CTK_ErrorRecovery, ClassDecl))) {
  3776. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  3777. // We have found a non-static data member with a similar
  3778. // name to what was typed; complain and initialize that
  3779. // member.
  3780. diagnoseTypo(Corr,
  3781. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3782. << MemberOrBase << true);
  3783. return BuildMemberInitializer(Member, Init, IdLoc);
  3784. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  3785. const CXXBaseSpecifier *DirectBaseSpec;
  3786. const CXXBaseSpecifier *VirtualBaseSpec;
  3787. if (FindBaseInitializer(*this, ClassDecl,
  3788. Context.getTypeDeclType(Type),
  3789. DirectBaseSpec, VirtualBaseSpec)) {
  3790. // We have found a direct or virtual base class with a
  3791. // similar name to what was typed; complain and initialize
  3792. // that base class.
  3793. diagnoseTypo(Corr,
  3794. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  3795. << MemberOrBase << false,
  3796. PDiag() /*Suppress note, we provide our own.*/);
  3797. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  3798. : VirtualBaseSpec;
  3799. Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
  3800. << BaseSpec->getType() << BaseSpec->getSourceRange();
  3801. TyD = Type;
  3802. }
  3803. }
  3804. }
  3805. if (!TyD && BaseType.isNull()) {
  3806. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  3807. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  3808. return true;
  3809. }
  3810. }
  3811. if (BaseType.isNull()) {
  3812. BaseType = Context.getTypeDeclType(TyD);
  3813. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  3814. if (SS.isSet()) {
  3815. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  3816. BaseType);
  3817. TInfo = Context.CreateTypeSourceInfo(BaseType);
  3818. ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
  3819. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
  3820. TL.setElaboratedKeywordLoc(SourceLocation());
  3821. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  3822. }
  3823. }
  3824. }
  3825. if (!TInfo)
  3826. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  3827. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  3828. }
  3829. MemInitResult
  3830. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  3831. SourceLocation IdLoc) {
  3832. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  3833. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  3834. assert((DirectMember || IndirectMember) &&
  3835. "Member must be a FieldDecl or IndirectFieldDecl");
  3836. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3837. return true;
  3838. if (Member->isInvalidDecl())
  3839. return true;
  3840. MultiExprArg Args;
  3841. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3842. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3843. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  3844. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  3845. } else {
  3846. // Template instantiation doesn't reconstruct ParenListExprs for us.
  3847. Args = Init;
  3848. }
  3849. SourceRange InitRange = Init->getSourceRange();
  3850. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  3851. // Can't check initialization for a member of dependent type or when
  3852. // any of the arguments are type-dependent expressions.
  3853. DiscardCleanupsInEvaluationContext();
  3854. } else {
  3855. bool InitList = false;
  3856. if (isa<InitListExpr>(Init)) {
  3857. InitList = true;
  3858. Args = Init;
  3859. }
  3860. // Initialize the member.
  3861. InitializedEntity MemberEntity =
  3862. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  3863. : InitializedEntity::InitializeMember(IndirectMember,
  3864. nullptr);
  3865. InitializationKind Kind =
  3866. InitList ? InitializationKind::CreateDirectList(
  3867. IdLoc, Init->getBeginLoc(), Init->getEndLoc())
  3868. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  3869. InitRange.getEnd());
  3870. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  3871. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  3872. nullptr);
  3873. if (!MemberInit.isInvalid()) {
  3874. // C++11 [class.base.init]p7:
  3875. // The initialization of each base and member constitutes a
  3876. // full-expression.
  3877. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
  3878. /*DiscardedValue*/ false);
  3879. }
  3880. if (MemberInit.isInvalid()) {
  3881. // Args were sensible expressions but we couldn't initialize the member
  3882. // from them. Preserve them in a RecoveryExpr instead.
  3883. Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
  3884. Member->getType())
  3885. .get();
  3886. if (!Init)
  3887. return true;
  3888. } else {
  3889. Init = MemberInit.get();
  3890. }
  3891. }
  3892. if (DirectMember) {
  3893. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  3894. InitRange.getBegin(), Init,
  3895. InitRange.getEnd());
  3896. } else {
  3897. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  3898. InitRange.getBegin(), Init,
  3899. InitRange.getEnd());
  3900. }
  3901. }
  3902. MemInitResult
  3903. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  3904. CXXRecordDecl *ClassDecl) {
  3905. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3906. if (!LangOpts.CPlusPlus11)
  3907. return Diag(NameLoc, diag::err_delegating_ctor)
  3908. << TInfo->getTypeLoc().getLocalSourceRange();
  3909. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  3910. bool InitList = true;
  3911. MultiExprArg Args = Init;
  3912. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  3913. InitList = false;
  3914. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  3915. }
  3916. SourceRange InitRange = Init->getSourceRange();
  3917. // Initialize the object.
  3918. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  3919. QualType(ClassDecl->getTypeForDecl(), 0));
  3920. InitializationKind Kind =
  3921. InitList ? InitializationKind::CreateDirectList(
  3922. NameLoc, Init->getBeginLoc(), Init->getEndLoc())
  3923. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  3924. InitRange.getEnd());
  3925. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  3926. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  3927. Args, nullptr);
  3928. if (!DelegationInit.isInvalid()) {
  3929. assert((DelegationInit.get()->containsErrors() ||
  3930. cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
  3931. "Delegating constructor with no target?");
  3932. // C++11 [class.base.init]p7:
  3933. // The initialization of each base and member constitutes a
  3934. // full-expression.
  3935. DelegationInit = ActOnFinishFullExpr(
  3936. DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
  3937. }
  3938. if (DelegationInit.isInvalid()) {
  3939. DelegationInit =
  3940. CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
  3941. QualType(ClassDecl->getTypeForDecl(), 0));
  3942. if (DelegationInit.isInvalid())
  3943. return true;
  3944. } else {
  3945. // If we are in a dependent context, template instantiation will
  3946. // perform this type-checking again. Just save the arguments that we
  3947. // received in a ParenListExpr.
  3948. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  3949. // of the information that we have about the base
  3950. // initializer. However, deconstructing the ASTs is a dicey process,
  3951. // and this approach is far more likely to get the corner cases right.
  3952. if (CurContext->isDependentContext())
  3953. DelegationInit = Init;
  3954. }
  3955. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  3956. DelegationInit.getAs<Expr>(),
  3957. InitRange.getEnd());
  3958. }
  3959. MemInitResult
  3960. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  3961. Expr *Init, CXXRecordDecl *ClassDecl,
  3962. SourceLocation EllipsisLoc) {
  3963. SourceLocation BaseLoc
  3964. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  3965. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  3966. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  3967. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  3968. // C++ [class.base.init]p2:
  3969. // [...] Unless the mem-initializer-id names a nonstatic data
  3970. // member of the constructor's class or a direct or virtual base
  3971. // of that class, the mem-initializer is ill-formed. A
  3972. // mem-initializer-list can initialize a base class using any
  3973. // name that denotes that base class type.
  3974. // We can store the initializers in "as-written" form and delay analysis until
  3975. // instantiation if the constructor is dependent. But not for dependent
  3976. // (broken) code in a non-template! SetCtorInitializers does not expect this.
  3977. bool Dependent = CurContext->isDependentContext() &&
  3978. (BaseType->isDependentType() || Init->isTypeDependent());
  3979. SourceRange InitRange = Init->getSourceRange();
  3980. if (EllipsisLoc.isValid()) {
  3981. // This is a pack expansion.
  3982. if (!BaseType->containsUnexpandedParameterPack()) {
  3983. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  3984. << SourceRange(BaseLoc, InitRange.getEnd());
  3985. EllipsisLoc = SourceLocation();
  3986. }
  3987. } else {
  3988. // Check for any unexpanded parameter packs.
  3989. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  3990. return true;
  3991. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  3992. return true;
  3993. }
  3994. // Check for direct and virtual base classes.
  3995. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  3996. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  3997. if (!Dependent) {
  3998. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  3999. BaseType))
  4000. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  4001. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  4002. VirtualBaseSpec);
  4003. // C++ [base.class.init]p2:
  4004. // Unless the mem-initializer-id names a nonstatic data member of the
  4005. // constructor's class or a direct or virtual base of that class, the
  4006. // mem-initializer is ill-formed.
  4007. if (!DirectBaseSpec && !VirtualBaseSpec) {
  4008. // If the class has any dependent bases, then it's possible that
  4009. // one of those types will resolve to the same type as
  4010. // BaseType. Therefore, just treat this as a dependent base
  4011. // class initialization. FIXME: Should we try to check the
  4012. // initialization anyway? It seems odd.
  4013. if (ClassDecl->hasAnyDependentBases())
  4014. Dependent = true;
  4015. else
  4016. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  4017. << BaseType << Context.getTypeDeclType(ClassDecl)
  4018. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  4019. }
  4020. }
  4021. if (Dependent) {
  4022. DiscardCleanupsInEvaluationContext();
  4023. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  4024. /*IsVirtual=*/false,
  4025. InitRange.getBegin(), Init,
  4026. InitRange.getEnd(), EllipsisLoc);
  4027. }
  4028. // C++ [base.class.init]p2:
  4029. // If a mem-initializer-id is ambiguous because it designates both
  4030. // a direct non-virtual base class and an inherited virtual base
  4031. // class, the mem-initializer is ill-formed.
  4032. if (DirectBaseSpec && VirtualBaseSpec)
  4033. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  4034. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  4035. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  4036. if (!BaseSpec)
  4037. BaseSpec = VirtualBaseSpec;
  4038. // Initialize the base.
  4039. bool InitList = true;
  4040. MultiExprArg Args = Init;
  4041. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  4042. InitList = false;
  4043. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  4044. }
  4045. InitializedEntity BaseEntity =
  4046. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  4047. InitializationKind Kind =
  4048. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  4049. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  4050. InitRange.getEnd());
  4051. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  4052. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  4053. if (!BaseInit.isInvalid()) {
  4054. // C++11 [class.base.init]p7:
  4055. // The initialization of each base and member constitutes a
  4056. // full-expression.
  4057. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
  4058. /*DiscardedValue*/ false);
  4059. }
  4060. if (BaseInit.isInvalid()) {
  4061. BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
  4062. Args, BaseType);
  4063. if (BaseInit.isInvalid())
  4064. return true;
  4065. } else {
  4066. // If we are in a dependent context, template instantiation will
  4067. // perform this type-checking again. Just save the arguments that we
  4068. // received in a ParenListExpr.
  4069. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  4070. // of the information that we have about the base
  4071. // initializer. However, deconstructing the ASTs is a dicey process,
  4072. // and this approach is far more likely to get the corner cases right.
  4073. if (CurContext->isDependentContext())
  4074. BaseInit = Init;
  4075. }
  4076. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  4077. BaseSpec->isVirtual(),
  4078. InitRange.getBegin(),
  4079. BaseInit.getAs<Expr>(),
  4080. InitRange.getEnd(), EllipsisLoc);
  4081. }
  4082. // Create a static_cast\<T&&>(expr).
  4083. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  4084. if (T.isNull()) T = E->getType();
  4085. QualType TargetType = SemaRef.BuildReferenceType(
  4086. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  4087. SourceLocation ExprLoc = E->getBeginLoc();
  4088. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  4089. TargetType, ExprLoc);
  4090. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  4091. SourceRange(ExprLoc, ExprLoc),
  4092. E->getSourceRange()).get();
  4093. }
  4094. /// ImplicitInitializerKind - How an implicit base or member initializer should
  4095. /// initialize its base or member.
  4096. enum ImplicitInitializerKind {
  4097. IIK_Default,
  4098. IIK_Copy,
  4099. IIK_Move,
  4100. IIK_Inherit
  4101. };
  4102. static bool
  4103. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  4104. ImplicitInitializerKind ImplicitInitKind,
  4105. CXXBaseSpecifier *BaseSpec,
  4106. bool IsInheritedVirtualBase,
  4107. CXXCtorInitializer *&CXXBaseInit) {
  4108. InitializedEntity InitEntity
  4109. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  4110. IsInheritedVirtualBase);
  4111. ExprResult BaseInit;
  4112. switch (ImplicitInitKind) {
  4113. case IIK_Inherit:
  4114. case IIK_Default: {
  4115. InitializationKind InitKind
  4116. = InitializationKind::CreateDefault(Constructor->getLocation());
  4117. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  4118. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  4119. break;
  4120. }
  4121. case IIK_Move:
  4122. case IIK_Copy: {
  4123. bool Moving = ImplicitInitKind == IIK_Move;
  4124. ParmVarDecl *Param = Constructor->getParamDecl(0);
  4125. QualType ParamType = Param->getType().getNonReferenceType();
  4126. Expr *CopyCtorArg =
  4127. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4128. SourceLocation(), Param, false,
  4129. Constructor->getLocation(), ParamType,
  4130. VK_LValue, nullptr);
  4131. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  4132. // Cast to the base class to avoid ambiguities.
  4133. QualType ArgTy =
  4134. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  4135. ParamType.getQualifiers());
  4136. if (Moving) {
  4137. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  4138. }
  4139. CXXCastPath BasePath;
  4140. BasePath.push_back(BaseSpec);
  4141. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  4142. CK_UncheckedDerivedToBase,
  4143. Moving ? VK_XValue : VK_LValue,
  4144. &BasePath).get();
  4145. InitializationKind InitKind
  4146. = InitializationKind::CreateDirect(Constructor->getLocation(),
  4147. SourceLocation(), SourceLocation());
  4148. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4149. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  4150. break;
  4151. }
  4152. }
  4153. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  4154. if (BaseInit.isInvalid())
  4155. return true;
  4156. CXXBaseInit =
  4157. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4158. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  4159. SourceLocation()),
  4160. BaseSpec->isVirtual(),
  4161. SourceLocation(),
  4162. BaseInit.getAs<Expr>(),
  4163. SourceLocation(),
  4164. SourceLocation());
  4165. return false;
  4166. }
  4167. static bool RefersToRValueRef(Expr *MemRef) {
  4168. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  4169. return Referenced->getType()->isRValueReferenceType();
  4170. }
  4171. static bool
  4172. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  4173. ImplicitInitializerKind ImplicitInitKind,
  4174. FieldDecl *Field, IndirectFieldDecl *Indirect,
  4175. CXXCtorInitializer *&CXXMemberInit) {
  4176. if (Field->isInvalidDecl())
  4177. return true;
  4178. SourceLocation Loc = Constructor->getLocation();
  4179. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  4180. bool Moving = ImplicitInitKind == IIK_Move;
  4181. ParmVarDecl *Param = Constructor->getParamDecl(0);
  4182. QualType ParamType = Param->getType().getNonReferenceType();
  4183. // Suppress copying zero-width bitfields.
  4184. if (Field->isZeroLengthBitField(SemaRef.Context))
  4185. return false;
  4186. Expr *MemberExprBase =
  4187. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  4188. SourceLocation(), Param, false,
  4189. Loc, ParamType, VK_LValue, nullptr);
  4190. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  4191. if (Moving) {
  4192. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  4193. }
  4194. // Build a reference to this field within the parameter.
  4195. CXXScopeSpec SS;
  4196. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  4197. Sema::LookupMemberName);
  4198. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  4199. : cast<ValueDecl>(Field), AS_public);
  4200. MemberLookup.resolveKind();
  4201. ExprResult CtorArg
  4202. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  4203. ParamType, Loc,
  4204. /*IsArrow=*/false,
  4205. SS,
  4206. /*TemplateKWLoc=*/SourceLocation(),
  4207. /*FirstQualifierInScope=*/nullptr,
  4208. MemberLookup,
  4209. /*TemplateArgs=*/nullptr,
  4210. /*S*/nullptr);
  4211. if (CtorArg.isInvalid())
  4212. return true;
  4213. // C++11 [class.copy]p15:
  4214. // - if a member m has rvalue reference type T&&, it is direct-initialized
  4215. // with static_cast<T&&>(x.m);
  4216. if (RefersToRValueRef(CtorArg.get())) {
  4217. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  4218. }
  4219. InitializedEntity Entity =
  4220. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4221. /*Implicit*/ true)
  4222. : InitializedEntity::InitializeMember(Field, nullptr,
  4223. /*Implicit*/ true);
  4224. // Direct-initialize to use the copy constructor.
  4225. InitializationKind InitKind =
  4226. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  4227. Expr *CtorArgE = CtorArg.getAs<Expr>();
  4228. InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
  4229. ExprResult MemberInit =
  4230. InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
  4231. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4232. if (MemberInit.isInvalid())
  4233. return true;
  4234. if (Indirect)
  4235. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4236. SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4237. else
  4238. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
  4239. SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
  4240. return false;
  4241. }
  4242. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  4243. "Unhandled implicit init kind!");
  4244. QualType FieldBaseElementType =
  4245. SemaRef.Context.getBaseElementType(Field->getType());
  4246. if (FieldBaseElementType->isRecordType()) {
  4247. InitializedEntity InitEntity =
  4248. Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
  4249. /*Implicit*/ true)
  4250. : InitializedEntity::InitializeMember(Field, nullptr,
  4251. /*Implicit*/ true);
  4252. InitializationKind InitKind =
  4253. InitializationKind::CreateDefault(Loc);
  4254. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  4255. ExprResult MemberInit =
  4256. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  4257. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  4258. if (MemberInit.isInvalid())
  4259. return true;
  4260. if (Indirect)
  4261. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4262. Indirect, Loc,
  4263. Loc,
  4264. MemberInit.get(),
  4265. Loc);
  4266. else
  4267. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  4268. Field, Loc, Loc,
  4269. MemberInit.get(),
  4270. Loc);
  4271. return false;
  4272. }
  4273. if (!Field->getParent()->isUnion()) {
  4274. if (FieldBaseElementType->isReferenceType()) {
  4275. SemaRef.Diag(Constructor->getLocation(),
  4276. diag::err_uninitialized_member_in_ctor)
  4277. << (int)Constructor->isImplicit()
  4278. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4279. << 0 << Field->getDeclName();
  4280. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4281. return true;
  4282. }
  4283. if (FieldBaseElementType.isConstQualified()) {
  4284. SemaRef.Diag(Constructor->getLocation(),
  4285. diag::err_uninitialized_member_in_ctor)
  4286. << (int)Constructor->isImplicit()
  4287. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  4288. << 1 << Field->getDeclName();
  4289. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  4290. return true;
  4291. }
  4292. }
  4293. if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
  4294. // ARC and Weak:
  4295. // Default-initialize Objective-C pointers to NULL.
  4296. CXXMemberInit
  4297. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  4298. Loc, Loc,
  4299. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  4300. Loc);
  4301. return false;
  4302. }
  4303. // Nothing to initialize.
  4304. CXXMemberInit = nullptr;
  4305. return false;
  4306. }
  4307. namespace {
  4308. struct BaseAndFieldInfo {
  4309. Sema &S;
  4310. CXXConstructorDecl *Ctor;
  4311. bool AnyErrorsInInits;
  4312. ImplicitInitializerKind IIK;
  4313. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  4314. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  4315. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  4316. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  4317. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  4318. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  4319. if (Ctor->getInheritedConstructor())
  4320. IIK = IIK_Inherit;
  4321. else if (Generated && Ctor->isCopyConstructor())
  4322. IIK = IIK_Copy;
  4323. else if (Generated && Ctor->isMoveConstructor())
  4324. IIK = IIK_Move;
  4325. else
  4326. IIK = IIK_Default;
  4327. }
  4328. bool isImplicitCopyOrMove() const {
  4329. switch (IIK) {
  4330. case IIK_Copy:
  4331. case IIK_Move:
  4332. return true;
  4333. case IIK_Default:
  4334. case IIK_Inherit:
  4335. return false;
  4336. }
  4337. llvm_unreachable("Invalid ImplicitInitializerKind!");
  4338. }
  4339. bool addFieldInitializer(CXXCtorInitializer *Init) {
  4340. AllToInit.push_back(Init);
  4341. // Check whether this initializer makes the field "used".
  4342. if (Init->getInit()->HasSideEffects(S.Context))
  4343. S.UnusedPrivateFields.remove(Init->getAnyMember());
  4344. return false;
  4345. }
  4346. bool isInactiveUnionMember(FieldDecl *Field) {
  4347. RecordDecl *Record = Field->getParent();
  4348. if (!Record->isUnion())
  4349. return false;
  4350. if (FieldDecl *Active =
  4351. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  4352. return Active != Field->getCanonicalDecl();
  4353. // In an implicit copy or move constructor, ignore any in-class initializer.
  4354. if (isImplicitCopyOrMove())
  4355. return true;
  4356. // If there's no explicit initialization, the field is active only if it
  4357. // has an in-class initializer...
  4358. if (Field->hasInClassInitializer())
  4359. return false;
  4360. // ... or it's an anonymous struct or union whose class has an in-class
  4361. // initializer.
  4362. if (!Field->isAnonymousStructOrUnion())
  4363. return true;
  4364. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  4365. return !FieldRD->hasInClassInitializer();
  4366. }
  4367. /// Determine whether the given field is, or is within, a union member
  4368. /// that is inactive (because there was an initializer given for a different
  4369. /// member of the union, or because the union was not initialized at all).
  4370. bool isWithinInactiveUnionMember(FieldDecl *Field,
  4371. IndirectFieldDecl *Indirect) {
  4372. if (!Indirect)
  4373. return isInactiveUnionMember(Field);
  4374. for (auto *C : Indirect->chain()) {
  4375. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  4376. if (Field && isInactiveUnionMember(Field))
  4377. return true;
  4378. }
  4379. return false;
  4380. }
  4381. };
  4382. }
  4383. /// Determine whether the given type is an incomplete or zero-lenfgth
  4384. /// array type.
  4385. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  4386. if (T->isIncompleteArrayType())
  4387. return true;
  4388. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  4389. if (!ArrayT->getSize())
  4390. return true;
  4391. T = ArrayT->getElementType();
  4392. }
  4393. return false;
  4394. }
  4395. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  4396. FieldDecl *Field,
  4397. IndirectFieldDecl *Indirect = nullptr) {
  4398. if (Field->isInvalidDecl())
  4399. return false;
  4400. // Overwhelmingly common case: we have a direct initializer for this field.
  4401. if (CXXCtorInitializer *Init =
  4402. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  4403. return Info.addFieldInitializer(Init);
  4404. // C++11 [class.base.init]p8:
  4405. // if the entity is a non-static data member that has a
  4406. // brace-or-equal-initializer and either
  4407. // -- the constructor's class is a union and no other variant member of that
  4408. // union is designated by a mem-initializer-id or
  4409. // -- the constructor's class is not a union, and, if the entity is a member
  4410. // of an anonymous union, no other member of that union is designated by
  4411. // a mem-initializer-id,
  4412. // the entity is initialized as specified in [dcl.init].
  4413. //
  4414. // We also apply the same rules to handle anonymous structs within anonymous
  4415. // unions.
  4416. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  4417. return false;
  4418. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  4419. ExprResult DIE =
  4420. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  4421. if (DIE.isInvalid())
  4422. return true;
  4423. auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
  4424. SemaRef.checkInitializerLifetime(Entity, DIE.get());
  4425. CXXCtorInitializer *Init;
  4426. if (Indirect)
  4427. Init = new (SemaRef.Context)
  4428. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  4429. SourceLocation(), DIE.get(), SourceLocation());
  4430. else
  4431. Init = new (SemaRef.Context)
  4432. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  4433. SourceLocation(), DIE.get(), SourceLocation());
  4434. return Info.addFieldInitializer(Init);
  4435. }
  4436. // Don't initialize incomplete or zero-length arrays.
  4437. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  4438. return false;
  4439. // Don't try to build an implicit initializer if there were semantic
  4440. // errors in any of the initializers (and therefore we might be
  4441. // missing some that the user actually wrote).
  4442. if (Info.AnyErrorsInInits)
  4443. return false;
  4444. CXXCtorInitializer *Init = nullptr;
  4445. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  4446. Indirect, Init))
  4447. return true;
  4448. if (!Init)
  4449. return false;
  4450. return Info.addFieldInitializer(Init);
  4451. }
  4452. bool
  4453. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  4454. CXXCtorInitializer *Initializer) {
  4455. assert(Initializer->isDelegatingInitializer());
  4456. Constructor->setNumCtorInitializers(1);
  4457. CXXCtorInitializer **initializer =
  4458. new (Context) CXXCtorInitializer*[1];
  4459. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  4460. Constructor->setCtorInitializers(initializer);
  4461. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  4462. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  4463. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  4464. }
  4465. DelegatingCtorDecls.push_back(Constructor);
  4466. DiagnoseUninitializedFields(*this, Constructor);
  4467. return false;
  4468. }
  4469. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  4470. ArrayRef<CXXCtorInitializer *> Initializers) {
  4471. if (Constructor->isDependentContext()) {
  4472. // Just store the initializers as written, they will be checked during
  4473. // instantiation.
  4474. if (!Initializers.empty()) {
  4475. Constructor->setNumCtorInitializers(Initializers.size());
  4476. CXXCtorInitializer **baseOrMemberInitializers =
  4477. new (Context) CXXCtorInitializer*[Initializers.size()];
  4478. memcpy(baseOrMemberInitializers, Initializers.data(),
  4479. Initializers.size() * sizeof(CXXCtorInitializer*));
  4480. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4481. }
  4482. // Let template instantiation know whether we had errors.
  4483. if (AnyErrors)
  4484. Constructor->setInvalidDecl();
  4485. return false;
  4486. }
  4487. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  4488. // We need to build the initializer AST according to order of construction
  4489. // and not what user specified in the Initializers list.
  4490. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  4491. if (!ClassDecl)
  4492. return true;
  4493. bool HadError = false;
  4494. for (unsigned i = 0; i < Initializers.size(); i++) {
  4495. CXXCtorInitializer *Member = Initializers[i];
  4496. if (Member->isBaseInitializer())
  4497. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  4498. else {
  4499. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  4500. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  4501. for (auto *C : F->chain()) {
  4502. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  4503. if (FD && FD->getParent()->isUnion())
  4504. Info.ActiveUnionMember.insert(std::make_pair(
  4505. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4506. }
  4507. } else if (FieldDecl *FD = Member->getMember()) {
  4508. if (FD->getParent()->isUnion())
  4509. Info.ActiveUnionMember.insert(std::make_pair(
  4510. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  4511. }
  4512. }
  4513. }
  4514. // Keep track of the direct virtual bases.
  4515. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  4516. for (auto &I : ClassDecl->bases()) {
  4517. if (I.isVirtual())
  4518. DirectVBases.insert(&I);
  4519. }
  4520. // Push virtual bases before others.
  4521. for (auto &VBase : ClassDecl->vbases()) {
  4522. if (CXXCtorInitializer *Value
  4523. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  4524. // [class.base.init]p7, per DR257:
  4525. // A mem-initializer where the mem-initializer-id names a virtual base
  4526. // class is ignored during execution of a constructor of any class that
  4527. // is not the most derived class.
  4528. if (ClassDecl->isAbstract()) {
  4529. // FIXME: Provide a fixit to remove the base specifier. This requires
  4530. // tracking the location of the associated comma for a base specifier.
  4531. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  4532. << VBase.getType() << ClassDecl;
  4533. DiagnoseAbstractType(ClassDecl);
  4534. }
  4535. Info.AllToInit.push_back(Value);
  4536. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  4537. // [class.base.init]p8, per DR257:
  4538. // If a given [...] base class is not named by a mem-initializer-id
  4539. // [...] and the entity is not a virtual base class of an abstract
  4540. // class, then [...] the entity is default-initialized.
  4541. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  4542. CXXCtorInitializer *CXXBaseInit;
  4543. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4544. &VBase, IsInheritedVirtualBase,
  4545. CXXBaseInit)) {
  4546. HadError = true;
  4547. continue;
  4548. }
  4549. Info.AllToInit.push_back(CXXBaseInit);
  4550. }
  4551. }
  4552. // Non-virtual bases.
  4553. for (auto &Base : ClassDecl->bases()) {
  4554. // Virtuals are in the virtual base list and already constructed.
  4555. if (Base.isVirtual())
  4556. continue;
  4557. if (CXXCtorInitializer *Value
  4558. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  4559. Info.AllToInit.push_back(Value);
  4560. } else if (!AnyErrors) {
  4561. CXXCtorInitializer *CXXBaseInit;
  4562. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  4563. &Base, /*IsInheritedVirtualBase=*/false,
  4564. CXXBaseInit)) {
  4565. HadError = true;
  4566. continue;
  4567. }
  4568. Info.AllToInit.push_back(CXXBaseInit);
  4569. }
  4570. }
  4571. // Fields.
  4572. for (auto *Mem : ClassDecl->decls()) {
  4573. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  4574. // C++ [class.bit]p2:
  4575. // A declaration for a bit-field that omits the identifier declares an
  4576. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  4577. // initialized.
  4578. if (F->isUnnamedBitfield())
  4579. continue;
  4580. // If we're not generating the implicit copy/move constructor, then we'll
  4581. // handle anonymous struct/union fields based on their individual
  4582. // indirect fields.
  4583. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  4584. continue;
  4585. if (CollectFieldInitializer(*this, Info, F))
  4586. HadError = true;
  4587. continue;
  4588. }
  4589. // Beyond this point, we only consider default initialization.
  4590. if (Info.isImplicitCopyOrMove())
  4591. continue;
  4592. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  4593. if (F->getType()->isIncompleteArrayType()) {
  4594. assert(ClassDecl->hasFlexibleArrayMember() &&
  4595. "Incomplete array type is not valid");
  4596. continue;
  4597. }
  4598. // Initialize each field of an anonymous struct individually.
  4599. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  4600. HadError = true;
  4601. continue;
  4602. }
  4603. }
  4604. unsigned NumInitializers = Info.AllToInit.size();
  4605. if (NumInitializers > 0) {
  4606. Constructor->setNumCtorInitializers(NumInitializers);
  4607. CXXCtorInitializer **baseOrMemberInitializers =
  4608. new (Context) CXXCtorInitializer*[NumInitializers];
  4609. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  4610. NumInitializers * sizeof(CXXCtorInitializer*));
  4611. Constructor->setCtorInitializers(baseOrMemberInitializers);
  4612. // Constructors implicitly reference the base and member
  4613. // destructors.
  4614. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  4615. Constructor->getParent());
  4616. }
  4617. return HadError;
  4618. }
  4619. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  4620. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  4621. const RecordDecl *RD = RT->getDecl();
  4622. if (RD->isAnonymousStructOrUnion()) {
  4623. for (auto *Field : RD->fields())
  4624. PopulateKeysForFields(Field, IdealInits);
  4625. return;
  4626. }
  4627. }
  4628. IdealInits.push_back(Field->getCanonicalDecl());
  4629. }
  4630. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  4631. return Context.getCanonicalType(BaseType).getTypePtr();
  4632. }
  4633. static const void *GetKeyForMember(ASTContext &Context,
  4634. CXXCtorInitializer *Member) {
  4635. if (!Member->isAnyMemberInitializer())
  4636. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  4637. return Member->getAnyMember()->getCanonicalDecl();
  4638. }
  4639. static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
  4640. const CXXCtorInitializer *Previous,
  4641. const CXXCtorInitializer *Current) {
  4642. if (Previous->isAnyMemberInitializer())
  4643. Diag << 0 << Previous->getAnyMember();
  4644. else
  4645. Diag << 1 << Previous->getTypeSourceInfo()->getType();
  4646. if (Current->isAnyMemberInitializer())
  4647. Diag << 0 << Current->getAnyMember();
  4648. else
  4649. Diag << 1 << Current->getTypeSourceInfo()->getType();
  4650. }
  4651. static void DiagnoseBaseOrMemInitializerOrder(
  4652. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  4653. ArrayRef<CXXCtorInitializer *> Inits) {
  4654. if (Constructor->getDeclContext()->isDependentContext())
  4655. return;
  4656. // Don't check initializers order unless the warning is enabled at the
  4657. // location of at least one initializer.
  4658. bool ShouldCheckOrder = false;
  4659. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4660. CXXCtorInitializer *Init = Inits[InitIndex];
  4661. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  4662. Init->getSourceLocation())) {
  4663. ShouldCheckOrder = true;
  4664. break;
  4665. }
  4666. }
  4667. if (!ShouldCheckOrder)
  4668. return;
  4669. // Build the list of bases and members in the order that they'll
  4670. // actually be initialized. The explicit initializers should be in
  4671. // this same order but may be missing things.
  4672. SmallVector<const void*, 32> IdealInitKeys;
  4673. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  4674. // 1. Virtual bases.
  4675. for (const auto &VBase : ClassDecl->vbases())
  4676. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  4677. // 2. Non-virtual bases.
  4678. for (const auto &Base : ClassDecl->bases()) {
  4679. if (Base.isVirtual())
  4680. continue;
  4681. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  4682. }
  4683. // 3. Direct fields.
  4684. for (auto *Field : ClassDecl->fields()) {
  4685. if (Field->isUnnamedBitfield())
  4686. continue;
  4687. PopulateKeysForFields(Field, IdealInitKeys);
  4688. }
  4689. unsigned NumIdealInits = IdealInitKeys.size();
  4690. unsigned IdealIndex = 0;
  4691. // Track initializers that are in an incorrect order for either a warning or
  4692. // note if multiple ones occur.
  4693. SmallVector<unsigned> WarnIndexes;
  4694. // Correlates the index of an initializer in the init-list to the index of
  4695. // the field/base in the class.
  4696. SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
  4697. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  4698. const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
  4699. // Scan forward to try to find this initializer in the idealized
  4700. // initializers list.
  4701. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  4702. if (InitKey == IdealInitKeys[IdealIndex])
  4703. break;
  4704. // If we didn't find this initializer, it must be because we
  4705. // scanned past it on a previous iteration. That can only
  4706. // happen if we're out of order; emit a warning.
  4707. if (IdealIndex == NumIdealInits && InitIndex) {
  4708. WarnIndexes.push_back(InitIndex);
  4709. // Move back to the initializer's location in the ideal list.
  4710. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  4711. if (InitKey == IdealInitKeys[IdealIndex])
  4712. break;
  4713. assert(IdealIndex < NumIdealInits &&
  4714. "initializer not found in initializer list");
  4715. }
  4716. CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
  4717. }
  4718. if (WarnIndexes.empty())
  4719. return;
  4720. // Sort based on the ideal order, first in the pair.
  4721. llvm::sort(CorrelatedInitOrder,
  4722. [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
  4723. // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
  4724. // emit the diagnostic before we can try adding notes.
  4725. {
  4726. Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
  4727. Inits[WarnIndexes.front() - 1]->getSourceLocation(),
  4728. WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
  4729. : diag::warn_some_initializers_out_of_order);
  4730. for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
  4731. if (CorrelatedInitOrder[I].second == I)
  4732. continue;
  4733. // Ideally we would be using InsertFromRange here, but clang doesn't
  4734. // appear to handle InsertFromRange correctly when the source range is
  4735. // modified by another fix-it.
  4736. D << FixItHint::CreateReplacement(
  4737. Inits[I]->getSourceRange(),
  4738. Lexer::getSourceText(
  4739. CharSourceRange::getTokenRange(
  4740. Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
  4741. SemaRef.getSourceManager(), SemaRef.getLangOpts()));
  4742. }
  4743. // If there is only 1 item out of order, the warning expects the name and
  4744. // type of each being added to it.
  4745. if (WarnIndexes.size() == 1) {
  4746. AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
  4747. Inits[WarnIndexes.front()]);
  4748. return;
  4749. }
  4750. }
  4751. // More than 1 item to warn, create notes letting the user know which ones
  4752. // are bad.
  4753. for (unsigned WarnIndex : WarnIndexes) {
  4754. const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
  4755. auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
  4756. diag::note_initializer_out_of_order);
  4757. AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
  4758. D << PrevInit->getSourceRange();
  4759. }
  4760. }
  4761. namespace {
  4762. bool CheckRedundantInit(Sema &S,
  4763. CXXCtorInitializer *Init,
  4764. CXXCtorInitializer *&PrevInit) {
  4765. if (!PrevInit) {
  4766. PrevInit = Init;
  4767. return false;
  4768. }
  4769. if (FieldDecl *Field = Init->getAnyMember())
  4770. S.Diag(Init->getSourceLocation(),
  4771. diag::err_multiple_mem_initialization)
  4772. << Field->getDeclName()
  4773. << Init->getSourceRange();
  4774. else {
  4775. const Type *BaseClass = Init->getBaseClass();
  4776. assert(BaseClass && "neither field nor base");
  4777. S.Diag(Init->getSourceLocation(),
  4778. diag::err_multiple_base_initialization)
  4779. << QualType(BaseClass, 0)
  4780. << Init->getSourceRange();
  4781. }
  4782. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  4783. << 0 << PrevInit->getSourceRange();
  4784. return true;
  4785. }
  4786. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  4787. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  4788. bool CheckRedundantUnionInit(Sema &S,
  4789. CXXCtorInitializer *Init,
  4790. RedundantUnionMap &Unions) {
  4791. FieldDecl *Field = Init->getAnyMember();
  4792. RecordDecl *Parent = Field->getParent();
  4793. NamedDecl *Child = Field;
  4794. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  4795. if (Parent->isUnion()) {
  4796. UnionEntry &En = Unions[Parent];
  4797. if (En.first && En.first != Child) {
  4798. S.Diag(Init->getSourceLocation(),
  4799. diag::err_multiple_mem_union_initialization)
  4800. << Field->getDeclName()
  4801. << Init->getSourceRange();
  4802. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  4803. << 0 << En.second->getSourceRange();
  4804. return true;
  4805. }
  4806. if (!En.first) {
  4807. En.first = Child;
  4808. En.second = Init;
  4809. }
  4810. if (!Parent->isAnonymousStructOrUnion())
  4811. return false;
  4812. }
  4813. Child = Parent;
  4814. Parent = cast<RecordDecl>(Parent->getDeclContext());
  4815. }
  4816. return false;
  4817. }
  4818. } // namespace
  4819. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  4820. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  4821. SourceLocation ColonLoc,
  4822. ArrayRef<CXXCtorInitializer*> MemInits,
  4823. bool AnyErrors) {
  4824. if (!ConstructorDecl)
  4825. return;
  4826. AdjustDeclIfTemplate(ConstructorDecl);
  4827. CXXConstructorDecl *Constructor
  4828. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  4829. if (!Constructor) {
  4830. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  4831. return;
  4832. }
  4833. // Mapping for the duplicate initializers check.
  4834. // For member initializers, this is keyed with a FieldDecl*.
  4835. // For base initializers, this is keyed with a Type*.
  4836. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  4837. // Mapping for the inconsistent anonymous-union initializers check.
  4838. RedundantUnionMap MemberUnions;
  4839. bool HadError = false;
  4840. for (unsigned i = 0; i < MemInits.size(); i++) {
  4841. CXXCtorInitializer *Init = MemInits[i];
  4842. // Set the source order index.
  4843. Init->setSourceOrder(i);
  4844. if (Init->isAnyMemberInitializer()) {
  4845. const void *Key = GetKeyForMember(Context, Init);
  4846. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  4847. CheckRedundantUnionInit(*this, Init, MemberUnions))
  4848. HadError = true;
  4849. } else if (Init->isBaseInitializer()) {
  4850. const void *Key = GetKeyForMember(Context, Init);
  4851. if (CheckRedundantInit(*this, Init, Members[Key]))
  4852. HadError = true;
  4853. } else {
  4854. assert(Init->isDelegatingInitializer());
  4855. // This must be the only initializer
  4856. if (MemInits.size() != 1) {
  4857. Diag(Init->getSourceLocation(),
  4858. diag::err_delegating_initializer_alone)
  4859. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  4860. // We will treat this as being the only initializer.
  4861. }
  4862. SetDelegatingInitializer(Constructor, MemInits[i]);
  4863. // Return immediately as the initializer is set.
  4864. return;
  4865. }
  4866. }
  4867. if (HadError)
  4868. return;
  4869. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  4870. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  4871. DiagnoseUninitializedFields(*this, Constructor);
  4872. }
  4873. void
  4874. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  4875. CXXRecordDecl *ClassDecl) {
  4876. // Ignore dependent contexts. Also ignore unions, since their members never
  4877. // have destructors implicitly called.
  4878. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  4879. return;
  4880. // FIXME: all the access-control diagnostics are positioned on the
  4881. // field/base declaration. That's probably good; that said, the
  4882. // user might reasonably want to know why the destructor is being
  4883. // emitted, and we currently don't say.
  4884. // Non-static data members.
  4885. for (auto *Field : ClassDecl->fields()) {
  4886. if (Field->isInvalidDecl())
  4887. continue;
  4888. // Don't destroy incomplete or zero-length arrays.
  4889. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  4890. continue;
  4891. QualType FieldType = Context.getBaseElementType(Field->getType());
  4892. const RecordType* RT = FieldType->getAs<RecordType>();
  4893. if (!RT)
  4894. continue;
  4895. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4896. if (FieldClassDecl->isInvalidDecl())
  4897. continue;
  4898. if (FieldClassDecl->hasIrrelevantDestructor())
  4899. continue;
  4900. // The destructor for an implicit anonymous union member is never invoked.
  4901. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  4902. continue;
  4903. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  4904. assert(Dtor && "No dtor found for FieldClassDecl!");
  4905. CheckDestructorAccess(Field->getLocation(), Dtor,
  4906. PDiag(diag::err_access_dtor_field)
  4907. << Field->getDeclName()
  4908. << FieldType);
  4909. MarkFunctionReferenced(Location, Dtor);
  4910. DiagnoseUseOfDecl(Dtor, Location);
  4911. }
  4912. // We only potentially invoke the destructors of potentially constructed
  4913. // subobjects.
  4914. bool VisitVirtualBases = !ClassDecl->isAbstract();
  4915. // If the destructor exists and has already been marked used in the MS ABI,
  4916. // then virtual base destructors have already been checked and marked used.
  4917. // Skip checking them again to avoid duplicate diagnostics.
  4918. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  4919. CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
  4920. if (Dtor && Dtor->isUsed())
  4921. VisitVirtualBases = false;
  4922. }
  4923. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  4924. // Bases.
  4925. for (const auto &Base : ClassDecl->bases()) {
  4926. const RecordType *RT = Base.getType()->getAs<RecordType>();
  4927. if (!RT)
  4928. continue;
  4929. // Remember direct virtual bases.
  4930. if (Base.isVirtual()) {
  4931. if (!VisitVirtualBases)
  4932. continue;
  4933. DirectVirtualBases.insert(RT);
  4934. }
  4935. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4936. // If our base class is invalid, we probably can't get its dtor anyway.
  4937. if (BaseClassDecl->isInvalidDecl())
  4938. continue;
  4939. if (BaseClassDecl->hasIrrelevantDestructor())
  4940. continue;
  4941. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4942. assert(Dtor && "No dtor found for BaseClassDecl!");
  4943. // FIXME: caret should be on the start of the class name
  4944. CheckDestructorAccess(Base.getBeginLoc(), Dtor,
  4945. PDiag(diag::err_access_dtor_base)
  4946. << Base.getType() << Base.getSourceRange(),
  4947. Context.getTypeDeclType(ClassDecl));
  4948. MarkFunctionReferenced(Location, Dtor);
  4949. DiagnoseUseOfDecl(Dtor, Location);
  4950. }
  4951. if (VisitVirtualBases)
  4952. MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
  4953. &DirectVirtualBases);
  4954. }
  4955. void Sema::MarkVirtualBaseDestructorsReferenced(
  4956. SourceLocation Location, CXXRecordDecl *ClassDecl,
  4957. llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
  4958. // Virtual bases.
  4959. for (const auto &VBase : ClassDecl->vbases()) {
  4960. // Bases are always records in a well-formed non-dependent class.
  4961. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  4962. // Ignore already visited direct virtual bases.
  4963. if (DirectVirtualBases && DirectVirtualBases->count(RT))
  4964. continue;
  4965. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  4966. // If our base class is invalid, we probably can't get its dtor anyway.
  4967. if (BaseClassDecl->isInvalidDecl())
  4968. continue;
  4969. if (BaseClassDecl->hasIrrelevantDestructor())
  4970. continue;
  4971. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  4972. assert(Dtor && "No dtor found for BaseClassDecl!");
  4973. if (CheckDestructorAccess(
  4974. ClassDecl->getLocation(), Dtor,
  4975. PDiag(diag::err_access_dtor_vbase)
  4976. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  4977. Context.getTypeDeclType(ClassDecl)) ==
  4978. AR_accessible) {
  4979. CheckDerivedToBaseConversion(
  4980. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  4981. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  4982. SourceRange(), DeclarationName(), nullptr);
  4983. }
  4984. MarkFunctionReferenced(Location, Dtor);
  4985. DiagnoseUseOfDecl(Dtor, Location);
  4986. }
  4987. }
  4988. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  4989. if (!CDtorDecl)
  4990. return;
  4991. if (CXXConstructorDecl *Constructor
  4992. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  4993. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  4994. DiagnoseUninitializedFields(*this, Constructor);
  4995. }
  4996. }
  4997. bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
  4998. if (!getLangOpts().CPlusPlus)
  4999. return false;
  5000. const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
  5001. if (!RD)
  5002. return false;
  5003. // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
  5004. // class template specialization here, but doing so breaks a lot of code.
  5005. // We can't answer whether something is abstract until it has a
  5006. // definition. If it's currently being defined, we'll walk back
  5007. // over all the declarations when we have a full definition.
  5008. const CXXRecordDecl *Def = RD->getDefinition();
  5009. if (!Def || Def->isBeingDefined())
  5010. return false;
  5011. return RD->isAbstract();
  5012. }
  5013. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  5014. TypeDiagnoser &Diagnoser) {
  5015. if (!isAbstractType(Loc, T))
  5016. return false;
  5017. T = Context.getBaseElementType(T);
  5018. Diagnoser.diagnose(*this, Loc, T);
  5019. DiagnoseAbstractType(T->getAsCXXRecordDecl());
  5020. return true;
  5021. }
  5022. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  5023. // Check if we've already emitted the list of pure virtual functions
  5024. // for this class.
  5025. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  5026. return;
  5027. // If the diagnostic is suppressed, don't emit the notes. We're only
  5028. // going to emit them once, so try to attach them to a diagnostic we're
  5029. // actually going to show.
  5030. if (Diags.isLastDiagnosticIgnored())
  5031. return;
  5032. CXXFinalOverriderMap FinalOverriders;
  5033. RD->getFinalOverriders(FinalOverriders);
  5034. // Keep a set of seen pure methods so we won't diagnose the same method
  5035. // more than once.
  5036. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  5037. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  5038. MEnd = FinalOverriders.end();
  5039. M != MEnd;
  5040. ++M) {
  5041. for (OverridingMethods::iterator SO = M->second.begin(),
  5042. SOEnd = M->second.end();
  5043. SO != SOEnd; ++SO) {
  5044. // C++ [class.abstract]p4:
  5045. // A class is abstract if it contains or inherits at least one
  5046. // pure virtual function for which the final overrider is pure
  5047. // virtual.
  5048. //
  5049. if (SO->second.size() != 1)
  5050. continue;
  5051. if (!SO->second.front().Method->isPure())
  5052. continue;
  5053. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  5054. continue;
  5055. Diag(SO->second.front().Method->getLocation(),
  5056. diag::note_pure_virtual_function)
  5057. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  5058. }
  5059. }
  5060. if (!PureVirtualClassDiagSet)
  5061. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  5062. PureVirtualClassDiagSet->insert(RD);
  5063. }
  5064. namespace {
  5065. struct AbstractUsageInfo {
  5066. Sema &S;
  5067. CXXRecordDecl *Record;
  5068. CanQualType AbstractType;
  5069. bool Invalid;
  5070. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  5071. : S(S), Record(Record),
  5072. AbstractType(S.Context.getCanonicalType(
  5073. S.Context.getTypeDeclType(Record))),
  5074. Invalid(false) {}
  5075. void DiagnoseAbstractType() {
  5076. if (Invalid) return;
  5077. S.DiagnoseAbstractType(Record);
  5078. Invalid = true;
  5079. }
  5080. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  5081. };
  5082. struct CheckAbstractUsage {
  5083. AbstractUsageInfo &Info;
  5084. const NamedDecl *Ctx;
  5085. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  5086. : Info(Info), Ctx(Ctx) {}
  5087. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5088. switch (TL.getTypeLocClass()) {
  5089. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  5090. #define TYPELOC(CLASS, PARENT) \
  5091. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  5092. #include "clang/AST/TypeLocNodes.def"
  5093. }
  5094. }
  5095. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5096. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  5097. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  5098. if (!TL.getParam(I))
  5099. continue;
  5100. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  5101. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  5102. }
  5103. }
  5104. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5105. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  5106. }
  5107. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5108. // Visit the type parameters from a permissive context.
  5109. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  5110. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  5111. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  5112. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  5113. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  5114. // TODO: other template argument types?
  5115. }
  5116. }
  5117. // Visit pointee types from a permissive context.
  5118. #define CheckPolymorphic(Type) \
  5119. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  5120. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  5121. }
  5122. CheckPolymorphic(PointerTypeLoc)
  5123. CheckPolymorphic(ReferenceTypeLoc)
  5124. CheckPolymorphic(MemberPointerTypeLoc)
  5125. CheckPolymorphic(BlockPointerTypeLoc)
  5126. CheckPolymorphic(AtomicTypeLoc)
  5127. /// Handle all the types we haven't given a more specific
  5128. /// implementation for above.
  5129. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  5130. // Every other kind of type that we haven't called out already
  5131. // that has an inner type is either (1) sugar or (2) contains that
  5132. // inner type in some way as a subobject.
  5133. if (TypeLoc Next = TL.getNextTypeLoc())
  5134. return Visit(Next, Sel);
  5135. // If there's no inner type and we're in a permissive context,
  5136. // don't diagnose.
  5137. if (Sel == Sema::AbstractNone) return;
  5138. // Check whether the type matches the abstract type.
  5139. QualType T = TL.getType();
  5140. if (T->isArrayType()) {
  5141. Sel = Sema::AbstractArrayType;
  5142. T = Info.S.Context.getBaseElementType(T);
  5143. }
  5144. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  5145. if (CT != Info.AbstractType) return;
  5146. // It matched; do some magic.
  5147. // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
  5148. if (Sel == Sema::AbstractArrayType) {
  5149. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  5150. << T << TL.getSourceRange();
  5151. } else {
  5152. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  5153. << Sel << T << TL.getSourceRange();
  5154. }
  5155. Info.DiagnoseAbstractType();
  5156. }
  5157. };
  5158. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  5159. Sema::AbstractDiagSelID Sel) {
  5160. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  5161. }
  5162. }
  5163. /// Check for invalid uses of an abstract type in a function declaration.
  5164. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  5165. FunctionDecl *FD) {
  5166. // No need to do the check on definitions, which require that
  5167. // the return/param types be complete.
  5168. if (FD->doesThisDeclarationHaveABody())
  5169. return;
  5170. // For safety's sake, just ignore it if we don't have type source
  5171. // information. This should never happen for non-implicit methods,
  5172. // but...
  5173. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  5174. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
  5175. }
  5176. /// Check for invalid uses of an abstract type in a variable0 declaration.
  5177. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  5178. VarDecl *VD) {
  5179. // No need to do the check on definitions, which require that
  5180. // the type is complete.
  5181. if (VD->isThisDeclarationADefinition())
  5182. return;
  5183. Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
  5184. Sema::AbstractVariableType);
  5185. }
  5186. /// Check for invalid uses of an abstract type within a class definition.
  5187. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  5188. CXXRecordDecl *RD) {
  5189. for (auto *D : RD->decls()) {
  5190. if (D->isImplicit()) continue;
  5191. // Step through friends to the befriended declaration.
  5192. if (auto *FD = dyn_cast<FriendDecl>(D)) {
  5193. D = FD->getFriendDecl();
  5194. if (!D) continue;
  5195. }
  5196. // Functions and function templates.
  5197. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  5198. CheckAbstractClassUsage(Info, FD);
  5199. } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
  5200. CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
  5201. // Fields and static variables.
  5202. } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
  5203. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  5204. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  5205. } else if (auto *VD = dyn_cast<VarDecl>(D)) {
  5206. CheckAbstractClassUsage(Info, VD);
  5207. } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
  5208. CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
  5209. // Nested classes and class templates.
  5210. } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  5211. CheckAbstractClassUsage(Info, RD);
  5212. } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
  5213. CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
  5214. }
  5215. }
  5216. }
  5217. static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
  5218. Attr *ClassAttr = getDLLAttr(Class);
  5219. if (!ClassAttr)
  5220. return;
  5221. assert(ClassAttr->getKind() == attr::DLLExport);
  5222. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5223. if (TSK == TSK_ExplicitInstantiationDeclaration)
  5224. // Don't go any further if this is just an explicit instantiation
  5225. // declaration.
  5226. return;
  5227. // Add a context note to explain how we got to any diagnostics produced below.
  5228. struct MarkingClassDllexported {
  5229. Sema &S;
  5230. MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
  5231. SourceLocation AttrLoc)
  5232. : S(S) {
  5233. Sema::CodeSynthesisContext Ctx;
  5234. Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
  5235. Ctx.PointOfInstantiation = AttrLoc;
  5236. Ctx.Entity = Class;
  5237. S.pushCodeSynthesisContext(Ctx);
  5238. }
  5239. ~MarkingClassDllexported() {
  5240. S.popCodeSynthesisContext();
  5241. }
  5242. } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
  5243. if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
  5244. S.MarkVTableUsed(Class->getLocation(), Class, true);
  5245. for (Decl *Member : Class->decls()) {
  5246. // Skip members that were not marked exported.
  5247. if (!Member->hasAttr<DLLExportAttr>())
  5248. continue;
  5249. // Defined static variables that are members of an exported base
  5250. // class must be marked export too.
  5251. auto *VD = dyn_cast<VarDecl>(Member);
  5252. if (VD && VD->getStorageClass() == SC_Static &&
  5253. TSK == TSK_ImplicitInstantiation)
  5254. S.MarkVariableReferenced(VD->getLocation(), VD);
  5255. auto *MD = dyn_cast<CXXMethodDecl>(Member);
  5256. if (!MD)
  5257. continue;
  5258. if (MD->isUserProvided()) {
  5259. // Instantiate non-default class member functions ...
  5260. // .. except for certain kinds of template specializations.
  5261. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  5262. continue;
  5263. // If this is an MS ABI dllexport default constructor, instantiate any
  5264. // default arguments.
  5265. if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  5266. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5267. if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
  5268. S.InstantiateDefaultCtorDefaultArgs(CD);
  5269. }
  5270. }
  5271. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5272. // The function will be passed to the consumer when its definition is
  5273. // encountered.
  5274. } else if (MD->isExplicitlyDefaulted()) {
  5275. // Synthesize and instantiate explicitly defaulted methods.
  5276. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5277. if (TSK != TSK_ExplicitInstantiationDefinition) {
  5278. // Except for explicit instantiation defs, we will not see the
  5279. // definition again later, so pass it to the consumer now.
  5280. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5281. }
  5282. } else if (!MD->isTrivial() ||
  5283. MD->isCopyAssignmentOperator() ||
  5284. MD->isMoveAssignmentOperator()) {
  5285. // Synthesize and instantiate non-trivial implicit methods, and the copy
  5286. // and move assignment operators. The latter are exported even if they
  5287. // are trivial, because the address of an operator can be taken and
  5288. // should compare equal across libraries.
  5289. S.MarkFunctionReferenced(Class->getLocation(), MD);
  5290. // There is no later point when we will see the definition of this
  5291. // function, so pass it to the consumer now.
  5292. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  5293. }
  5294. }
  5295. }
  5296. static void checkForMultipleExportedDefaultConstructors(Sema &S,
  5297. CXXRecordDecl *Class) {
  5298. // Only the MS ABI has default constructor closures, so we don't need to do
  5299. // this semantic checking anywhere else.
  5300. if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
  5301. return;
  5302. CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
  5303. for (Decl *Member : Class->decls()) {
  5304. // Look for exported default constructors.
  5305. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  5306. if (!CD || !CD->isDefaultConstructor())
  5307. continue;
  5308. auto *Attr = CD->getAttr<DLLExportAttr>();
  5309. if (!Attr)
  5310. continue;
  5311. // If the class is non-dependent, mark the default arguments as ODR-used so
  5312. // that we can properly codegen the constructor closure.
  5313. if (!Class->isDependentContext()) {
  5314. for (ParmVarDecl *PD : CD->parameters()) {
  5315. (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
  5316. S.DiscardCleanupsInEvaluationContext();
  5317. }
  5318. }
  5319. if (LastExportedDefaultCtor) {
  5320. S.Diag(LastExportedDefaultCtor->getLocation(),
  5321. diag::err_attribute_dll_ambiguous_default_ctor)
  5322. << Class;
  5323. S.Diag(CD->getLocation(), diag::note_entity_declared_at)
  5324. << CD->getDeclName();
  5325. return;
  5326. }
  5327. LastExportedDefaultCtor = CD;
  5328. }
  5329. }
  5330. static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
  5331. CXXRecordDecl *Class) {
  5332. bool ErrorReported = false;
  5333. auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
  5334. ClassTemplateDecl *TD) {
  5335. if (ErrorReported)
  5336. return;
  5337. S.Diag(TD->getLocation(),
  5338. diag::err_cuda_device_builtin_surftex_cls_template)
  5339. << /*surface*/ 0 << TD;
  5340. ErrorReported = true;
  5341. };
  5342. ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
  5343. if (!TD) {
  5344. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
  5345. if (!SD) {
  5346. S.Diag(Class->getLocation(),
  5347. diag::err_cuda_device_builtin_surftex_ref_decl)
  5348. << /*surface*/ 0 << Class;
  5349. S.Diag(Class->getLocation(),
  5350. diag::note_cuda_device_builtin_surftex_should_be_template_class)
  5351. << Class;
  5352. return;
  5353. }
  5354. TD = SD->getSpecializedTemplate();
  5355. }
  5356. TemplateParameterList *Params = TD->getTemplateParameters();
  5357. unsigned N = Params->size();
  5358. if (N != 2) {
  5359. reportIllegalClassTemplate(S, TD);
  5360. S.Diag(TD->getLocation(),
  5361. diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
  5362. << TD << 2;
  5363. }
  5364. if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  5365. reportIllegalClassTemplate(S, TD);
  5366. S.Diag(TD->getLocation(),
  5367. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5368. << TD << /*1st*/ 0 << /*type*/ 0;
  5369. }
  5370. if (N > 1) {
  5371. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
  5372. if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
  5373. reportIllegalClassTemplate(S, TD);
  5374. S.Diag(TD->getLocation(),
  5375. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5376. << TD << /*2nd*/ 1 << /*integer*/ 1;
  5377. }
  5378. }
  5379. }
  5380. static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
  5381. CXXRecordDecl *Class) {
  5382. bool ErrorReported = false;
  5383. auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
  5384. ClassTemplateDecl *TD) {
  5385. if (ErrorReported)
  5386. return;
  5387. S.Diag(TD->getLocation(),
  5388. diag::err_cuda_device_builtin_surftex_cls_template)
  5389. << /*texture*/ 1 << TD;
  5390. ErrorReported = true;
  5391. };
  5392. ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
  5393. if (!TD) {
  5394. auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
  5395. if (!SD) {
  5396. S.Diag(Class->getLocation(),
  5397. diag::err_cuda_device_builtin_surftex_ref_decl)
  5398. << /*texture*/ 1 << Class;
  5399. S.Diag(Class->getLocation(),
  5400. diag::note_cuda_device_builtin_surftex_should_be_template_class)
  5401. << Class;
  5402. return;
  5403. }
  5404. TD = SD->getSpecializedTemplate();
  5405. }
  5406. TemplateParameterList *Params = TD->getTemplateParameters();
  5407. unsigned N = Params->size();
  5408. if (N != 3) {
  5409. reportIllegalClassTemplate(S, TD);
  5410. S.Diag(TD->getLocation(),
  5411. diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
  5412. << TD << 3;
  5413. }
  5414. if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  5415. reportIllegalClassTemplate(S, TD);
  5416. S.Diag(TD->getLocation(),
  5417. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5418. << TD << /*1st*/ 0 << /*type*/ 0;
  5419. }
  5420. if (N > 1) {
  5421. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
  5422. if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
  5423. reportIllegalClassTemplate(S, TD);
  5424. S.Diag(TD->getLocation(),
  5425. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5426. << TD << /*2nd*/ 1 << /*integer*/ 1;
  5427. }
  5428. }
  5429. if (N > 2) {
  5430. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
  5431. if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
  5432. reportIllegalClassTemplate(S, TD);
  5433. S.Diag(TD->getLocation(),
  5434. diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
  5435. << TD << /*3rd*/ 2 << /*integer*/ 1;
  5436. }
  5437. }
  5438. }
  5439. void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
  5440. // Mark any compiler-generated routines with the implicit code_seg attribute.
  5441. for (auto *Method : Class->methods()) {
  5442. if (Method->isUserProvided())
  5443. continue;
  5444. if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
  5445. Method->addAttr(A);
  5446. }
  5447. }
  5448. /// Check class-level dllimport/dllexport attribute.
  5449. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  5450. Attr *ClassAttr = getDLLAttr(Class);
  5451. // MSVC inherits DLL attributes to partial class template specializations.
  5452. if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
  5453. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  5454. if (Attr *TemplateAttr =
  5455. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  5456. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  5457. A->setInherited(true);
  5458. ClassAttr = A;
  5459. }
  5460. }
  5461. }
  5462. if (!ClassAttr)
  5463. return;
  5464. if (!Class->isExternallyVisible()) {
  5465. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  5466. << Class << ClassAttr;
  5467. return;
  5468. }
  5469. if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  5470. !ClassAttr->isInherited()) {
  5471. // Diagnose dll attributes on members of class with dll attribute.
  5472. for (Decl *Member : Class->decls()) {
  5473. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  5474. continue;
  5475. InheritableAttr *MemberAttr = getDLLAttr(Member);
  5476. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  5477. continue;
  5478. Diag(MemberAttr->getLocation(),
  5479. diag::err_attribute_dll_member_of_dll_class)
  5480. << MemberAttr << ClassAttr;
  5481. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  5482. Member->setInvalidDecl();
  5483. }
  5484. }
  5485. if (Class->getDescribedClassTemplate())
  5486. // Don't inherit dll attribute until the template is instantiated.
  5487. return;
  5488. // The class is either imported or exported.
  5489. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  5490. // Check if this was a dllimport attribute propagated from a derived class to
  5491. // a base class template specialization. We don't apply these attributes to
  5492. // static data members.
  5493. const bool PropagatedImport =
  5494. !ClassExported &&
  5495. cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
  5496. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  5497. // Ignore explicit dllexport on explicit class template instantiation
  5498. // declarations, except in MinGW mode.
  5499. if (ClassExported && !ClassAttr->isInherited() &&
  5500. TSK == TSK_ExplicitInstantiationDeclaration &&
  5501. !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
  5502. Class->dropAttr<DLLExportAttr>();
  5503. return;
  5504. }
  5505. // Force declaration of implicit members so they can inherit the attribute.
  5506. ForceDeclarationOfImplicitMembers(Class);
  5507. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  5508. // seem to be true in practice?
  5509. for (Decl *Member : Class->decls()) {
  5510. VarDecl *VD = dyn_cast<VarDecl>(Member);
  5511. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  5512. // Only methods and static fields inherit the attributes.
  5513. if (!VD && !MD)
  5514. continue;
  5515. if (MD) {
  5516. // Don't process deleted methods.
  5517. if (MD->isDeleted())
  5518. continue;
  5519. if (MD->isInlined()) {
  5520. // MinGW does not import or export inline methods. But do it for
  5521. // template instantiations.
  5522. if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
  5523. TSK != TSK_ExplicitInstantiationDeclaration &&
  5524. TSK != TSK_ExplicitInstantiationDefinition)
  5525. continue;
  5526. // MSVC versions before 2015 don't export the move assignment operators
  5527. // and move constructor, so don't attempt to import/export them if
  5528. // we have a definition.
  5529. auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
  5530. if ((MD->isMoveAssignmentOperator() ||
  5531. (Ctor && Ctor->isMoveConstructor())) &&
  5532. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  5533. continue;
  5534. // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
  5535. // operator is exported anyway.
  5536. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  5537. (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
  5538. continue;
  5539. }
  5540. }
  5541. // Don't apply dllimport attributes to static data members of class template
  5542. // instantiations when the attribute is propagated from a derived class.
  5543. if (VD && PropagatedImport)
  5544. continue;
  5545. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  5546. continue;
  5547. if (!getDLLAttr(Member)) {
  5548. InheritableAttr *NewAttr = nullptr;
  5549. // Do not export/import inline function when -fno-dllexport-inlines is
  5550. // passed. But add attribute for later local static var check.
  5551. if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
  5552. TSK != TSK_ExplicitInstantiationDeclaration &&
  5553. TSK != TSK_ExplicitInstantiationDefinition) {
  5554. if (ClassExported) {
  5555. NewAttr = ::new (getASTContext())
  5556. DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
  5557. } else {
  5558. NewAttr = ::new (getASTContext())
  5559. DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
  5560. }
  5561. } else {
  5562. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5563. }
  5564. NewAttr->setInherited(true);
  5565. Member->addAttr(NewAttr);
  5566. if (MD) {
  5567. // Propagate DLLAttr to friend re-declarations of MD that have already
  5568. // been constructed.
  5569. for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
  5570. FD = FD->getPreviousDecl()) {
  5571. if (FD->getFriendObjectKind() == Decl::FOK_None)
  5572. continue;
  5573. assert(!getDLLAttr(FD) &&
  5574. "friend re-decl should not already have a DLLAttr");
  5575. NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5576. NewAttr->setInherited(true);
  5577. FD->addAttr(NewAttr);
  5578. }
  5579. }
  5580. }
  5581. }
  5582. if (ClassExported)
  5583. DelayedDllExportClasses.push_back(Class);
  5584. }
  5585. /// Perform propagation of DLL attributes from a derived class to a
  5586. /// templated base class for MS compatibility.
  5587. void Sema::propagateDLLAttrToBaseClassTemplate(
  5588. CXXRecordDecl *Class, Attr *ClassAttr,
  5589. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  5590. if (getDLLAttr(
  5591. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  5592. // If the base class template has a DLL attribute, don't try to change it.
  5593. return;
  5594. }
  5595. auto TSK = BaseTemplateSpec->getSpecializationKind();
  5596. if (!getDLLAttr(BaseTemplateSpec) &&
  5597. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  5598. TSK == TSK_ImplicitInstantiation)) {
  5599. // The template hasn't been instantiated yet (or it has, but only as an
  5600. // explicit instantiation declaration or implicit instantiation, which means
  5601. // we haven't codegenned any members yet), so propagate the attribute.
  5602. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  5603. NewAttr->setInherited(true);
  5604. BaseTemplateSpec->addAttr(NewAttr);
  5605. // If this was an import, mark that we propagated it from a derived class to
  5606. // a base class template specialization.
  5607. if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
  5608. ImportAttr->setPropagatedToBaseTemplate();
  5609. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  5610. // needs to be run again to work see the new attribute. Otherwise this will
  5611. // get run whenever the template is instantiated.
  5612. if (TSK != TSK_Undeclared)
  5613. checkClassLevelDLLAttribute(BaseTemplateSpec);
  5614. return;
  5615. }
  5616. if (getDLLAttr(BaseTemplateSpec)) {
  5617. // The template has already been specialized or instantiated with an
  5618. // attribute, explicitly or through propagation. We should not try to change
  5619. // it.
  5620. return;
  5621. }
  5622. // The template was previously instantiated or explicitly specialized without
  5623. // a dll attribute, It's too late for us to add an attribute, so warn that
  5624. // this is unsupported.
  5625. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  5626. << BaseTemplateSpec->isExplicitSpecialization();
  5627. Diag(ClassAttr->getLocation(), diag::note_attribute);
  5628. if (BaseTemplateSpec->isExplicitSpecialization()) {
  5629. Diag(BaseTemplateSpec->getLocation(),
  5630. diag::note_template_class_explicit_specialization_was_here)
  5631. << BaseTemplateSpec;
  5632. } else {
  5633. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  5634. diag::note_template_class_instantiation_was_here)
  5635. << BaseTemplateSpec;
  5636. }
  5637. }
  5638. /// Determine the kind of defaulting that would be done for a given function.
  5639. ///
  5640. /// If the function is both a default constructor and a copy / move constructor
  5641. /// (due to having a default argument for the first parameter), this picks
  5642. /// CXXDefaultConstructor.
  5643. ///
  5644. /// FIXME: Check that case is properly handled by all callers.
  5645. Sema::DefaultedFunctionKind
  5646. Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
  5647. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5648. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
  5649. if (Ctor->isDefaultConstructor())
  5650. return Sema::CXXDefaultConstructor;
  5651. if (Ctor->isCopyConstructor())
  5652. return Sema::CXXCopyConstructor;
  5653. if (Ctor->isMoveConstructor())
  5654. return Sema::CXXMoveConstructor;
  5655. }
  5656. if (MD->isCopyAssignmentOperator())
  5657. return Sema::CXXCopyAssignment;
  5658. if (MD->isMoveAssignmentOperator())
  5659. return Sema::CXXMoveAssignment;
  5660. if (isa<CXXDestructorDecl>(FD))
  5661. return Sema::CXXDestructor;
  5662. }
  5663. switch (FD->getDeclName().getCXXOverloadedOperator()) {
  5664. case OO_EqualEqual:
  5665. return DefaultedComparisonKind::Equal;
  5666. case OO_ExclaimEqual:
  5667. return DefaultedComparisonKind::NotEqual;
  5668. case OO_Spaceship:
  5669. // No point allowing this if <=> doesn't exist in the current language mode.
  5670. if (!getLangOpts().CPlusPlus20)
  5671. break;
  5672. return DefaultedComparisonKind::ThreeWay;
  5673. case OO_Less:
  5674. case OO_LessEqual:
  5675. case OO_Greater:
  5676. case OO_GreaterEqual:
  5677. // No point allowing this if <=> doesn't exist in the current language mode.
  5678. if (!getLangOpts().CPlusPlus20)
  5679. break;
  5680. return DefaultedComparisonKind::Relational;
  5681. default:
  5682. break;
  5683. }
  5684. // Not defaultable.
  5685. return DefaultedFunctionKind();
  5686. }
  5687. static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
  5688. SourceLocation DefaultLoc) {
  5689. Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
  5690. if (DFK.isComparison())
  5691. return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
  5692. switch (DFK.asSpecialMember()) {
  5693. case Sema::CXXDefaultConstructor:
  5694. S.DefineImplicitDefaultConstructor(DefaultLoc,
  5695. cast<CXXConstructorDecl>(FD));
  5696. break;
  5697. case Sema::CXXCopyConstructor:
  5698. S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
  5699. break;
  5700. case Sema::CXXCopyAssignment:
  5701. S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
  5702. break;
  5703. case Sema::CXXDestructor:
  5704. S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
  5705. break;
  5706. case Sema::CXXMoveConstructor:
  5707. S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
  5708. break;
  5709. case Sema::CXXMoveAssignment:
  5710. S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
  5711. break;
  5712. case Sema::CXXInvalid:
  5713. llvm_unreachable("Invalid special member.");
  5714. }
  5715. }
  5716. /// Determine whether a type is permitted to be passed or returned in
  5717. /// registers, per C++ [class.temporary]p3.
  5718. static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
  5719. TargetInfo::CallingConvKind CCK) {
  5720. if (D->isDependentType() || D->isInvalidDecl())
  5721. return false;
  5722. // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
  5723. // The PS4 platform ABI follows the behavior of Clang 3.2.
  5724. if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
  5725. return !D->hasNonTrivialDestructorForCall() &&
  5726. !D->hasNonTrivialCopyConstructorForCall();
  5727. if (CCK == TargetInfo::CCK_MicrosoftWin64) {
  5728. bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
  5729. bool DtorIsTrivialForCall = false;
  5730. // If a class has at least one non-deleted, trivial copy constructor, it
  5731. // is passed according to the C ABI. Otherwise, it is passed indirectly.
  5732. //
  5733. // Note: This permits classes with non-trivial copy or move ctors to be
  5734. // passed in registers, so long as they *also* have a trivial copy ctor,
  5735. // which is non-conforming.
  5736. if (D->needsImplicitCopyConstructor()) {
  5737. if (!D->defaultedCopyConstructorIsDeleted()) {
  5738. if (D->hasTrivialCopyConstructor())
  5739. CopyCtorIsTrivial = true;
  5740. if (D->hasTrivialCopyConstructorForCall())
  5741. CopyCtorIsTrivialForCall = true;
  5742. }
  5743. } else {
  5744. for (const CXXConstructorDecl *CD : D->ctors()) {
  5745. if (CD->isCopyConstructor() && !CD->isDeleted()) {
  5746. if (CD->isTrivial())
  5747. CopyCtorIsTrivial = true;
  5748. if (CD->isTrivialForCall())
  5749. CopyCtorIsTrivialForCall = true;
  5750. }
  5751. }
  5752. }
  5753. if (D->needsImplicitDestructor()) {
  5754. if (!D->defaultedDestructorIsDeleted() &&
  5755. D->hasTrivialDestructorForCall())
  5756. DtorIsTrivialForCall = true;
  5757. } else if (const auto *DD = D->getDestructor()) {
  5758. if (!DD->isDeleted() && DD->isTrivialForCall())
  5759. DtorIsTrivialForCall = true;
  5760. }
  5761. // If the copy ctor and dtor are both trivial-for-calls, pass direct.
  5762. if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
  5763. return true;
  5764. // If a class has a destructor, we'd really like to pass it indirectly
  5765. // because it allows us to elide copies. Unfortunately, MSVC makes that
  5766. // impossible for small types, which it will pass in a single register or
  5767. // stack slot. Most objects with dtors are large-ish, so handle that early.
  5768. // We can't call out all large objects as being indirect because there are
  5769. // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
  5770. // how we pass large POD types.
  5771. // Note: This permits small classes with nontrivial destructors to be
  5772. // passed in registers, which is non-conforming.
  5773. bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
  5774. uint64_t TypeSize = isAArch64 ? 128 : 64;
  5775. if (CopyCtorIsTrivial &&
  5776. S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
  5777. return true;
  5778. return false;
  5779. }
  5780. // Per C++ [class.temporary]p3, the relevant condition is:
  5781. // each copy constructor, move constructor, and destructor of X is
  5782. // either trivial or deleted, and X has at least one non-deleted copy
  5783. // or move constructor
  5784. bool HasNonDeletedCopyOrMove = false;
  5785. if (D->needsImplicitCopyConstructor() &&
  5786. !D->defaultedCopyConstructorIsDeleted()) {
  5787. if (!D->hasTrivialCopyConstructorForCall())
  5788. return false;
  5789. HasNonDeletedCopyOrMove = true;
  5790. }
  5791. if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
  5792. !D->defaultedMoveConstructorIsDeleted()) {
  5793. if (!D->hasTrivialMoveConstructorForCall())
  5794. return false;
  5795. HasNonDeletedCopyOrMove = true;
  5796. }
  5797. if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
  5798. !D->hasTrivialDestructorForCall())
  5799. return false;
  5800. for (const CXXMethodDecl *MD : D->methods()) {
  5801. if (MD->isDeleted())
  5802. continue;
  5803. auto *CD = dyn_cast<CXXConstructorDecl>(MD);
  5804. if (CD && CD->isCopyOrMoveConstructor())
  5805. HasNonDeletedCopyOrMove = true;
  5806. else if (!isa<CXXDestructorDecl>(MD))
  5807. continue;
  5808. if (!MD->isTrivialForCall())
  5809. return false;
  5810. }
  5811. return HasNonDeletedCopyOrMove;
  5812. }
  5813. /// Report an error regarding overriding, along with any relevant
  5814. /// overridden methods.
  5815. ///
  5816. /// \param DiagID the primary error to report.
  5817. /// \param MD the overriding method.
  5818. static bool
  5819. ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
  5820. llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
  5821. bool IssuedDiagnostic = false;
  5822. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  5823. if (Report(O)) {
  5824. if (!IssuedDiagnostic) {
  5825. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5826. IssuedDiagnostic = true;
  5827. }
  5828. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  5829. }
  5830. }
  5831. return IssuedDiagnostic;
  5832. }
  5833. /// Perform semantic checks on a class definition that has been
  5834. /// completing, introducing implicitly-declared members, checking for
  5835. /// abstract types, etc.
  5836. ///
  5837. /// \param S The scope in which the class was parsed. Null if we didn't just
  5838. /// parse a class definition.
  5839. /// \param Record The completed class.
  5840. void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
  5841. if (!Record)
  5842. return;
  5843. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  5844. AbstractUsageInfo Info(*this, Record);
  5845. CheckAbstractClassUsage(Info, Record);
  5846. }
  5847. // If this is not an aggregate type and has no user-declared constructor,
  5848. // complain about any non-static data members of reference or const scalar
  5849. // type, since they will never get initializers.
  5850. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  5851. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  5852. !Record->isLambda()) {
  5853. bool Complained = false;
  5854. for (const auto *F : Record->fields()) {
  5855. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  5856. continue;
  5857. if (F->getType()->isReferenceType() ||
  5858. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  5859. if (!Complained) {
  5860. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  5861. << Record->getTagKind() << Record;
  5862. Complained = true;
  5863. }
  5864. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  5865. << F->getType()->isReferenceType()
  5866. << F->getDeclName();
  5867. }
  5868. }
  5869. }
  5870. if (Record->getIdentifier()) {
  5871. // C++ [class.mem]p13:
  5872. // If T is the name of a class, then each of the following shall have a
  5873. // name different from T:
  5874. // - every member of every anonymous union that is a member of class T.
  5875. //
  5876. // C++ [class.mem]p14:
  5877. // In addition, if class T has a user-declared constructor (12.1), every
  5878. // non-static data member of class T shall have a name different from T.
  5879. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  5880. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  5881. ++I) {
  5882. NamedDecl *D = (*I)->getUnderlyingDecl();
  5883. if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
  5884. Record->hasUserDeclaredConstructor()) ||
  5885. isa<IndirectFieldDecl>(D)) {
  5886. Diag((*I)->getLocation(), diag::err_member_name_of_class)
  5887. << D->getDeclName();
  5888. break;
  5889. }
  5890. }
  5891. }
  5892. // Warn if the class has virtual methods but non-virtual public destructor.
  5893. if (Record->isPolymorphic() && !Record->isDependentType()) {
  5894. CXXDestructorDecl *dtor = Record->getDestructor();
  5895. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  5896. !Record->hasAttr<FinalAttr>())
  5897. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  5898. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  5899. }
  5900. if (Record->isAbstract()) {
  5901. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  5902. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  5903. << FA->isSpelledAsSealed();
  5904. DiagnoseAbstractType(Record);
  5905. }
  5906. }
  5907. // Warn if the class has a final destructor but is not itself marked final.
  5908. if (!Record->hasAttr<FinalAttr>()) {
  5909. if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
  5910. if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
  5911. Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
  5912. << FA->isSpelledAsSealed()
  5913. << FixItHint::CreateInsertion(
  5914. getLocForEndOfToken(Record->getLocation()),
  5915. (FA->isSpelledAsSealed() ? " sealed" : " final"));
  5916. Diag(Record->getLocation(),
  5917. diag::note_final_dtor_non_final_class_silence)
  5918. << Context.getRecordType(Record) << FA->isSpelledAsSealed();
  5919. }
  5920. }
  5921. }
  5922. // See if trivial_abi has to be dropped.
  5923. if (Record->hasAttr<TrivialABIAttr>())
  5924. checkIllFormedTrivialABIStruct(*Record);
  5925. // Set HasTrivialSpecialMemberForCall if the record has attribute
  5926. // "trivial_abi".
  5927. bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
  5928. if (HasTrivialABI)
  5929. Record->setHasTrivialSpecialMemberForCall();
  5930. // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
  5931. // We check these last because they can depend on the properties of the
  5932. // primary comparison functions (==, <=>).
  5933. llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
  5934. // Perform checks that can't be done until we know all the properties of a
  5935. // member function (whether it's defaulted, deleted, virtual, overriding,
  5936. // ...).
  5937. auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
  5938. // A static function cannot override anything.
  5939. if (MD->getStorageClass() == SC_Static) {
  5940. if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
  5941. [](const CXXMethodDecl *) { return true; }))
  5942. return;
  5943. }
  5944. // A deleted function cannot override a non-deleted function and vice
  5945. // versa.
  5946. if (ReportOverrides(*this,
  5947. MD->isDeleted() ? diag::err_deleted_override
  5948. : diag::err_non_deleted_override,
  5949. MD, [&](const CXXMethodDecl *V) {
  5950. return MD->isDeleted() != V->isDeleted();
  5951. })) {
  5952. if (MD->isDefaulted() && MD->isDeleted())
  5953. // Explain why this defaulted function was deleted.
  5954. DiagnoseDeletedDefaultedFunction(MD);
  5955. return;
  5956. }
  5957. // A consteval function cannot override a non-consteval function and vice
  5958. // versa.
  5959. if (ReportOverrides(*this,
  5960. MD->isConsteval() ? diag::err_consteval_override
  5961. : diag::err_non_consteval_override,
  5962. MD, [&](const CXXMethodDecl *V) {
  5963. return MD->isConsteval() != V->isConsteval();
  5964. })) {
  5965. if (MD->isDefaulted() && MD->isDeleted())
  5966. // Explain why this defaulted function was deleted.
  5967. DiagnoseDeletedDefaultedFunction(MD);
  5968. return;
  5969. }
  5970. };
  5971. auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
  5972. if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
  5973. return false;
  5974. DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
  5975. if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
  5976. DFK.asComparison() == DefaultedComparisonKind::Relational) {
  5977. DefaultedSecondaryComparisons.push_back(FD);
  5978. return true;
  5979. }
  5980. CheckExplicitlyDefaultedFunction(S, FD);
  5981. return false;
  5982. };
  5983. auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
  5984. // Check whether the explicitly-defaulted members are valid.
  5985. bool Incomplete = CheckForDefaultedFunction(M);
  5986. // Skip the rest of the checks for a member of a dependent class.
  5987. if (Record->isDependentType())
  5988. return;
  5989. // For an explicitly defaulted or deleted special member, we defer
  5990. // determining triviality until the class is complete. That time is now!
  5991. CXXSpecialMember CSM = getSpecialMember(M);
  5992. if (!M->isImplicit() && !M->isUserProvided()) {
  5993. if (CSM != CXXInvalid) {
  5994. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  5995. // Inform the class that we've finished declaring this member.
  5996. Record->finishedDefaultedOrDeletedMember(M);
  5997. M->setTrivialForCall(
  5998. HasTrivialABI ||
  5999. SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
  6000. Record->setTrivialForCallFlags(M);
  6001. }
  6002. }
  6003. // Set triviality for the purpose of calls if this is a user-provided
  6004. // copy/move constructor or destructor.
  6005. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
  6006. CSM == CXXDestructor) && M->isUserProvided()) {
  6007. M->setTrivialForCall(HasTrivialABI);
  6008. Record->setTrivialForCallFlags(M);
  6009. }
  6010. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
  6011. M->hasAttr<DLLExportAttr>()) {
  6012. if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  6013. M->isTrivial() &&
  6014. (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
  6015. CSM == CXXDestructor))
  6016. M->dropAttr<DLLExportAttr>();
  6017. if (M->hasAttr<DLLExportAttr>()) {
  6018. // Define after any fields with in-class initializers have been parsed.
  6019. DelayedDllExportMemberFunctions.push_back(M);
  6020. }
  6021. }
  6022. // Define defaulted constexpr virtual functions that override a base class
  6023. // function right away.
  6024. // FIXME: We can defer doing this until the vtable is marked as used.
  6025. if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
  6026. DefineDefaultedFunction(*this, M, M->getLocation());
  6027. if (!Incomplete)
  6028. CheckCompletedMemberFunction(M);
  6029. };
  6030. // Check the destructor before any other member function. We need to
  6031. // determine whether it's trivial in order to determine whether the claas
  6032. // type is a literal type, which is a prerequisite for determining whether
  6033. // other special member functions are valid and whether they're implicitly
  6034. // 'constexpr'.
  6035. if (CXXDestructorDecl *Dtor = Record->getDestructor())
  6036. CompleteMemberFunction(Dtor);
  6037. bool HasMethodWithOverrideControl = false,
  6038. HasOverridingMethodWithoutOverrideControl = false;
  6039. for (auto *D : Record->decls()) {
  6040. if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
  6041. // FIXME: We could do this check for dependent types with non-dependent
  6042. // bases.
  6043. if (!Record->isDependentType()) {
  6044. // See if a method overloads virtual methods in a base
  6045. // class without overriding any.
  6046. if (!M->isStatic())
  6047. DiagnoseHiddenVirtualMethods(M);
  6048. if (M->hasAttr<OverrideAttr>())
  6049. HasMethodWithOverrideControl = true;
  6050. else if (M->size_overridden_methods() > 0)
  6051. HasOverridingMethodWithoutOverrideControl = true;
  6052. }
  6053. if (!isa<CXXDestructorDecl>(M))
  6054. CompleteMemberFunction(M);
  6055. } else if (auto *F = dyn_cast<FriendDecl>(D)) {
  6056. CheckForDefaultedFunction(
  6057. dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
  6058. }
  6059. }
  6060. if (HasOverridingMethodWithoutOverrideControl) {
  6061. bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
  6062. for (auto *M : Record->methods())
  6063. DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
  6064. }
  6065. // Check the defaulted secondary comparisons after any other member functions.
  6066. for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
  6067. CheckExplicitlyDefaultedFunction(S, FD);
  6068. // If this is a member function, we deferred checking it until now.
  6069. if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
  6070. CheckCompletedMemberFunction(MD);
  6071. }
  6072. // ms_struct is a request to use the same ABI rules as MSVC. Check
  6073. // whether this class uses any C++ features that are implemented
  6074. // completely differently in MSVC, and if so, emit a diagnostic.
  6075. // That diagnostic defaults to an error, but we allow projects to
  6076. // map it down to a warning (or ignore it). It's a fairly common
  6077. // practice among users of the ms_struct pragma to mass-annotate
  6078. // headers, sweeping up a bunch of types that the project doesn't
  6079. // really rely on MSVC-compatible layout for. We must therefore
  6080. // support "ms_struct except for C++ stuff" as a secondary ABI.
  6081. // Don't emit this diagnostic if the feature was enabled as a
  6082. // language option (as opposed to via a pragma or attribute), as
  6083. // the option -mms-bitfields otherwise essentially makes it impossible
  6084. // to build C++ code, unless this diagnostic is turned off.
  6085. if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
  6086. (Record->isPolymorphic() || Record->getNumBases())) {
  6087. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  6088. }
  6089. checkClassLevelDLLAttribute(Record);
  6090. checkClassLevelCodeSegAttribute(Record);
  6091. bool ClangABICompat4 =
  6092. Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
  6093. TargetInfo::CallingConvKind CCK =
  6094. Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
  6095. bool CanPass = canPassInRegisters(*this, Record, CCK);
  6096. // Do not change ArgPassingRestrictions if it has already been set to
  6097. // APK_CanNeverPassInRegs.
  6098. if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
  6099. Record->setArgPassingRestrictions(CanPass
  6100. ? RecordDecl::APK_CanPassInRegs
  6101. : RecordDecl::APK_CannotPassInRegs);
  6102. // If canPassInRegisters returns true despite the record having a non-trivial
  6103. // destructor, the record is destructed in the callee. This happens only when
  6104. // the record or one of its subobjects has a field annotated with trivial_abi
  6105. // or a field qualified with ObjC __strong/__weak.
  6106. if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
  6107. Record->setParamDestroyedInCallee(true);
  6108. else if (Record->hasNonTrivialDestructor())
  6109. Record->setParamDestroyedInCallee(CanPass);
  6110. if (getLangOpts().ForceEmitVTables) {
  6111. // If we want to emit all the vtables, we need to mark it as used. This
  6112. // is especially required for cases like vtable assumption loads.
  6113. MarkVTableUsed(Record->getInnerLocStart(), Record);
  6114. }
  6115. if (getLangOpts().CUDA) {
  6116. if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
  6117. checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
  6118. else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
  6119. checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
  6120. }
  6121. }
  6122. /// Look up the special member function that would be called by a special
  6123. /// member function for a subobject of class type.
  6124. ///
  6125. /// \param Class The class type of the subobject.
  6126. /// \param CSM The kind of special member function.
  6127. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  6128. /// \param ConstRHS True if this is a copy operation with a const object
  6129. /// on its RHS, that is, if the argument to the outer special member
  6130. /// function is 'const' and this is not a field marked 'mutable'.
  6131. static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
  6132. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  6133. unsigned FieldQuals, bool ConstRHS) {
  6134. unsigned LHSQuals = 0;
  6135. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  6136. LHSQuals = FieldQuals;
  6137. unsigned RHSQuals = FieldQuals;
  6138. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  6139. RHSQuals = 0;
  6140. else if (ConstRHS)
  6141. RHSQuals |= Qualifiers::Const;
  6142. return S.LookupSpecialMember(Class, CSM,
  6143. RHSQuals & Qualifiers::Const,
  6144. RHSQuals & Qualifiers::Volatile,
  6145. false,
  6146. LHSQuals & Qualifiers::Const,
  6147. LHSQuals & Qualifiers::Volatile);
  6148. }
  6149. class Sema::InheritedConstructorInfo {
  6150. Sema &S;
  6151. SourceLocation UseLoc;
  6152. /// A mapping from the base classes through which the constructor was
  6153. /// inherited to the using shadow declaration in that base class (or a null
  6154. /// pointer if the constructor was declared in that base class).
  6155. llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
  6156. InheritedFromBases;
  6157. public:
  6158. InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
  6159. ConstructorUsingShadowDecl *Shadow)
  6160. : S(S), UseLoc(UseLoc) {
  6161. bool DiagnosedMultipleConstructedBases = false;
  6162. CXXRecordDecl *ConstructedBase = nullptr;
  6163. BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
  6164. // Find the set of such base class subobjects and check that there's a
  6165. // unique constructed subobject.
  6166. for (auto *D : Shadow->redecls()) {
  6167. auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
  6168. auto *DNominatedBase = DShadow->getNominatedBaseClass();
  6169. auto *DConstructedBase = DShadow->getConstructedBaseClass();
  6170. InheritedFromBases.insert(
  6171. std::make_pair(DNominatedBase->getCanonicalDecl(),
  6172. DShadow->getNominatedBaseClassShadowDecl()));
  6173. if (DShadow->constructsVirtualBase())
  6174. InheritedFromBases.insert(
  6175. std::make_pair(DConstructedBase->getCanonicalDecl(),
  6176. DShadow->getConstructedBaseClassShadowDecl()));
  6177. else
  6178. assert(DNominatedBase == DConstructedBase);
  6179. // [class.inhctor.init]p2:
  6180. // If the constructor was inherited from multiple base class subobjects
  6181. // of type B, the program is ill-formed.
  6182. if (!ConstructedBase) {
  6183. ConstructedBase = DConstructedBase;
  6184. ConstructedBaseIntroducer = D->getIntroducer();
  6185. } else if (ConstructedBase != DConstructedBase &&
  6186. !Shadow->isInvalidDecl()) {
  6187. if (!DiagnosedMultipleConstructedBases) {
  6188. S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
  6189. << Shadow->getTargetDecl();
  6190. S.Diag(ConstructedBaseIntroducer->getLocation(),
  6191. diag::note_ambiguous_inherited_constructor_using)
  6192. << ConstructedBase;
  6193. DiagnosedMultipleConstructedBases = true;
  6194. }
  6195. S.Diag(D->getIntroducer()->getLocation(),
  6196. diag::note_ambiguous_inherited_constructor_using)
  6197. << DConstructedBase;
  6198. }
  6199. }
  6200. if (DiagnosedMultipleConstructedBases)
  6201. Shadow->setInvalidDecl();
  6202. }
  6203. /// Find the constructor to use for inherited construction of a base class,
  6204. /// and whether that base class constructor inherits the constructor from a
  6205. /// virtual base class (in which case it won't actually invoke it).
  6206. std::pair<CXXConstructorDecl *, bool>
  6207. findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
  6208. auto It = InheritedFromBases.find(Base->getCanonicalDecl());
  6209. if (It == InheritedFromBases.end())
  6210. return std::make_pair(nullptr, false);
  6211. // This is an intermediary class.
  6212. if (It->second)
  6213. return std::make_pair(
  6214. S.findInheritingConstructor(UseLoc, Ctor, It->second),
  6215. It->second->constructsVirtualBase());
  6216. // This is the base class from which the constructor was inherited.
  6217. return std::make_pair(Ctor, false);
  6218. }
  6219. };
  6220. /// Is the special member function which would be selected to perform the
  6221. /// specified operation on the specified class type a constexpr constructor?
  6222. static bool
  6223. specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  6224. Sema::CXXSpecialMember CSM, unsigned Quals,
  6225. bool ConstRHS,
  6226. CXXConstructorDecl *InheritedCtor = nullptr,
  6227. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  6228. // If we're inheriting a constructor, see if we need to call it for this base
  6229. // class.
  6230. if (InheritedCtor) {
  6231. assert(CSM == Sema::CXXDefaultConstructor);
  6232. auto BaseCtor =
  6233. Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
  6234. if (BaseCtor)
  6235. return BaseCtor->isConstexpr();
  6236. }
  6237. if (CSM == Sema::CXXDefaultConstructor)
  6238. return ClassDecl->hasConstexprDefaultConstructor();
  6239. if (CSM == Sema::CXXDestructor)
  6240. return ClassDecl->hasConstexprDestructor();
  6241. Sema::SpecialMemberOverloadResult SMOR =
  6242. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  6243. if (!SMOR.getMethod())
  6244. // A constructor we wouldn't select can't be "involved in initializing"
  6245. // anything.
  6246. return true;
  6247. return SMOR.getMethod()->isConstexpr();
  6248. }
  6249. /// Determine whether the specified special member function would be constexpr
  6250. /// if it were implicitly defined.
  6251. static bool defaultedSpecialMemberIsConstexpr(
  6252. Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
  6253. bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
  6254. Sema::InheritedConstructorInfo *Inherited = nullptr) {
  6255. if (!S.getLangOpts().CPlusPlus11)
  6256. return false;
  6257. // C++11 [dcl.constexpr]p4:
  6258. // In the definition of a constexpr constructor [...]
  6259. bool Ctor = true;
  6260. switch (CSM) {
  6261. case Sema::CXXDefaultConstructor:
  6262. if (Inherited)
  6263. break;
  6264. // Since default constructor lookup is essentially trivial (and cannot
  6265. // involve, for instance, template instantiation), we compute whether a
  6266. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  6267. //
  6268. // This is important for performance; we need to know whether the default
  6269. // constructor is constexpr to determine whether the type is a literal type.
  6270. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  6271. case Sema::CXXCopyConstructor:
  6272. case Sema::CXXMoveConstructor:
  6273. // For copy or move constructors, we need to perform overload resolution.
  6274. break;
  6275. case Sema::CXXCopyAssignment:
  6276. case Sema::CXXMoveAssignment:
  6277. if (!S.getLangOpts().CPlusPlus14)
  6278. return false;
  6279. // In C++1y, we need to perform overload resolution.
  6280. Ctor = false;
  6281. break;
  6282. case Sema::CXXDestructor:
  6283. return ClassDecl->defaultedDestructorIsConstexpr();
  6284. case Sema::CXXInvalid:
  6285. return false;
  6286. }
  6287. // -- if the class is a non-empty union, or for each non-empty anonymous
  6288. // union member of a non-union class, exactly one non-static data member
  6289. // shall be initialized; [DR1359]
  6290. //
  6291. // If we squint, this is guaranteed, since exactly one non-static data member
  6292. // will be initialized (if the constructor isn't deleted), we just don't know
  6293. // which one.
  6294. if (Ctor && ClassDecl->isUnion())
  6295. return CSM == Sema::CXXDefaultConstructor
  6296. ? ClassDecl->hasInClassInitializer() ||
  6297. !ClassDecl->hasVariantMembers()
  6298. : true;
  6299. // -- the class shall not have any virtual base classes;
  6300. if (Ctor && ClassDecl->getNumVBases())
  6301. return false;
  6302. // C++1y [class.copy]p26:
  6303. // -- [the class] is a literal type, and
  6304. if (!Ctor && !ClassDecl->isLiteral())
  6305. return false;
  6306. // -- every constructor involved in initializing [...] base class
  6307. // sub-objects shall be a constexpr constructor;
  6308. // -- the assignment operator selected to copy/move each direct base
  6309. // class is a constexpr function, and
  6310. for (const auto &B : ClassDecl->bases()) {
  6311. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  6312. if (!BaseType) continue;
  6313. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  6314. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
  6315. InheritedCtor, Inherited))
  6316. return false;
  6317. }
  6318. // -- every constructor involved in initializing non-static data members
  6319. // [...] shall be a constexpr constructor;
  6320. // -- every non-static data member and base class sub-object shall be
  6321. // initialized
  6322. // -- for each non-static data member of X that is of class type (or array
  6323. // thereof), the assignment operator selected to copy/move that member is
  6324. // a constexpr function
  6325. for (const auto *F : ClassDecl->fields()) {
  6326. if (F->isInvalidDecl())
  6327. continue;
  6328. if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
  6329. continue;
  6330. QualType BaseType = S.Context.getBaseElementType(F->getType());
  6331. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  6332. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  6333. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  6334. BaseType.getCVRQualifiers(),
  6335. ConstArg && !F->isMutable()))
  6336. return false;
  6337. } else if (CSM == Sema::CXXDefaultConstructor) {
  6338. return false;
  6339. }
  6340. }
  6341. // All OK, it's constexpr!
  6342. return true;
  6343. }
  6344. namespace {
  6345. /// RAII object to register a defaulted function as having its exception
  6346. /// specification computed.
  6347. struct ComputingExceptionSpec {
  6348. Sema &S;
  6349. ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
  6350. : S(S) {
  6351. Sema::CodeSynthesisContext Ctx;
  6352. Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
  6353. Ctx.PointOfInstantiation = Loc;
  6354. Ctx.Entity = FD;
  6355. S.pushCodeSynthesisContext(Ctx);
  6356. }
  6357. ~ComputingExceptionSpec() {
  6358. S.popCodeSynthesisContext();
  6359. }
  6360. };
  6361. }
  6362. static Sema::ImplicitExceptionSpecification
  6363. ComputeDefaultedSpecialMemberExceptionSpec(
  6364. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  6365. Sema::InheritedConstructorInfo *ICI);
  6366. static Sema::ImplicitExceptionSpecification
  6367. ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
  6368. FunctionDecl *FD,
  6369. Sema::DefaultedComparisonKind DCK);
  6370. static Sema::ImplicitExceptionSpecification
  6371. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
  6372. auto DFK = S.getDefaultedFunctionKind(FD);
  6373. if (DFK.isSpecialMember())
  6374. return ComputeDefaultedSpecialMemberExceptionSpec(
  6375. S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
  6376. if (DFK.isComparison())
  6377. return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
  6378. DFK.asComparison());
  6379. auto *CD = cast<CXXConstructorDecl>(FD);
  6380. assert(CD->getInheritedConstructor() &&
  6381. "only defaulted functions and inherited constructors have implicit "
  6382. "exception specs");
  6383. Sema::InheritedConstructorInfo ICI(
  6384. S, Loc, CD->getInheritedConstructor().getShadowDecl());
  6385. return ComputeDefaultedSpecialMemberExceptionSpec(
  6386. S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
  6387. }
  6388. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  6389. CXXMethodDecl *MD) {
  6390. FunctionProtoType::ExtProtoInfo EPI;
  6391. // Build an exception specification pointing back at this member.
  6392. EPI.ExceptionSpec.Type = EST_Unevaluated;
  6393. EPI.ExceptionSpec.SourceDecl = MD;
  6394. // Set the calling convention to the default for C++ instance methods.
  6395. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  6396. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  6397. /*IsCXXMethod=*/true));
  6398. return EPI;
  6399. }
  6400. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
  6401. const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
  6402. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  6403. return;
  6404. // Evaluate the exception specification.
  6405. auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
  6406. auto ESI = IES.getExceptionSpec();
  6407. // Update the type of the special member to use it.
  6408. UpdateExceptionSpec(FD, ESI);
  6409. }
  6410. void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
  6411. assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
  6412. DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
  6413. if (!DefKind) {
  6414. assert(FD->getDeclContext()->isDependentContext());
  6415. return;
  6416. }
  6417. if (DefKind.isComparison())
  6418. UnusedPrivateFields.clear();
  6419. if (DefKind.isSpecialMember()
  6420. ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
  6421. DefKind.asSpecialMember())
  6422. : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
  6423. FD->setInvalidDecl();
  6424. }
  6425. bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
  6426. CXXSpecialMember CSM) {
  6427. CXXRecordDecl *RD = MD->getParent();
  6428. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  6429. "not an explicitly-defaulted special member");
  6430. // Defer all checking for special members of a dependent type.
  6431. if (RD->isDependentType())
  6432. return false;
  6433. // Whether this was the first-declared instance of the constructor.
  6434. // This affects whether we implicitly add an exception spec and constexpr.
  6435. bool First = MD == MD->getCanonicalDecl();
  6436. bool HadError = false;
  6437. // C++11 [dcl.fct.def.default]p1:
  6438. // A function that is explicitly defaulted shall
  6439. // -- be a special member function [...] (checked elsewhere),
  6440. // -- have the same type (except for ref-qualifiers, and except that a
  6441. // copy operation can take a non-const reference) as an implicit
  6442. // declaration, and
  6443. // -- not have default arguments.
  6444. // C++2a changes the second bullet to instead delete the function if it's
  6445. // defaulted on its first declaration, unless it's "an assignment operator,
  6446. // and its return type differs or its parameter type is not a reference".
  6447. bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
  6448. bool ShouldDeleteForTypeMismatch = false;
  6449. unsigned ExpectedParams = 1;
  6450. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  6451. ExpectedParams = 0;
  6452. if (MD->getNumParams() != ExpectedParams) {
  6453. // This checks for default arguments: a copy or move constructor with a
  6454. // default argument is classified as a default constructor, and assignment
  6455. // operations and destructors can't have default arguments.
  6456. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  6457. << CSM << MD->getSourceRange();
  6458. HadError = true;
  6459. } else if (MD->isVariadic()) {
  6460. if (DeleteOnTypeMismatch)
  6461. ShouldDeleteForTypeMismatch = true;
  6462. else {
  6463. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  6464. << CSM << MD->getSourceRange();
  6465. HadError = true;
  6466. }
  6467. }
  6468. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  6469. bool CanHaveConstParam = false;
  6470. if (CSM == CXXCopyConstructor)
  6471. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  6472. else if (CSM == CXXCopyAssignment)
  6473. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  6474. QualType ReturnType = Context.VoidTy;
  6475. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  6476. // Check for return type matching.
  6477. ReturnType = Type->getReturnType();
  6478. QualType DeclType = Context.getTypeDeclType(RD);
  6479. DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
  6480. QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
  6481. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  6482. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  6483. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  6484. HadError = true;
  6485. }
  6486. // A defaulted special member cannot have cv-qualifiers.
  6487. if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
  6488. if (DeleteOnTypeMismatch)
  6489. ShouldDeleteForTypeMismatch = true;
  6490. else {
  6491. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  6492. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  6493. HadError = true;
  6494. }
  6495. }
  6496. }
  6497. // Check for parameter type matching.
  6498. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  6499. bool HasConstParam = false;
  6500. if (ExpectedParams && ArgType->isReferenceType()) {
  6501. // Argument must be reference to possibly-const T.
  6502. QualType ReferentType = ArgType->getPointeeType();
  6503. HasConstParam = ReferentType.isConstQualified();
  6504. if (ReferentType.isVolatileQualified()) {
  6505. if (DeleteOnTypeMismatch)
  6506. ShouldDeleteForTypeMismatch = true;
  6507. else {
  6508. Diag(MD->getLocation(),
  6509. diag::err_defaulted_special_member_volatile_param) << CSM;
  6510. HadError = true;
  6511. }
  6512. }
  6513. if (HasConstParam && !CanHaveConstParam) {
  6514. if (DeleteOnTypeMismatch)
  6515. ShouldDeleteForTypeMismatch = true;
  6516. else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  6517. Diag(MD->getLocation(),
  6518. diag::err_defaulted_special_member_copy_const_param)
  6519. << (CSM == CXXCopyAssignment);
  6520. // FIXME: Explain why this special member can't be const.
  6521. HadError = true;
  6522. } else {
  6523. Diag(MD->getLocation(),
  6524. diag::err_defaulted_special_member_move_const_param)
  6525. << (CSM == CXXMoveAssignment);
  6526. HadError = true;
  6527. }
  6528. }
  6529. } else if (ExpectedParams) {
  6530. // A copy assignment operator can take its argument by value, but a
  6531. // defaulted one cannot.
  6532. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  6533. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  6534. HadError = true;
  6535. }
  6536. // C++11 [dcl.fct.def.default]p2:
  6537. // An explicitly-defaulted function may be declared constexpr only if it
  6538. // would have been implicitly declared as constexpr,
  6539. // Do not apply this rule to members of class templates, since core issue 1358
  6540. // makes such functions always instantiate to constexpr functions. For
  6541. // functions which cannot be constexpr (for non-constructors in C++11 and for
  6542. // destructors in C++14 and C++17), this is checked elsewhere.
  6543. //
  6544. // FIXME: This should not apply if the member is deleted.
  6545. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  6546. HasConstParam);
  6547. if ((getLangOpts().CPlusPlus20 ||
  6548. (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  6549. : isa<CXXConstructorDecl>(MD))) &&
  6550. MD->isConstexpr() && !Constexpr &&
  6551. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  6552. Diag(MD->getBeginLoc(), MD->isConsteval()
  6553. ? diag::err_incorrect_defaulted_consteval
  6554. : diag::err_incorrect_defaulted_constexpr)
  6555. << CSM;
  6556. // FIXME: Explain why the special member can't be constexpr.
  6557. HadError = true;
  6558. }
  6559. if (First) {
  6560. // C++2a [dcl.fct.def.default]p3:
  6561. // If a function is explicitly defaulted on its first declaration, it is
  6562. // implicitly considered to be constexpr if the implicit declaration
  6563. // would be.
  6564. MD->setConstexprKind(Constexpr ? (MD->isConsteval()
  6565. ? ConstexprSpecKind::Consteval
  6566. : ConstexprSpecKind::Constexpr)
  6567. : ConstexprSpecKind::Unspecified);
  6568. if (!Type->hasExceptionSpec()) {
  6569. // C++2a [except.spec]p3:
  6570. // If a declaration of a function does not have a noexcept-specifier
  6571. // [and] is defaulted on its first declaration, [...] the exception
  6572. // specification is as specified below
  6573. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  6574. EPI.ExceptionSpec.Type = EST_Unevaluated;
  6575. EPI.ExceptionSpec.SourceDecl = MD;
  6576. MD->setType(Context.getFunctionType(ReturnType,
  6577. llvm::makeArrayRef(&ArgType,
  6578. ExpectedParams),
  6579. EPI));
  6580. }
  6581. }
  6582. if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
  6583. if (First) {
  6584. SetDeclDeleted(MD, MD->getLocation());
  6585. if (!inTemplateInstantiation() && !HadError) {
  6586. Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
  6587. if (ShouldDeleteForTypeMismatch) {
  6588. Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
  6589. } else {
  6590. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6591. }
  6592. }
  6593. if (ShouldDeleteForTypeMismatch && !HadError) {
  6594. Diag(MD->getLocation(),
  6595. diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
  6596. }
  6597. } else {
  6598. // C++11 [dcl.fct.def.default]p4:
  6599. // [For a] user-provided explicitly-defaulted function [...] if such a
  6600. // function is implicitly defined as deleted, the program is ill-formed.
  6601. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  6602. assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
  6603. ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
  6604. HadError = true;
  6605. }
  6606. }
  6607. return HadError;
  6608. }
  6609. namespace {
  6610. /// Helper class for building and checking a defaulted comparison.
  6611. ///
  6612. /// Defaulted functions are built in two phases:
  6613. ///
  6614. /// * First, the set of operations that the function will perform are
  6615. /// identified, and some of them are checked. If any of the checked
  6616. /// operations is invalid in certain ways, the comparison function is
  6617. /// defined as deleted and no body is built.
  6618. /// * Then, if the function is not defined as deleted, the body is built.
  6619. ///
  6620. /// This is accomplished by performing two visitation steps over the eventual
  6621. /// body of the function.
  6622. template<typename Derived, typename ResultList, typename Result,
  6623. typename Subobject>
  6624. class DefaultedComparisonVisitor {
  6625. public:
  6626. using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
  6627. DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
  6628. DefaultedComparisonKind DCK)
  6629. : S(S), RD(RD), FD(FD), DCK(DCK) {
  6630. if (auto *Info = FD->getDefaultedFunctionInfo()) {
  6631. // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
  6632. // UnresolvedSet to avoid this copy.
  6633. Fns.assign(Info->getUnqualifiedLookups().begin(),
  6634. Info->getUnqualifiedLookups().end());
  6635. }
  6636. }
  6637. ResultList visit() {
  6638. // The type of an lvalue naming a parameter of this function.
  6639. QualType ParamLvalType =
  6640. FD->getParamDecl(0)->getType().getNonReferenceType();
  6641. ResultList Results;
  6642. switch (DCK) {
  6643. case DefaultedComparisonKind::None:
  6644. llvm_unreachable("not a defaulted comparison");
  6645. case DefaultedComparisonKind::Equal:
  6646. case DefaultedComparisonKind::ThreeWay:
  6647. getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
  6648. return Results;
  6649. case DefaultedComparisonKind::NotEqual:
  6650. case DefaultedComparisonKind::Relational:
  6651. Results.add(getDerived().visitExpandedSubobject(
  6652. ParamLvalType, getDerived().getCompleteObject()));
  6653. return Results;
  6654. }
  6655. llvm_unreachable("");
  6656. }
  6657. protected:
  6658. Derived &getDerived() { return static_cast<Derived&>(*this); }
  6659. /// Visit the expanded list of subobjects of the given type, as specified in
  6660. /// C++2a [class.compare.default].
  6661. ///
  6662. /// \return \c true if the ResultList object said we're done, \c false if not.
  6663. bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
  6664. Qualifiers Quals) {
  6665. // C++2a [class.compare.default]p4:
  6666. // The direct base class subobjects of C
  6667. for (CXXBaseSpecifier &Base : Record->bases())
  6668. if (Results.add(getDerived().visitSubobject(
  6669. S.Context.getQualifiedType(Base.getType(), Quals),
  6670. getDerived().getBase(&Base))))
  6671. return true;
  6672. // followed by the non-static data members of C
  6673. for (FieldDecl *Field : Record->fields()) {
  6674. // Recursively expand anonymous structs.
  6675. if (Field->isAnonymousStructOrUnion()) {
  6676. if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
  6677. Quals))
  6678. return true;
  6679. continue;
  6680. }
  6681. // Figure out the type of an lvalue denoting this field.
  6682. Qualifiers FieldQuals = Quals;
  6683. if (Field->isMutable())
  6684. FieldQuals.removeConst();
  6685. QualType FieldType =
  6686. S.Context.getQualifiedType(Field->getType(), FieldQuals);
  6687. if (Results.add(getDerived().visitSubobject(
  6688. FieldType, getDerived().getField(Field))))
  6689. return true;
  6690. }
  6691. // form a list of subobjects.
  6692. return false;
  6693. }
  6694. Result visitSubobject(QualType Type, Subobject Subobj) {
  6695. // In that list, any subobject of array type is recursively expanded
  6696. const ArrayType *AT = S.Context.getAsArrayType(Type);
  6697. if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
  6698. return getDerived().visitSubobjectArray(CAT->getElementType(),
  6699. CAT->getSize(), Subobj);
  6700. return getDerived().visitExpandedSubobject(Type, Subobj);
  6701. }
  6702. Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
  6703. Subobject Subobj) {
  6704. return getDerived().visitSubobject(Type, Subobj);
  6705. }
  6706. protected:
  6707. Sema &S;
  6708. CXXRecordDecl *RD;
  6709. FunctionDecl *FD;
  6710. DefaultedComparisonKind DCK;
  6711. UnresolvedSet<16> Fns;
  6712. };
  6713. /// Information about a defaulted comparison, as determined by
  6714. /// DefaultedComparisonAnalyzer.
  6715. struct DefaultedComparisonInfo {
  6716. bool Deleted = false;
  6717. bool Constexpr = true;
  6718. ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
  6719. static DefaultedComparisonInfo deleted() {
  6720. DefaultedComparisonInfo Deleted;
  6721. Deleted.Deleted = true;
  6722. return Deleted;
  6723. }
  6724. bool add(const DefaultedComparisonInfo &R) {
  6725. Deleted |= R.Deleted;
  6726. Constexpr &= R.Constexpr;
  6727. Category = commonComparisonType(Category, R.Category);
  6728. return Deleted;
  6729. }
  6730. };
  6731. /// An element in the expanded list of subobjects of a defaulted comparison, as
  6732. /// specified in C++2a [class.compare.default]p4.
  6733. struct DefaultedComparisonSubobject {
  6734. enum { CompleteObject, Member, Base } Kind;
  6735. NamedDecl *Decl;
  6736. SourceLocation Loc;
  6737. };
  6738. /// A visitor over the notional body of a defaulted comparison that determines
  6739. /// whether that body would be deleted or constexpr.
  6740. class DefaultedComparisonAnalyzer
  6741. : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
  6742. DefaultedComparisonInfo,
  6743. DefaultedComparisonInfo,
  6744. DefaultedComparisonSubobject> {
  6745. public:
  6746. enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
  6747. private:
  6748. DiagnosticKind Diagnose;
  6749. public:
  6750. using Base = DefaultedComparisonVisitor;
  6751. using Result = DefaultedComparisonInfo;
  6752. using Subobject = DefaultedComparisonSubobject;
  6753. friend Base;
  6754. DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
  6755. DefaultedComparisonKind DCK,
  6756. DiagnosticKind Diagnose = NoDiagnostics)
  6757. : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
  6758. Result visit() {
  6759. if ((DCK == DefaultedComparisonKind::Equal ||
  6760. DCK == DefaultedComparisonKind::ThreeWay) &&
  6761. RD->hasVariantMembers()) {
  6762. // C++2a [class.compare.default]p2 [P2002R0]:
  6763. // A defaulted comparison operator function for class C is defined as
  6764. // deleted if [...] C has variant members.
  6765. if (Diagnose == ExplainDeleted) {
  6766. S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
  6767. << FD << RD->isUnion() << RD;
  6768. }
  6769. return Result::deleted();
  6770. }
  6771. return Base::visit();
  6772. }
  6773. private:
  6774. Subobject getCompleteObject() {
  6775. return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
  6776. }
  6777. Subobject getBase(CXXBaseSpecifier *Base) {
  6778. return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
  6779. Base->getBaseTypeLoc()};
  6780. }
  6781. Subobject getField(FieldDecl *Field) {
  6782. return Subobject{Subobject::Member, Field, Field->getLocation()};
  6783. }
  6784. Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
  6785. // C++2a [class.compare.default]p2 [P2002R0]:
  6786. // A defaulted <=> or == operator function for class C is defined as
  6787. // deleted if any non-static data member of C is of reference type
  6788. if (Type->isReferenceType()) {
  6789. if (Diagnose == ExplainDeleted) {
  6790. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
  6791. << FD << RD;
  6792. }
  6793. return Result::deleted();
  6794. }
  6795. // [...] Let xi be an lvalue denoting the ith element [...]
  6796. OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
  6797. Expr *Args[] = {&Xi, &Xi};
  6798. // All operators start by trying to apply that same operator recursively.
  6799. OverloadedOperatorKind OO = FD->getOverloadedOperator();
  6800. assert(OO != OO_None && "not an overloaded operator!");
  6801. return visitBinaryOperator(OO, Args, Subobj);
  6802. }
  6803. Result
  6804. visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
  6805. Subobject Subobj,
  6806. OverloadCandidateSet *SpaceshipCandidates = nullptr) {
  6807. // Note that there is no need to consider rewritten candidates here if
  6808. // we've already found there is no viable 'operator<=>' candidate (and are
  6809. // considering synthesizing a '<=>' from '==' and '<').
  6810. OverloadCandidateSet CandidateSet(
  6811. FD->getLocation(), OverloadCandidateSet::CSK_Operator,
  6812. OverloadCandidateSet::OperatorRewriteInfo(
  6813. OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
  6814. /// C++2a [class.compare.default]p1 [P2002R0]:
  6815. /// [...] the defaulted function itself is never a candidate for overload
  6816. /// resolution [...]
  6817. CandidateSet.exclude(FD);
  6818. if (Args[0]->getType()->isOverloadableType())
  6819. S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
  6820. else
  6821. // FIXME: We determine whether this is a valid expression by checking to
  6822. // see if there's a viable builtin operator candidate for it. That isn't
  6823. // really what the rules ask us to do, but should give the right results.
  6824. S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
  6825. Result R;
  6826. OverloadCandidateSet::iterator Best;
  6827. switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
  6828. case OR_Success: {
  6829. // C++2a [class.compare.secondary]p2 [P2002R0]:
  6830. // The operator function [...] is defined as deleted if [...] the
  6831. // candidate selected by overload resolution is not a rewritten
  6832. // candidate.
  6833. if ((DCK == DefaultedComparisonKind::NotEqual ||
  6834. DCK == DefaultedComparisonKind::Relational) &&
  6835. !Best->RewriteKind) {
  6836. if (Diagnose == ExplainDeleted) {
  6837. if (Best->Function) {
  6838. S.Diag(Best->Function->getLocation(),
  6839. diag::note_defaulted_comparison_not_rewritten_callee)
  6840. << FD;
  6841. } else {
  6842. assert(Best->Conversions.size() == 2 &&
  6843. Best->Conversions[0].isUserDefined() &&
  6844. "non-user-defined conversion from class to built-in "
  6845. "comparison");
  6846. S.Diag(Best->Conversions[0]
  6847. .UserDefined.FoundConversionFunction.getDecl()
  6848. ->getLocation(),
  6849. diag::note_defaulted_comparison_not_rewritten_conversion)
  6850. << FD;
  6851. }
  6852. }
  6853. return Result::deleted();
  6854. }
  6855. // Throughout C++2a [class.compare]: if overload resolution does not
  6856. // result in a usable function, the candidate function is defined as
  6857. // deleted. This requires that we selected an accessible function.
  6858. //
  6859. // Note that this only considers the access of the function when named
  6860. // within the type of the subobject, and not the access path for any
  6861. // derived-to-base conversion.
  6862. CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
  6863. if (ArgClass && Best->FoundDecl.getDecl() &&
  6864. Best->FoundDecl.getDecl()->isCXXClassMember()) {
  6865. QualType ObjectType = Subobj.Kind == Subobject::Member
  6866. ? Args[0]->getType()
  6867. : S.Context.getRecordType(RD);
  6868. if (!S.isMemberAccessibleForDeletion(
  6869. ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
  6870. Diagnose == ExplainDeleted
  6871. ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
  6872. << FD << Subobj.Kind << Subobj.Decl
  6873. : S.PDiag()))
  6874. return Result::deleted();
  6875. }
  6876. bool NeedsDeducing =
  6877. OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
  6878. if (FunctionDecl *BestFD = Best->Function) {
  6879. // C++2a [class.compare.default]p3 [P2002R0]:
  6880. // A defaulted comparison function is constexpr-compatible if
  6881. // [...] no overlod resolution performed [...] results in a
  6882. // non-constexpr function.
  6883. assert(!BestFD->isDeleted() && "wrong overload resolution result");
  6884. // If it's not constexpr, explain why not.
  6885. if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
  6886. if (Subobj.Kind != Subobject::CompleteObject)
  6887. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
  6888. << Subobj.Kind << Subobj.Decl;
  6889. S.Diag(BestFD->getLocation(),
  6890. diag::note_defaulted_comparison_not_constexpr_here);
  6891. // Bail out after explaining; we don't want any more notes.
  6892. return Result::deleted();
  6893. }
  6894. R.Constexpr &= BestFD->isConstexpr();
  6895. if (NeedsDeducing) {
  6896. // If any callee has an undeduced return type, deduce it now.
  6897. // FIXME: It's not clear how a failure here should be handled. For
  6898. // now, we produce an eager diagnostic, because that is forward
  6899. // compatible with most (all?) other reasonable options.
  6900. if (BestFD->getReturnType()->isUndeducedType() &&
  6901. S.DeduceReturnType(BestFD, FD->getLocation(),
  6902. /*Diagnose=*/false)) {
  6903. // Don't produce a duplicate error when asked to explain why the
  6904. // comparison is deleted: we diagnosed that when initially checking
  6905. // the defaulted operator.
  6906. if (Diagnose == NoDiagnostics) {
  6907. S.Diag(
  6908. FD->getLocation(),
  6909. diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
  6910. << Subobj.Kind << Subobj.Decl;
  6911. S.Diag(
  6912. Subobj.Loc,
  6913. diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
  6914. << Subobj.Kind << Subobj.Decl;
  6915. S.Diag(BestFD->getLocation(),
  6916. diag::note_defaulted_comparison_cannot_deduce_callee)
  6917. << Subobj.Kind << Subobj.Decl;
  6918. }
  6919. return Result::deleted();
  6920. }
  6921. auto *Info = S.Context.CompCategories.lookupInfoForType(
  6922. BestFD->getCallResultType());
  6923. if (!Info) {
  6924. if (Diagnose == ExplainDeleted) {
  6925. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
  6926. << Subobj.Kind << Subobj.Decl
  6927. << BestFD->getCallResultType().withoutLocalFastQualifiers();
  6928. S.Diag(BestFD->getLocation(),
  6929. diag::note_defaulted_comparison_cannot_deduce_callee)
  6930. << Subobj.Kind << Subobj.Decl;
  6931. }
  6932. return Result::deleted();
  6933. }
  6934. R.Category = Info->Kind;
  6935. }
  6936. } else {
  6937. QualType T = Best->BuiltinParamTypes[0];
  6938. assert(T == Best->BuiltinParamTypes[1] &&
  6939. "builtin comparison for different types?");
  6940. assert(Best->BuiltinParamTypes[2].isNull() &&
  6941. "invalid builtin comparison");
  6942. if (NeedsDeducing) {
  6943. Optional<ComparisonCategoryType> Cat =
  6944. getComparisonCategoryForBuiltinCmp(T);
  6945. assert(Cat && "no category for builtin comparison?");
  6946. R.Category = *Cat;
  6947. }
  6948. }
  6949. // Note that we might be rewriting to a different operator. That call is
  6950. // not considered until we come to actually build the comparison function.
  6951. break;
  6952. }
  6953. case OR_Ambiguous:
  6954. if (Diagnose == ExplainDeleted) {
  6955. unsigned Kind = 0;
  6956. if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
  6957. Kind = OO == OO_EqualEqual ? 1 : 2;
  6958. CandidateSet.NoteCandidates(
  6959. PartialDiagnosticAt(
  6960. Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
  6961. << FD << Kind << Subobj.Kind << Subobj.Decl),
  6962. S, OCD_AmbiguousCandidates, Args);
  6963. }
  6964. R = Result::deleted();
  6965. break;
  6966. case OR_Deleted:
  6967. if (Diagnose == ExplainDeleted) {
  6968. if ((DCK == DefaultedComparisonKind::NotEqual ||
  6969. DCK == DefaultedComparisonKind::Relational) &&
  6970. !Best->RewriteKind) {
  6971. S.Diag(Best->Function->getLocation(),
  6972. diag::note_defaulted_comparison_not_rewritten_callee)
  6973. << FD;
  6974. } else {
  6975. S.Diag(Subobj.Loc,
  6976. diag::note_defaulted_comparison_calls_deleted)
  6977. << FD << Subobj.Kind << Subobj.Decl;
  6978. S.NoteDeletedFunction(Best->Function);
  6979. }
  6980. }
  6981. R = Result::deleted();
  6982. break;
  6983. case OR_No_Viable_Function:
  6984. // If there's no usable candidate, we're done unless we can rewrite a
  6985. // '<=>' in terms of '==' and '<'.
  6986. if (OO == OO_Spaceship &&
  6987. S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
  6988. // For any kind of comparison category return type, we need a usable
  6989. // '==' and a usable '<'.
  6990. if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
  6991. &CandidateSet)))
  6992. R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
  6993. break;
  6994. }
  6995. if (Diagnose == ExplainDeleted) {
  6996. S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
  6997. << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
  6998. // For a three-way comparison, list both the candidates for the
  6999. // original operator and the candidates for the synthesized operator.
  7000. if (SpaceshipCandidates) {
  7001. SpaceshipCandidates->NoteCandidates(
  7002. S, Args,
  7003. SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
  7004. Args, FD->getLocation()));
  7005. S.Diag(Subobj.Loc,
  7006. diag::note_defaulted_comparison_no_viable_function_synthesized)
  7007. << (OO == OO_EqualEqual ? 0 : 1);
  7008. }
  7009. CandidateSet.NoteCandidates(
  7010. S, Args,
  7011. CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
  7012. FD->getLocation()));
  7013. }
  7014. R = Result::deleted();
  7015. break;
  7016. }
  7017. return R;
  7018. }
  7019. };
  7020. /// A list of statements.
  7021. struct StmtListResult {
  7022. bool IsInvalid = false;
  7023. llvm::SmallVector<Stmt*, 16> Stmts;
  7024. bool add(const StmtResult &S) {
  7025. IsInvalid |= S.isInvalid();
  7026. if (IsInvalid)
  7027. return true;
  7028. Stmts.push_back(S.get());
  7029. return false;
  7030. }
  7031. };
  7032. /// A visitor over the notional body of a defaulted comparison that synthesizes
  7033. /// the actual body.
  7034. class DefaultedComparisonSynthesizer
  7035. : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
  7036. StmtListResult, StmtResult,
  7037. std::pair<ExprResult, ExprResult>> {
  7038. SourceLocation Loc;
  7039. unsigned ArrayDepth = 0;
  7040. public:
  7041. using Base = DefaultedComparisonVisitor;
  7042. using ExprPair = std::pair<ExprResult, ExprResult>;
  7043. friend Base;
  7044. DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
  7045. DefaultedComparisonKind DCK,
  7046. SourceLocation BodyLoc)
  7047. : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
  7048. /// Build a suitable function body for this defaulted comparison operator.
  7049. StmtResult build() {
  7050. Sema::CompoundScopeRAII CompoundScope(S);
  7051. StmtListResult Stmts = visit();
  7052. if (Stmts.IsInvalid)
  7053. return StmtError();
  7054. ExprResult RetVal;
  7055. switch (DCK) {
  7056. case DefaultedComparisonKind::None:
  7057. llvm_unreachable("not a defaulted comparison");
  7058. case DefaultedComparisonKind::Equal: {
  7059. // C++2a [class.eq]p3:
  7060. // [...] compar[e] the corresponding elements [...] until the first
  7061. // index i where xi == yi yields [...] false. If no such index exists,
  7062. // V is true. Otherwise, V is false.
  7063. //
  7064. // Join the comparisons with '&&'s and return the result. Use a right
  7065. // fold (traversing the conditions right-to-left), because that
  7066. // short-circuits more naturally.
  7067. auto OldStmts = std::move(Stmts.Stmts);
  7068. Stmts.Stmts.clear();
  7069. ExprResult CmpSoFar;
  7070. // Finish a particular comparison chain.
  7071. auto FinishCmp = [&] {
  7072. if (Expr *Prior = CmpSoFar.get()) {
  7073. // Convert the last expression to 'return ...;'
  7074. if (RetVal.isUnset() && Stmts.Stmts.empty())
  7075. RetVal = CmpSoFar;
  7076. // Convert any prior comparison to 'if (!(...)) return false;'
  7077. else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
  7078. return true;
  7079. CmpSoFar = ExprResult();
  7080. }
  7081. return false;
  7082. };
  7083. for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
  7084. Expr *E = dyn_cast<Expr>(EAsStmt);
  7085. if (!E) {
  7086. // Found an array comparison.
  7087. if (FinishCmp() || Stmts.add(EAsStmt))
  7088. return StmtError();
  7089. continue;
  7090. }
  7091. if (CmpSoFar.isUnset()) {
  7092. CmpSoFar = E;
  7093. continue;
  7094. }
  7095. CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
  7096. if (CmpSoFar.isInvalid())
  7097. return StmtError();
  7098. }
  7099. if (FinishCmp())
  7100. return StmtError();
  7101. std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
  7102. // If no such index exists, V is true.
  7103. if (RetVal.isUnset())
  7104. RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
  7105. break;
  7106. }
  7107. case DefaultedComparisonKind::ThreeWay: {
  7108. // Per C++2a [class.spaceship]p3, as a fallback add:
  7109. // return static_cast<R>(std::strong_ordering::equal);
  7110. QualType StrongOrdering = S.CheckComparisonCategoryType(
  7111. ComparisonCategoryType::StrongOrdering, Loc,
  7112. Sema::ComparisonCategoryUsage::DefaultedOperator);
  7113. if (StrongOrdering.isNull())
  7114. return StmtError();
  7115. VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
  7116. .getValueInfo(ComparisonCategoryResult::Equal)
  7117. ->VD;
  7118. RetVal = getDecl(EqualVD);
  7119. if (RetVal.isInvalid())
  7120. return StmtError();
  7121. RetVal = buildStaticCastToR(RetVal.get());
  7122. break;
  7123. }
  7124. case DefaultedComparisonKind::NotEqual:
  7125. case DefaultedComparisonKind::Relational:
  7126. RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
  7127. break;
  7128. }
  7129. // Build the final return statement.
  7130. if (RetVal.isInvalid())
  7131. return StmtError();
  7132. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
  7133. if (ReturnStmt.isInvalid())
  7134. return StmtError();
  7135. Stmts.Stmts.push_back(ReturnStmt.get());
  7136. return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
  7137. }
  7138. private:
  7139. ExprResult getDecl(ValueDecl *VD) {
  7140. return S.BuildDeclarationNameExpr(
  7141. CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
  7142. }
  7143. ExprResult getParam(unsigned I) {
  7144. ParmVarDecl *PD = FD->getParamDecl(I);
  7145. return getDecl(PD);
  7146. }
  7147. ExprPair getCompleteObject() {
  7148. unsigned Param = 0;
  7149. ExprResult LHS;
  7150. if (isa<CXXMethodDecl>(FD)) {
  7151. // LHS is '*this'.
  7152. LHS = S.ActOnCXXThis(Loc);
  7153. if (!LHS.isInvalid())
  7154. LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
  7155. } else {
  7156. LHS = getParam(Param++);
  7157. }
  7158. ExprResult RHS = getParam(Param++);
  7159. assert(Param == FD->getNumParams());
  7160. return {LHS, RHS};
  7161. }
  7162. ExprPair getBase(CXXBaseSpecifier *Base) {
  7163. ExprPair Obj = getCompleteObject();
  7164. if (Obj.first.isInvalid() || Obj.second.isInvalid())
  7165. return {ExprError(), ExprError()};
  7166. CXXCastPath Path = {Base};
  7167. return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
  7168. CK_DerivedToBase, VK_LValue, &Path),
  7169. S.ImpCastExprToType(Obj.second.get(), Base->getType(),
  7170. CK_DerivedToBase, VK_LValue, &Path)};
  7171. }
  7172. ExprPair getField(FieldDecl *Field) {
  7173. ExprPair Obj = getCompleteObject();
  7174. if (Obj.first.isInvalid() || Obj.second.isInvalid())
  7175. return {ExprError(), ExprError()};
  7176. DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
  7177. DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
  7178. return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
  7179. CXXScopeSpec(), Field, Found, NameInfo),
  7180. S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
  7181. CXXScopeSpec(), Field, Found, NameInfo)};
  7182. }
  7183. // FIXME: When expanding a subobject, register a note in the code synthesis
  7184. // stack to say which subobject we're comparing.
  7185. StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
  7186. if (Cond.isInvalid())
  7187. return StmtError();
  7188. ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
  7189. if (NotCond.isInvalid())
  7190. return StmtError();
  7191. ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
  7192. assert(!False.isInvalid() && "should never fail");
  7193. StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
  7194. if (ReturnFalse.isInvalid())
  7195. return StmtError();
  7196. return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
  7197. S.ActOnCondition(nullptr, Loc, NotCond.get(),
  7198. Sema::ConditionKind::Boolean),
  7199. Loc, ReturnFalse.get(), SourceLocation(), nullptr);
  7200. }
  7201. StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
  7202. ExprPair Subobj) {
  7203. QualType SizeType = S.Context.getSizeType();
  7204. Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
  7205. // Build 'size_t i$n = 0'.
  7206. IdentifierInfo *IterationVarName = nullptr;
  7207. {
  7208. SmallString<8> Str;
  7209. llvm::raw_svector_ostream OS(Str);
  7210. OS << "i" << ArrayDepth;
  7211. IterationVarName = &S.Context.Idents.get(OS.str());
  7212. }
  7213. VarDecl *IterationVar = VarDecl::Create(
  7214. S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
  7215. S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
  7216. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  7217. IterationVar->setInit(
  7218. IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  7219. Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
  7220. auto IterRef = [&] {
  7221. ExprResult Ref = S.BuildDeclarationNameExpr(
  7222. CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
  7223. IterationVar);
  7224. assert(!Ref.isInvalid() && "can't reference our own variable?");
  7225. return Ref.get();
  7226. };
  7227. // Build 'i$n != Size'.
  7228. ExprResult Cond = S.CreateBuiltinBinOp(
  7229. Loc, BO_NE, IterRef(),
  7230. IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
  7231. assert(!Cond.isInvalid() && "should never fail");
  7232. // Build '++i$n'.
  7233. ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
  7234. assert(!Inc.isInvalid() && "should never fail");
  7235. // Build 'a[i$n]' and 'b[i$n]'.
  7236. auto Index = [&](ExprResult E) {
  7237. if (E.isInvalid())
  7238. return ExprError();
  7239. return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
  7240. };
  7241. Subobj.first = Index(Subobj.first);
  7242. Subobj.second = Index(Subobj.second);
  7243. // Compare the array elements.
  7244. ++ArrayDepth;
  7245. StmtResult Substmt = visitSubobject(Type, Subobj);
  7246. --ArrayDepth;
  7247. if (Substmt.isInvalid())
  7248. return StmtError();
  7249. // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
  7250. // For outer levels or for an 'operator<=>' we already have a suitable
  7251. // statement that returns as necessary.
  7252. if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
  7253. assert(DCK == DefaultedComparisonKind::Equal &&
  7254. "should have non-expression statement");
  7255. Substmt = buildIfNotCondReturnFalse(ElemCmp);
  7256. if (Substmt.isInvalid())
  7257. return StmtError();
  7258. }
  7259. // Build 'for (...) ...'
  7260. return S.ActOnForStmt(Loc, Loc, Init,
  7261. S.ActOnCondition(nullptr, Loc, Cond.get(),
  7262. Sema::ConditionKind::Boolean),
  7263. S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
  7264. Substmt.get());
  7265. }
  7266. StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
  7267. if (Obj.first.isInvalid() || Obj.second.isInvalid())
  7268. return StmtError();
  7269. OverloadedOperatorKind OO = FD->getOverloadedOperator();
  7270. BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
  7271. ExprResult Op;
  7272. if (Type->isOverloadableType())
  7273. Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
  7274. Obj.second.get(), /*PerformADL=*/true,
  7275. /*AllowRewrittenCandidates=*/true, FD);
  7276. else
  7277. Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
  7278. if (Op.isInvalid())
  7279. return StmtError();
  7280. switch (DCK) {
  7281. case DefaultedComparisonKind::None:
  7282. llvm_unreachable("not a defaulted comparison");
  7283. case DefaultedComparisonKind::Equal:
  7284. // Per C++2a [class.eq]p2, each comparison is individually contextually
  7285. // converted to bool.
  7286. Op = S.PerformContextuallyConvertToBool(Op.get());
  7287. if (Op.isInvalid())
  7288. return StmtError();
  7289. return Op.get();
  7290. case DefaultedComparisonKind::ThreeWay: {
  7291. // Per C++2a [class.spaceship]p3, form:
  7292. // if (R cmp = static_cast<R>(op); cmp != 0)
  7293. // return cmp;
  7294. QualType R = FD->getReturnType();
  7295. Op = buildStaticCastToR(Op.get());
  7296. if (Op.isInvalid())
  7297. return StmtError();
  7298. // R cmp = ...;
  7299. IdentifierInfo *Name = &S.Context.Idents.get("cmp");
  7300. VarDecl *VD =
  7301. VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
  7302. S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
  7303. S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
  7304. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
  7305. // cmp != 0
  7306. ExprResult VDRef = getDecl(VD);
  7307. if (VDRef.isInvalid())
  7308. return StmtError();
  7309. llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
  7310. Expr *Zero =
  7311. IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
  7312. ExprResult Comp;
  7313. if (VDRef.get()->getType()->isOverloadableType())
  7314. Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
  7315. true, FD);
  7316. else
  7317. Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
  7318. if (Comp.isInvalid())
  7319. return StmtError();
  7320. Sema::ConditionResult Cond = S.ActOnCondition(
  7321. nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
  7322. if (Cond.isInvalid())
  7323. return StmtError();
  7324. // return cmp;
  7325. VDRef = getDecl(VD);
  7326. if (VDRef.isInvalid())
  7327. return StmtError();
  7328. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
  7329. if (ReturnStmt.isInvalid())
  7330. return StmtError();
  7331. // if (...)
  7332. return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
  7333. Loc, ReturnStmt.get(),
  7334. /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
  7335. }
  7336. case DefaultedComparisonKind::NotEqual:
  7337. case DefaultedComparisonKind::Relational:
  7338. // C++2a [class.compare.secondary]p2:
  7339. // Otherwise, the operator function yields x @ y.
  7340. return Op.get();
  7341. }
  7342. llvm_unreachable("");
  7343. }
  7344. /// Build "static_cast<R>(E)".
  7345. ExprResult buildStaticCastToR(Expr *E) {
  7346. QualType R = FD->getReturnType();
  7347. assert(!R->isUndeducedType() && "type should have been deduced already");
  7348. // Don't bother forming a no-op cast in the common case.
  7349. if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
  7350. return E;
  7351. return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
  7352. S.Context.getTrivialTypeSourceInfo(R, Loc), E,
  7353. SourceRange(Loc, Loc), SourceRange(Loc, Loc));
  7354. }
  7355. };
  7356. }
  7357. /// Perform the unqualified lookups that might be needed to form a defaulted
  7358. /// comparison function for the given operator.
  7359. static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
  7360. UnresolvedSetImpl &Operators,
  7361. OverloadedOperatorKind Op) {
  7362. auto Lookup = [&](OverloadedOperatorKind OO) {
  7363. Self.LookupOverloadedOperatorName(OO, S, Operators);
  7364. };
  7365. // Every defaulted operator looks up itself.
  7366. Lookup(Op);
  7367. // ... and the rewritten form of itself, if any.
  7368. if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
  7369. Lookup(ExtraOp);
  7370. // For 'operator<=>', we also form a 'cmp != 0' expression, and might
  7371. // synthesize a three-way comparison from '<' and '=='. In a dependent
  7372. // context, we also need to look up '==' in case we implicitly declare a
  7373. // defaulted 'operator=='.
  7374. if (Op == OO_Spaceship) {
  7375. Lookup(OO_ExclaimEqual);
  7376. Lookup(OO_Less);
  7377. Lookup(OO_EqualEqual);
  7378. }
  7379. }
  7380. bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
  7381. DefaultedComparisonKind DCK) {
  7382. assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
  7383. // Perform any unqualified lookups we're going to need to default this
  7384. // function.
  7385. if (S) {
  7386. UnresolvedSet<32> Operators;
  7387. lookupOperatorsForDefaultedComparison(*this, S, Operators,
  7388. FD->getOverloadedOperator());
  7389. FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
  7390. Context, Operators.pairs()));
  7391. }
  7392. // C++2a [class.compare.default]p1:
  7393. // A defaulted comparison operator function for some class C shall be a
  7394. // non-template function declared in the member-specification of C that is
  7395. // -- a non-static const member of C having one parameter of type
  7396. // const C&, or
  7397. // -- a friend of C having two parameters of type const C& or two
  7398. // parameters of type C.
  7399. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
  7400. bool IsMethod = isa<CXXMethodDecl>(FD);
  7401. if (IsMethod) {
  7402. auto *MD = cast<CXXMethodDecl>(FD);
  7403. assert(!MD->isStatic() && "comparison function cannot be a static member");
  7404. // If we're out-of-class, this is the class we're comparing.
  7405. if (!RD)
  7406. RD = MD->getParent();
  7407. if (!MD->isConst()) {
  7408. SourceLocation InsertLoc;
  7409. if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
  7410. InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
  7411. // Don't diagnose an implicit 'operator=='; we will have diagnosed the
  7412. // corresponding defaulted 'operator<=>' already.
  7413. if (!MD->isImplicit()) {
  7414. Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
  7415. << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
  7416. }
  7417. // Add the 'const' to the type to recover.
  7418. const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
  7419. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7420. EPI.TypeQuals.addConst();
  7421. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  7422. FPT->getParamTypes(), EPI));
  7423. }
  7424. }
  7425. if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
  7426. // Let's not worry about using a variadic template pack here -- who would do
  7427. // such a thing?
  7428. Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
  7429. << int(IsMethod) << int(DCK);
  7430. return true;
  7431. }
  7432. const ParmVarDecl *KnownParm = nullptr;
  7433. for (const ParmVarDecl *Param : FD->parameters()) {
  7434. QualType ParmTy = Param->getType();
  7435. if (ParmTy->isDependentType())
  7436. continue;
  7437. if (!KnownParm) {
  7438. auto CTy = ParmTy;
  7439. // Is it `T const &`?
  7440. bool Ok = !IsMethod;
  7441. QualType ExpectedTy;
  7442. if (RD)
  7443. ExpectedTy = Context.getRecordType(RD);
  7444. if (auto *Ref = CTy->getAs<ReferenceType>()) {
  7445. CTy = Ref->getPointeeType();
  7446. if (RD)
  7447. ExpectedTy.addConst();
  7448. Ok = true;
  7449. }
  7450. // Is T a class?
  7451. if (!Ok) {
  7452. } else if (RD) {
  7453. if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
  7454. Ok = false;
  7455. } else if (auto *CRD = CTy->getAsRecordDecl()) {
  7456. RD = cast<CXXRecordDecl>(CRD);
  7457. } else {
  7458. Ok = false;
  7459. }
  7460. if (Ok) {
  7461. KnownParm = Param;
  7462. } else {
  7463. // Don't diagnose an implicit 'operator=='; we will have diagnosed the
  7464. // corresponding defaulted 'operator<=>' already.
  7465. if (!FD->isImplicit()) {
  7466. if (RD) {
  7467. QualType PlainTy = Context.getRecordType(RD);
  7468. QualType RefTy =
  7469. Context.getLValueReferenceType(PlainTy.withConst());
  7470. Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
  7471. << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
  7472. << Param->getSourceRange();
  7473. } else {
  7474. assert(!IsMethod && "should know expected type for method");
  7475. Diag(FD->getLocation(),
  7476. diag::err_defaulted_comparison_param_unknown)
  7477. << int(DCK) << ParmTy << Param->getSourceRange();
  7478. }
  7479. }
  7480. return true;
  7481. }
  7482. } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
  7483. Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
  7484. << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
  7485. << ParmTy << Param->getSourceRange();
  7486. return true;
  7487. }
  7488. }
  7489. assert(RD && "must have determined class");
  7490. if (IsMethod) {
  7491. } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  7492. // In-class, must be a friend decl.
  7493. assert(FD->getFriendObjectKind() && "expected a friend declaration");
  7494. } else {
  7495. // Out of class, require the defaulted comparison to be a friend (of a
  7496. // complete type).
  7497. if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
  7498. diag::err_defaulted_comparison_not_friend, int(DCK),
  7499. int(1)))
  7500. return true;
  7501. if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
  7502. return FD->getCanonicalDecl() ==
  7503. F->getFriendDecl()->getCanonicalDecl();
  7504. }) == RD->friends().end()) {
  7505. Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
  7506. << int(DCK) << int(0) << RD;
  7507. Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
  7508. return true;
  7509. }
  7510. }
  7511. // C++2a [class.eq]p1, [class.rel]p1:
  7512. // A [defaulted comparison other than <=>] shall have a declared return
  7513. // type bool.
  7514. if (DCK != DefaultedComparisonKind::ThreeWay &&
  7515. !FD->getDeclaredReturnType()->isDependentType() &&
  7516. !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
  7517. Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
  7518. << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
  7519. << FD->getReturnTypeSourceRange();
  7520. return true;
  7521. }
  7522. // C++2a [class.spaceship]p2 [P2002R0]:
  7523. // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
  7524. // R shall not contain a placeholder type.
  7525. if (DCK == DefaultedComparisonKind::ThreeWay &&
  7526. FD->getDeclaredReturnType()->getContainedDeducedType() &&
  7527. !Context.hasSameType(FD->getDeclaredReturnType(),
  7528. Context.getAutoDeductType())) {
  7529. Diag(FD->getLocation(),
  7530. diag::err_defaulted_comparison_deduced_return_type_not_auto)
  7531. << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
  7532. << FD->getReturnTypeSourceRange();
  7533. return true;
  7534. }
  7535. // For a defaulted function in a dependent class, defer all remaining checks
  7536. // until instantiation.
  7537. if (RD->isDependentType())
  7538. return false;
  7539. // Determine whether the function should be defined as deleted.
  7540. DefaultedComparisonInfo Info =
  7541. DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
  7542. bool First = FD == FD->getCanonicalDecl();
  7543. // If we want to delete the function, then do so; there's nothing else to
  7544. // check in that case.
  7545. if (Info.Deleted) {
  7546. if (!First) {
  7547. // C++11 [dcl.fct.def.default]p4:
  7548. // [For a] user-provided explicitly-defaulted function [...] if such a
  7549. // function is implicitly defined as deleted, the program is ill-formed.
  7550. //
  7551. // This is really just a consequence of the general rule that you can
  7552. // only delete a function on its first declaration.
  7553. Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
  7554. << FD->isImplicit() << (int)DCK;
  7555. DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
  7556. DefaultedComparisonAnalyzer::ExplainDeleted)
  7557. .visit();
  7558. return true;
  7559. }
  7560. SetDeclDeleted(FD, FD->getLocation());
  7561. if (!inTemplateInstantiation() && !FD->isImplicit()) {
  7562. Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
  7563. << (int)DCK;
  7564. DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
  7565. DefaultedComparisonAnalyzer::ExplainDeleted)
  7566. .visit();
  7567. }
  7568. return false;
  7569. }
  7570. // C++2a [class.spaceship]p2:
  7571. // The return type is deduced as the common comparison type of R0, R1, ...
  7572. if (DCK == DefaultedComparisonKind::ThreeWay &&
  7573. FD->getDeclaredReturnType()->isUndeducedAutoType()) {
  7574. SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
  7575. if (RetLoc.isInvalid())
  7576. RetLoc = FD->getBeginLoc();
  7577. // FIXME: Should we really care whether we have the complete type and the
  7578. // 'enumerator' constants here? A forward declaration seems sufficient.
  7579. QualType Cat = CheckComparisonCategoryType(
  7580. Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
  7581. if (Cat.isNull())
  7582. return true;
  7583. Context.adjustDeducedFunctionResultType(
  7584. FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
  7585. }
  7586. // C++2a [dcl.fct.def.default]p3 [P2002R0]:
  7587. // An explicitly-defaulted function that is not defined as deleted may be
  7588. // declared constexpr or consteval only if it is constexpr-compatible.
  7589. // C++2a [class.compare.default]p3 [P2002R0]:
  7590. // A defaulted comparison function is constexpr-compatible if it satisfies
  7591. // the requirements for a constexpr function [...]
  7592. // The only relevant requirements are that the parameter and return types are
  7593. // literal types. The remaining conditions are checked by the analyzer.
  7594. if (FD->isConstexpr()) {
  7595. if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
  7596. CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
  7597. !Info.Constexpr) {
  7598. Diag(FD->getBeginLoc(),
  7599. diag::err_incorrect_defaulted_comparison_constexpr)
  7600. << FD->isImplicit() << (int)DCK << FD->isConsteval();
  7601. DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
  7602. DefaultedComparisonAnalyzer::ExplainConstexpr)
  7603. .visit();
  7604. }
  7605. }
  7606. // C++2a [dcl.fct.def.default]p3 [P2002R0]:
  7607. // If a constexpr-compatible function is explicitly defaulted on its first
  7608. // declaration, it is implicitly considered to be constexpr.
  7609. // FIXME: Only applying this to the first declaration seems problematic, as
  7610. // simple reorderings can affect the meaning of the program.
  7611. if (First && !FD->isConstexpr() && Info.Constexpr)
  7612. FD->setConstexprKind(ConstexprSpecKind::Constexpr);
  7613. // C++2a [except.spec]p3:
  7614. // If a declaration of a function does not have a noexcept-specifier
  7615. // [and] is defaulted on its first declaration, [...] the exception
  7616. // specification is as specified below
  7617. if (FD->getExceptionSpecType() == EST_None) {
  7618. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  7619. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  7620. EPI.ExceptionSpec.Type = EST_Unevaluated;
  7621. EPI.ExceptionSpec.SourceDecl = FD;
  7622. FD->setType(Context.getFunctionType(FPT->getReturnType(),
  7623. FPT->getParamTypes(), EPI));
  7624. }
  7625. return false;
  7626. }
  7627. void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
  7628. FunctionDecl *Spaceship) {
  7629. Sema::CodeSynthesisContext Ctx;
  7630. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
  7631. Ctx.PointOfInstantiation = Spaceship->getEndLoc();
  7632. Ctx.Entity = Spaceship;
  7633. pushCodeSynthesisContext(Ctx);
  7634. if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
  7635. EqualEqual->setImplicit();
  7636. popCodeSynthesisContext();
  7637. }
  7638. void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
  7639. DefaultedComparisonKind DCK) {
  7640. assert(FD->isDefaulted() && !FD->isDeleted() &&
  7641. !FD->doesThisDeclarationHaveABody());
  7642. if (FD->willHaveBody() || FD->isInvalidDecl())
  7643. return;
  7644. SynthesizedFunctionScope Scope(*this, FD);
  7645. // Add a context note for diagnostics produced after this point.
  7646. Scope.addContextNote(UseLoc);
  7647. {
  7648. // Build and set up the function body.
  7649. // The first parameter has type maybe-ref-to maybe-const T, use that to get
  7650. // the type of the class being compared.
  7651. auto PT = FD->getParamDecl(0)->getType();
  7652. CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
  7653. SourceLocation BodyLoc =
  7654. FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
  7655. StmtResult Body =
  7656. DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
  7657. if (Body.isInvalid()) {
  7658. FD->setInvalidDecl();
  7659. return;
  7660. }
  7661. FD->setBody(Body.get());
  7662. FD->markUsed(Context);
  7663. }
  7664. // The exception specification is needed because we are defining the
  7665. // function. Note that this will reuse the body we just built.
  7666. ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
  7667. if (ASTMutationListener *L = getASTMutationListener())
  7668. L->CompletedImplicitDefinition(FD);
  7669. }
  7670. static Sema::ImplicitExceptionSpecification
  7671. ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
  7672. FunctionDecl *FD,
  7673. Sema::DefaultedComparisonKind DCK) {
  7674. ComputingExceptionSpec CES(S, FD, Loc);
  7675. Sema::ImplicitExceptionSpecification ExceptSpec(S);
  7676. if (FD->isInvalidDecl())
  7677. return ExceptSpec;
  7678. // The common case is that we just defined the comparison function. In that
  7679. // case, just look at whether the body can throw.
  7680. if (FD->hasBody()) {
  7681. ExceptSpec.CalledStmt(FD->getBody());
  7682. } else {
  7683. // Otherwise, build a body so we can check it. This should ideally only
  7684. // happen when we're not actually marking the function referenced. (This is
  7685. // only really important for efficiency: we don't want to build and throw
  7686. // away bodies for comparison functions more than we strictly need to.)
  7687. // Pretend to synthesize the function body in an unevaluated context.
  7688. // Note that we can't actually just go ahead and define the function here:
  7689. // we are not permitted to mark its callees as referenced.
  7690. Sema::SynthesizedFunctionScope Scope(S, FD);
  7691. EnterExpressionEvaluationContext Context(
  7692. S, Sema::ExpressionEvaluationContext::Unevaluated);
  7693. CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
  7694. SourceLocation BodyLoc =
  7695. FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
  7696. StmtResult Body =
  7697. DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
  7698. if (!Body.isInvalid())
  7699. ExceptSpec.CalledStmt(Body.get());
  7700. // FIXME: Can we hold onto this body and just transform it to potentially
  7701. // evaluated when we're asked to define the function rather than rebuilding
  7702. // it? Either that, or we should only build the bits of the body that we
  7703. // need (the expressions, not the statements).
  7704. }
  7705. return ExceptSpec;
  7706. }
  7707. void Sema::CheckDelayedMemberExceptionSpecs() {
  7708. decltype(DelayedOverridingExceptionSpecChecks) Overriding;
  7709. decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
  7710. std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
  7711. std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
  7712. // Perform any deferred checking of exception specifications for virtual
  7713. // destructors.
  7714. for (auto &Check : Overriding)
  7715. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  7716. // Perform any deferred checking of exception specifications for befriended
  7717. // special members.
  7718. for (auto &Check : Equivalent)
  7719. CheckEquivalentExceptionSpec(Check.second, Check.first);
  7720. }
  7721. namespace {
  7722. /// CRTP base class for visiting operations performed by a special member
  7723. /// function (or inherited constructor).
  7724. template<typename Derived>
  7725. struct SpecialMemberVisitor {
  7726. Sema &S;
  7727. CXXMethodDecl *MD;
  7728. Sema::CXXSpecialMember CSM;
  7729. Sema::InheritedConstructorInfo *ICI;
  7730. // Properties of the special member, computed for convenience.
  7731. bool IsConstructor = false, IsAssignment = false, ConstArg = false;
  7732. SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  7733. Sema::InheritedConstructorInfo *ICI)
  7734. : S(S), MD(MD), CSM(CSM), ICI(ICI) {
  7735. switch (CSM) {
  7736. case Sema::CXXDefaultConstructor:
  7737. case Sema::CXXCopyConstructor:
  7738. case Sema::CXXMoveConstructor:
  7739. IsConstructor = true;
  7740. break;
  7741. case Sema::CXXCopyAssignment:
  7742. case Sema::CXXMoveAssignment:
  7743. IsAssignment = true;
  7744. break;
  7745. case Sema::CXXDestructor:
  7746. break;
  7747. case Sema::CXXInvalid:
  7748. llvm_unreachable("invalid special member kind");
  7749. }
  7750. if (MD->getNumParams()) {
  7751. if (const ReferenceType *RT =
  7752. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  7753. ConstArg = RT->getPointeeType().isConstQualified();
  7754. }
  7755. }
  7756. Derived &getDerived() { return static_cast<Derived&>(*this); }
  7757. /// Is this a "move" special member?
  7758. bool isMove() const {
  7759. return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
  7760. }
  7761. /// Look up the corresponding special member in the given class.
  7762. Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
  7763. unsigned Quals, bool IsMutable) {
  7764. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  7765. ConstArg && !IsMutable);
  7766. }
  7767. /// Look up the constructor for the specified base class to see if it's
  7768. /// overridden due to this being an inherited constructor.
  7769. Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
  7770. if (!ICI)
  7771. return {};
  7772. assert(CSM == Sema::CXXDefaultConstructor);
  7773. auto *BaseCtor =
  7774. cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
  7775. if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
  7776. return MD;
  7777. return {};
  7778. }
  7779. /// A base or member subobject.
  7780. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  7781. /// Get the location to use for a subobject in diagnostics.
  7782. static SourceLocation getSubobjectLoc(Subobject Subobj) {
  7783. // FIXME: For an indirect virtual base, the direct base leading to
  7784. // the indirect virtual base would be a more useful choice.
  7785. if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
  7786. return B->getBaseTypeLoc();
  7787. else
  7788. return Subobj.get<FieldDecl*>()->getLocation();
  7789. }
  7790. enum BasesToVisit {
  7791. /// Visit all non-virtual (direct) bases.
  7792. VisitNonVirtualBases,
  7793. /// Visit all direct bases, virtual or not.
  7794. VisitDirectBases,
  7795. /// Visit all non-virtual bases, and all virtual bases if the class
  7796. /// is not abstract.
  7797. VisitPotentiallyConstructedBases,
  7798. /// Visit all direct or virtual bases.
  7799. VisitAllBases
  7800. };
  7801. // Visit the bases and members of the class.
  7802. bool visit(BasesToVisit Bases) {
  7803. CXXRecordDecl *RD = MD->getParent();
  7804. if (Bases == VisitPotentiallyConstructedBases)
  7805. Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
  7806. for (auto &B : RD->bases())
  7807. if ((Bases == VisitDirectBases || !B.isVirtual()) &&
  7808. getDerived().visitBase(&B))
  7809. return true;
  7810. if (Bases == VisitAllBases)
  7811. for (auto &B : RD->vbases())
  7812. if (getDerived().visitBase(&B))
  7813. return true;
  7814. for (auto *F : RD->fields())
  7815. if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
  7816. getDerived().visitField(F))
  7817. return true;
  7818. return false;
  7819. }
  7820. };
  7821. }
  7822. namespace {
  7823. struct SpecialMemberDeletionInfo
  7824. : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
  7825. bool Diagnose;
  7826. SourceLocation Loc;
  7827. bool AllFieldsAreConst;
  7828. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  7829. Sema::CXXSpecialMember CSM,
  7830. Sema::InheritedConstructorInfo *ICI, bool Diagnose)
  7831. : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
  7832. Loc(MD->getLocation()), AllFieldsAreConst(true) {}
  7833. bool inUnion() const { return MD->getParent()->isUnion(); }
  7834. Sema::CXXSpecialMember getEffectiveCSM() {
  7835. return ICI ? Sema::CXXInvalid : CSM;
  7836. }
  7837. bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
  7838. bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
  7839. bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
  7840. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  7841. bool shouldDeleteForField(FieldDecl *FD);
  7842. bool shouldDeleteForAllConstMembers();
  7843. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  7844. unsigned Quals);
  7845. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  7846. Sema::SpecialMemberOverloadResult SMOR,
  7847. bool IsDtorCallInCtor);
  7848. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  7849. };
  7850. }
  7851. /// Is the given special member inaccessible when used on the given
  7852. /// sub-object.
  7853. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  7854. CXXMethodDecl *target) {
  7855. /// If we're operating on a base class, the object type is the
  7856. /// type of this special member.
  7857. QualType objectTy;
  7858. AccessSpecifier access = target->getAccess();
  7859. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  7860. objectTy = S.Context.getTypeDeclType(MD->getParent());
  7861. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  7862. // If we're operating on a field, the object type is the type of the field.
  7863. } else {
  7864. objectTy = S.Context.getTypeDeclType(target->getParent());
  7865. }
  7866. return S.isMemberAccessibleForDeletion(
  7867. target->getParent(), DeclAccessPair::make(target, access), objectTy);
  7868. }
  7869. /// Check whether we should delete a special member due to the implicit
  7870. /// definition containing a call to a special member of a subobject.
  7871. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  7872. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
  7873. bool IsDtorCallInCtor) {
  7874. CXXMethodDecl *Decl = SMOR.getMethod();
  7875. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  7876. int DiagKind = -1;
  7877. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  7878. DiagKind = !Decl ? 0 : 1;
  7879. else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  7880. DiagKind = 2;
  7881. else if (!isAccessible(Subobj, Decl))
  7882. DiagKind = 3;
  7883. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  7884. !Decl->isTrivial()) {
  7885. // A member of a union must have a trivial corresponding special member.
  7886. // As a weird special case, a destructor call from a union's constructor
  7887. // must be accessible and non-deleted, but need not be trivial. Such a
  7888. // destructor is never actually called, but is semantically checked as
  7889. // if it were.
  7890. DiagKind = 4;
  7891. }
  7892. if (DiagKind == -1)
  7893. return false;
  7894. if (Diagnose) {
  7895. if (Field) {
  7896. S.Diag(Field->getLocation(),
  7897. diag::note_deleted_special_member_class_subobject)
  7898. << getEffectiveCSM() << MD->getParent() << /*IsField*/true
  7899. << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
  7900. } else {
  7901. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  7902. S.Diag(Base->getBeginLoc(),
  7903. diag::note_deleted_special_member_class_subobject)
  7904. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  7905. << Base->getType() << DiagKind << IsDtorCallInCtor
  7906. << /*IsObjCPtr*/false;
  7907. }
  7908. if (DiagKind == 1)
  7909. S.NoteDeletedFunction(Decl);
  7910. // FIXME: Explain inaccessibility if DiagKind == 3.
  7911. }
  7912. return true;
  7913. }
  7914. /// Check whether we should delete a special member function due to having a
  7915. /// direct or virtual base class or non-static data member of class type M.
  7916. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  7917. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  7918. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  7919. bool IsMutable = Field && Field->isMutable();
  7920. // C++11 [class.ctor]p5:
  7921. // -- any direct or virtual base class, or non-static data member with no
  7922. // brace-or-equal-initializer, has class type M (or array thereof) and
  7923. // either M has no default constructor or overload resolution as applied
  7924. // to M's default constructor results in an ambiguity or in a function
  7925. // that is deleted or inaccessible
  7926. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  7927. // -- a direct or virtual base class B that cannot be copied/moved because
  7928. // overload resolution, as applied to B's corresponding special member,
  7929. // results in an ambiguity or a function that is deleted or inaccessible
  7930. // from the defaulted special member
  7931. // C++11 [class.dtor]p5:
  7932. // -- any direct or virtual base class [...] has a type with a destructor
  7933. // that is deleted or inaccessible
  7934. if (!(CSM == Sema::CXXDefaultConstructor &&
  7935. Field && Field->hasInClassInitializer()) &&
  7936. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  7937. false))
  7938. return true;
  7939. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  7940. // -- any direct or virtual base class or non-static data member has a
  7941. // type with a destructor that is deleted or inaccessible
  7942. if (IsConstructor) {
  7943. Sema::SpecialMemberOverloadResult SMOR =
  7944. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  7945. false, false, false, false, false);
  7946. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  7947. return true;
  7948. }
  7949. return false;
  7950. }
  7951. bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
  7952. FieldDecl *FD, QualType FieldType) {
  7953. // The defaulted special functions are defined as deleted if this is a variant
  7954. // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
  7955. // type under ARC.
  7956. if (!FieldType.hasNonTrivialObjCLifetime())
  7957. return false;
  7958. // Don't make the defaulted default constructor defined as deleted if the
  7959. // member has an in-class initializer.
  7960. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
  7961. return false;
  7962. if (Diagnose) {
  7963. auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
  7964. S.Diag(FD->getLocation(),
  7965. diag::note_deleted_special_member_class_subobject)
  7966. << getEffectiveCSM() << ParentClass << /*IsField*/true
  7967. << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
  7968. }
  7969. return true;
  7970. }
  7971. /// Check whether we should delete a special member function due to the class
  7972. /// having a particular direct or virtual base class.
  7973. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  7974. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  7975. // If program is correct, BaseClass cannot be null, but if it is, the error
  7976. // must be reported elsewhere.
  7977. if (!BaseClass)
  7978. return false;
  7979. // If we have an inheriting constructor, check whether we're calling an
  7980. // inherited constructor instead of a default constructor.
  7981. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  7982. if (auto *BaseCtor = SMOR.getMethod()) {
  7983. // Note that we do not check access along this path; other than that,
  7984. // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
  7985. // FIXME: Check that the base has a usable destructor! Sink this into
  7986. // shouldDeleteForClassSubobject.
  7987. if (BaseCtor->isDeleted() && Diagnose) {
  7988. S.Diag(Base->getBeginLoc(),
  7989. diag::note_deleted_special_member_class_subobject)
  7990. << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
  7991. << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
  7992. << /*IsObjCPtr*/false;
  7993. S.NoteDeletedFunction(BaseCtor);
  7994. }
  7995. return BaseCtor->isDeleted();
  7996. }
  7997. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  7998. }
  7999. /// Check whether we should delete a special member function due to the class
  8000. /// having a particular non-static data member.
  8001. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  8002. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  8003. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  8004. if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
  8005. return true;
  8006. if (CSM == Sema::CXXDefaultConstructor) {
  8007. // For a default constructor, all references must be initialized in-class
  8008. // and, if a union, it must have a non-const member.
  8009. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  8010. if (Diagnose)
  8011. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  8012. << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
  8013. return true;
  8014. }
  8015. // C++11 [class.ctor]p5: any non-variant non-static data member of
  8016. // const-qualified type (or array thereof) with no
  8017. // brace-or-equal-initializer does not have a user-provided default
  8018. // constructor.
  8019. if (!inUnion() && FieldType.isConstQualified() &&
  8020. !FD->hasInClassInitializer() &&
  8021. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  8022. if (Diagnose)
  8023. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  8024. << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
  8025. return true;
  8026. }
  8027. if (inUnion() && !FieldType.isConstQualified())
  8028. AllFieldsAreConst = false;
  8029. } else if (CSM == Sema::CXXCopyConstructor) {
  8030. // For a copy constructor, data members must not be of rvalue reference
  8031. // type.
  8032. if (FieldType->isRValueReferenceType()) {
  8033. if (Diagnose)
  8034. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  8035. << MD->getParent() << FD << FieldType;
  8036. return true;
  8037. }
  8038. } else if (IsAssignment) {
  8039. // For an assignment operator, data members must not be of reference type.
  8040. if (FieldType->isReferenceType()) {
  8041. if (Diagnose)
  8042. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  8043. << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
  8044. return true;
  8045. }
  8046. if (!FieldRecord && FieldType.isConstQualified()) {
  8047. // C++11 [class.copy]p23:
  8048. // -- a non-static data member of const non-class type (or array thereof)
  8049. if (Diagnose)
  8050. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  8051. << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
  8052. return true;
  8053. }
  8054. }
  8055. if (FieldRecord) {
  8056. // Some additional restrictions exist on the variant members.
  8057. if (!inUnion() && FieldRecord->isUnion() &&
  8058. FieldRecord->isAnonymousStructOrUnion()) {
  8059. bool AllVariantFieldsAreConst = true;
  8060. // FIXME: Handle anonymous unions declared within anonymous unions.
  8061. for (auto *UI : FieldRecord->fields()) {
  8062. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  8063. if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
  8064. return true;
  8065. if (!UnionFieldType.isConstQualified())
  8066. AllVariantFieldsAreConst = false;
  8067. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  8068. if (UnionFieldRecord &&
  8069. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  8070. UnionFieldType.getCVRQualifiers()))
  8071. return true;
  8072. }
  8073. // At least one member in each anonymous union must be non-const
  8074. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  8075. !FieldRecord->field_empty()) {
  8076. if (Diagnose)
  8077. S.Diag(FieldRecord->getLocation(),
  8078. diag::note_deleted_default_ctor_all_const)
  8079. << !!ICI << MD->getParent() << /*anonymous union*/1;
  8080. return true;
  8081. }
  8082. // Don't check the implicit member of the anonymous union type.
  8083. // This is technically non-conformant but supported, and we have a
  8084. // diagnostic for this elsewhere.
  8085. return false;
  8086. }
  8087. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  8088. FieldType.getCVRQualifiers()))
  8089. return true;
  8090. }
  8091. return false;
  8092. }
  8093. /// C++11 [class.ctor] p5:
  8094. /// A defaulted default constructor for a class X is defined as deleted if
  8095. /// X is a union and all of its variant members are of const-qualified type.
  8096. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  8097. // This is a silly definition, because it gives an empty union a deleted
  8098. // default constructor. Don't do that.
  8099. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
  8100. bool AnyFields = false;
  8101. for (auto *F : MD->getParent()->fields())
  8102. if ((AnyFields = !F->isUnnamedBitfield()))
  8103. break;
  8104. if (!AnyFields)
  8105. return false;
  8106. if (Diagnose)
  8107. S.Diag(MD->getParent()->getLocation(),
  8108. diag::note_deleted_default_ctor_all_const)
  8109. << !!ICI << MD->getParent() << /*not anonymous union*/0;
  8110. return true;
  8111. }
  8112. return false;
  8113. }
  8114. /// Determine whether a defaulted special member function should be defined as
  8115. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  8116. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  8117. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  8118. InheritedConstructorInfo *ICI,
  8119. bool Diagnose) {
  8120. if (MD->isInvalidDecl())
  8121. return false;
  8122. CXXRecordDecl *RD = MD->getParent();
  8123. assert(!RD->isDependentType() && "do deletion after instantiation");
  8124. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  8125. return false;
  8126. // C++11 [expr.lambda.prim]p19:
  8127. // The closure type associated with a lambda-expression has a
  8128. // deleted (8.4.3) default constructor and a deleted copy
  8129. // assignment operator.
  8130. // C++2a adds back these operators if the lambda has no lambda-capture.
  8131. if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
  8132. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  8133. if (Diagnose)
  8134. Diag(RD->getLocation(), diag::note_lambda_decl);
  8135. return true;
  8136. }
  8137. // For an anonymous struct or union, the copy and assignment special members
  8138. // will never be used, so skip the check. For an anonymous union declared at
  8139. // namespace scope, the constructor and destructor are used.
  8140. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  8141. RD->isAnonymousStructOrUnion())
  8142. return false;
  8143. // C++11 [class.copy]p7, p18:
  8144. // If the class definition declares a move constructor or move assignment
  8145. // operator, an implicitly declared copy constructor or copy assignment
  8146. // operator is defined as deleted.
  8147. if (MD->isImplicit() &&
  8148. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  8149. CXXMethodDecl *UserDeclaredMove = nullptr;
  8150. // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
  8151. // deletion of the corresponding copy operation, not both copy operations.
  8152. // MSVC 2015 has adopted the standards conforming behavior.
  8153. bool DeletesOnlyMatchingCopy =
  8154. getLangOpts().MSVCCompat &&
  8155. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
  8156. if (RD->hasUserDeclaredMoveConstructor() &&
  8157. (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
  8158. if (!Diagnose) return true;
  8159. // Find any user-declared move constructor.
  8160. for (auto *I : RD->ctors()) {
  8161. if (I->isMoveConstructor()) {
  8162. UserDeclaredMove = I;
  8163. break;
  8164. }
  8165. }
  8166. assert(UserDeclaredMove);
  8167. } else if (RD->hasUserDeclaredMoveAssignment() &&
  8168. (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
  8169. if (!Diagnose) return true;
  8170. // Find any user-declared move assignment operator.
  8171. for (auto *I : RD->methods()) {
  8172. if (I->isMoveAssignmentOperator()) {
  8173. UserDeclaredMove = I;
  8174. break;
  8175. }
  8176. }
  8177. assert(UserDeclaredMove);
  8178. }
  8179. if (UserDeclaredMove) {
  8180. Diag(UserDeclaredMove->getLocation(),
  8181. diag::note_deleted_copy_user_declared_move)
  8182. << (CSM == CXXCopyAssignment) << RD
  8183. << UserDeclaredMove->isMoveAssignmentOperator();
  8184. return true;
  8185. }
  8186. }
  8187. // Do access control from the special member function
  8188. ContextRAII MethodContext(*this, MD);
  8189. // C++11 [class.dtor]p5:
  8190. // -- for a virtual destructor, lookup of the non-array deallocation function
  8191. // results in an ambiguity or in a function that is deleted or inaccessible
  8192. if (CSM == CXXDestructor && MD->isVirtual()) {
  8193. FunctionDecl *OperatorDelete = nullptr;
  8194. DeclarationName Name =
  8195. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  8196. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  8197. OperatorDelete, /*Diagnose*/false)) {
  8198. if (Diagnose)
  8199. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  8200. return true;
  8201. }
  8202. }
  8203. SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
  8204. // Per DR1611, do not consider virtual bases of constructors of abstract
  8205. // classes, since we are not going to construct them.
  8206. // Per DR1658, do not consider virtual bases of destructors of abstract
  8207. // classes either.
  8208. // Per DR2180, for assignment operators we only assign (and thus only
  8209. // consider) direct bases.
  8210. if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
  8211. : SMI.VisitPotentiallyConstructedBases))
  8212. return true;
  8213. if (SMI.shouldDeleteForAllConstMembers())
  8214. return true;
  8215. if (getLangOpts().CUDA) {
  8216. // We should delete the special member in CUDA mode if target inference
  8217. // failed.
  8218. // For inherited constructors (non-null ICI), CSM may be passed so that MD
  8219. // is treated as certain special member, which may not reflect what special
  8220. // member MD really is. However inferCUDATargetForImplicitSpecialMember
  8221. // expects CSM to match MD, therefore recalculate CSM.
  8222. assert(ICI || CSM == getSpecialMember(MD));
  8223. auto RealCSM = CSM;
  8224. if (ICI)
  8225. RealCSM = getSpecialMember(MD);
  8226. return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
  8227. SMI.ConstArg, Diagnose);
  8228. }
  8229. return false;
  8230. }
  8231. void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
  8232. DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
  8233. assert(DFK && "not a defaultable function");
  8234. assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
  8235. if (DFK.isSpecialMember()) {
  8236. ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
  8237. nullptr, /*Diagnose=*/true);
  8238. } else {
  8239. DefaultedComparisonAnalyzer(
  8240. *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
  8241. DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
  8242. .visit();
  8243. }
  8244. }
  8245. /// Perform lookup for a special member of the specified kind, and determine
  8246. /// whether it is trivial. If the triviality can be determined without the
  8247. /// lookup, skip it. This is intended for use when determining whether a
  8248. /// special member of a containing object is trivial, and thus does not ever
  8249. /// perform overload resolution for default constructors.
  8250. ///
  8251. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  8252. /// member that was most likely to be intended to be trivial, if any.
  8253. ///
  8254. /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
  8255. /// determine whether the special member is trivial.
  8256. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  8257. Sema::CXXSpecialMember CSM, unsigned Quals,
  8258. bool ConstRHS,
  8259. Sema::TrivialABIHandling TAH,
  8260. CXXMethodDecl **Selected) {
  8261. if (Selected)
  8262. *Selected = nullptr;
  8263. switch (CSM) {
  8264. case Sema::CXXInvalid:
  8265. llvm_unreachable("not a special member");
  8266. case Sema::CXXDefaultConstructor:
  8267. // C++11 [class.ctor]p5:
  8268. // A default constructor is trivial if:
  8269. // - all the [direct subobjects] have trivial default constructors
  8270. //
  8271. // Note, no overload resolution is performed in this case.
  8272. if (RD->hasTrivialDefaultConstructor())
  8273. return true;
  8274. if (Selected) {
  8275. // If there's a default constructor which could have been trivial, dig it
  8276. // out. Otherwise, if there's any user-provided default constructor, point
  8277. // to that as an example of why there's not a trivial one.
  8278. CXXConstructorDecl *DefCtor = nullptr;
  8279. if (RD->needsImplicitDefaultConstructor())
  8280. S.DeclareImplicitDefaultConstructor(RD);
  8281. for (auto *CI : RD->ctors()) {
  8282. if (!CI->isDefaultConstructor())
  8283. continue;
  8284. DefCtor = CI;
  8285. if (!DefCtor->isUserProvided())
  8286. break;
  8287. }
  8288. *Selected = DefCtor;
  8289. }
  8290. return false;
  8291. case Sema::CXXDestructor:
  8292. // C++11 [class.dtor]p5:
  8293. // A destructor is trivial if:
  8294. // - all the direct [subobjects] have trivial destructors
  8295. if (RD->hasTrivialDestructor() ||
  8296. (TAH == Sema::TAH_ConsiderTrivialABI &&
  8297. RD->hasTrivialDestructorForCall()))
  8298. return true;
  8299. if (Selected) {
  8300. if (RD->needsImplicitDestructor())
  8301. S.DeclareImplicitDestructor(RD);
  8302. *Selected = RD->getDestructor();
  8303. }
  8304. return false;
  8305. case Sema::CXXCopyConstructor:
  8306. // C++11 [class.copy]p12:
  8307. // A copy constructor is trivial if:
  8308. // - the constructor selected to copy each direct [subobject] is trivial
  8309. if (RD->hasTrivialCopyConstructor() ||
  8310. (TAH == Sema::TAH_ConsiderTrivialABI &&
  8311. RD->hasTrivialCopyConstructorForCall())) {
  8312. if (Quals == Qualifiers::Const)
  8313. // We must either select the trivial copy constructor or reach an
  8314. // ambiguity; no need to actually perform overload resolution.
  8315. return true;
  8316. } else if (!Selected) {
  8317. return false;
  8318. }
  8319. // In C++98, we are not supposed to perform overload resolution here, but we
  8320. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  8321. // cases like B as having a non-trivial copy constructor:
  8322. // struct A { template<typename T> A(T&); };
  8323. // struct B { mutable A a; };
  8324. goto NeedOverloadResolution;
  8325. case Sema::CXXCopyAssignment:
  8326. // C++11 [class.copy]p25:
  8327. // A copy assignment operator is trivial if:
  8328. // - the assignment operator selected to copy each direct [subobject] is
  8329. // trivial
  8330. if (RD->hasTrivialCopyAssignment()) {
  8331. if (Quals == Qualifiers::Const)
  8332. return true;
  8333. } else if (!Selected) {
  8334. return false;
  8335. }
  8336. // In C++98, we are not supposed to perform overload resolution here, but we
  8337. // treat that as a language defect.
  8338. goto NeedOverloadResolution;
  8339. case Sema::CXXMoveConstructor:
  8340. case Sema::CXXMoveAssignment:
  8341. NeedOverloadResolution:
  8342. Sema::SpecialMemberOverloadResult SMOR =
  8343. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  8344. // The standard doesn't describe how to behave if the lookup is ambiguous.
  8345. // We treat it as not making the member non-trivial, just like the standard
  8346. // mandates for the default constructor. This should rarely matter, because
  8347. // the member will also be deleted.
  8348. if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  8349. return true;
  8350. if (!SMOR.getMethod()) {
  8351. assert(SMOR.getKind() ==
  8352. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  8353. return false;
  8354. }
  8355. // We deliberately don't check if we found a deleted special member. We're
  8356. // not supposed to!
  8357. if (Selected)
  8358. *Selected = SMOR.getMethod();
  8359. if (TAH == Sema::TAH_ConsiderTrivialABI &&
  8360. (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
  8361. return SMOR.getMethod()->isTrivialForCall();
  8362. return SMOR.getMethod()->isTrivial();
  8363. }
  8364. llvm_unreachable("unknown special method kind");
  8365. }
  8366. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  8367. for (auto *CI : RD->ctors())
  8368. if (!CI->isImplicit())
  8369. return CI;
  8370. // Look for constructor templates.
  8371. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  8372. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  8373. if (CXXConstructorDecl *CD =
  8374. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  8375. return CD;
  8376. }
  8377. return nullptr;
  8378. }
  8379. /// The kind of subobject we are checking for triviality. The values of this
  8380. /// enumeration are used in diagnostics.
  8381. enum TrivialSubobjectKind {
  8382. /// The subobject is a base class.
  8383. TSK_BaseClass,
  8384. /// The subobject is a non-static data member.
  8385. TSK_Field,
  8386. /// The object is actually the complete object.
  8387. TSK_CompleteObject
  8388. };
  8389. /// Check whether the special member selected for a given type would be trivial.
  8390. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  8391. QualType SubType, bool ConstRHS,
  8392. Sema::CXXSpecialMember CSM,
  8393. TrivialSubobjectKind Kind,
  8394. Sema::TrivialABIHandling TAH, bool Diagnose) {
  8395. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  8396. if (!SubRD)
  8397. return true;
  8398. CXXMethodDecl *Selected;
  8399. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  8400. ConstRHS, TAH, Diagnose ? &Selected : nullptr))
  8401. return true;
  8402. if (Diagnose) {
  8403. if (ConstRHS)
  8404. SubType.addConst();
  8405. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  8406. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  8407. << Kind << SubType.getUnqualifiedType();
  8408. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  8409. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  8410. } else if (!Selected)
  8411. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  8412. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  8413. else if (Selected->isUserProvided()) {
  8414. if (Kind == TSK_CompleteObject)
  8415. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  8416. << Kind << SubType.getUnqualifiedType() << CSM;
  8417. else {
  8418. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  8419. << Kind << SubType.getUnqualifiedType() << CSM;
  8420. S.Diag(Selected->getLocation(), diag::note_declared_at);
  8421. }
  8422. } else {
  8423. if (Kind != TSK_CompleteObject)
  8424. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  8425. << Kind << SubType.getUnqualifiedType() << CSM;
  8426. // Explain why the defaulted or deleted special member isn't trivial.
  8427. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
  8428. Diagnose);
  8429. }
  8430. }
  8431. return false;
  8432. }
  8433. /// Check whether the members of a class type allow a special member to be
  8434. /// trivial.
  8435. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  8436. Sema::CXXSpecialMember CSM,
  8437. bool ConstArg,
  8438. Sema::TrivialABIHandling TAH,
  8439. bool Diagnose) {
  8440. for (const auto *FI : RD->fields()) {
  8441. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  8442. continue;
  8443. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  8444. // Pretend anonymous struct or union members are members of this class.
  8445. if (FI->isAnonymousStructOrUnion()) {
  8446. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  8447. CSM, ConstArg, TAH, Diagnose))
  8448. return false;
  8449. continue;
  8450. }
  8451. // C++11 [class.ctor]p5:
  8452. // A default constructor is trivial if [...]
  8453. // -- no non-static data member of its class has a
  8454. // brace-or-equal-initializer
  8455. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  8456. if (Diagnose)
  8457. S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
  8458. << FI;
  8459. return false;
  8460. }
  8461. // Objective C ARC 4.3.5:
  8462. // [...] nontrivally ownership-qualified types are [...] not trivially
  8463. // default constructible, copy constructible, move constructible, copy
  8464. // assignable, move assignable, or destructible [...]
  8465. if (FieldType.hasNonTrivialObjCLifetime()) {
  8466. if (Diagnose)
  8467. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  8468. << RD << FieldType.getObjCLifetime();
  8469. return false;
  8470. }
  8471. bool ConstRHS = ConstArg && !FI->isMutable();
  8472. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  8473. CSM, TSK_Field, TAH, Diagnose))
  8474. return false;
  8475. }
  8476. return true;
  8477. }
  8478. /// Diagnose why the specified class does not have a trivial special member of
  8479. /// the given kind.
  8480. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  8481. QualType Ty = Context.getRecordType(RD);
  8482. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  8483. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  8484. TSK_CompleteObject, TAH_IgnoreTrivialABI,
  8485. /*Diagnose*/true);
  8486. }
  8487. /// Determine whether a defaulted or deleted special member function is trivial,
  8488. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  8489. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  8490. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  8491. TrivialABIHandling TAH, bool Diagnose) {
  8492. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  8493. CXXRecordDecl *RD = MD->getParent();
  8494. bool ConstArg = false;
  8495. // C++11 [class.copy]p12, p25: [DR1593]
  8496. // A [special member] is trivial if [...] its parameter-type-list is
  8497. // equivalent to the parameter-type-list of an implicit declaration [...]
  8498. switch (CSM) {
  8499. case CXXDefaultConstructor:
  8500. case CXXDestructor:
  8501. // Trivial default constructors and destructors cannot have parameters.
  8502. break;
  8503. case CXXCopyConstructor:
  8504. case CXXCopyAssignment: {
  8505. // Trivial copy operations always have const, non-volatile parameter types.
  8506. ConstArg = true;
  8507. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  8508. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  8509. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  8510. if (Diagnose)
  8511. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  8512. << Param0->getSourceRange() << Param0->getType()
  8513. << Context.getLValueReferenceType(
  8514. Context.getRecordType(RD).withConst());
  8515. return false;
  8516. }
  8517. break;
  8518. }
  8519. case CXXMoveConstructor:
  8520. case CXXMoveAssignment: {
  8521. // Trivial move operations always have non-cv-qualified parameters.
  8522. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  8523. const RValueReferenceType *RT =
  8524. Param0->getType()->getAs<RValueReferenceType>();
  8525. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  8526. if (Diagnose)
  8527. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  8528. << Param0->getSourceRange() << Param0->getType()
  8529. << Context.getRValueReferenceType(Context.getRecordType(RD));
  8530. return false;
  8531. }
  8532. break;
  8533. }
  8534. case CXXInvalid:
  8535. llvm_unreachable("not a special member");
  8536. }
  8537. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  8538. if (Diagnose)
  8539. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  8540. diag::note_nontrivial_default_arg)
  8541. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  8542. return false;
  8543. }
  8544. if (MD->isVariadic()) {
  8545. if (Diagnose)
  8546. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  8547. return false;
  8548. }
  8549. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  8550. // A copy/move [constructor or assignment operator] is trivial if
  8551. // -- the [member] selected to copy/move each direct base class subobject
  8552. // is trivial
  8553. //
  8554. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  8555. // A [default constructor or destructor] is trivial if
  8556. // -- all the direct base classes have trivial [default constructors or
  8557. // destructors]
  8558. for (const auto &BI : RD->bases())
  8559. if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
  8560. ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
  8561. return false;
  8562. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  8563. // A copy/move [constructor or assignment operator] for a class X is
  8564. // trivial if
  8565. // -- for each non-static data member of X that is of class type (or array
  8566. // thereof), the constructor selected to copy/move that member is
  8567. // trivial
  8568. //
  8569. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  8570. // A [default constructor or destructor] is trivial if
  8571. // -- for all of the non-static data members of its class that are of class
  8572. // type (or array thereof), each such class has a trivial [default
  8573. // constructor or destructor]
  8574. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
  8575. return false;
  8576. // C++11 [class.dtor]p5:
  8577. // A destructor is trivial if [...]
  8578. // -- the destructor is not virtual
  8579. if (CSM == CXXDestructor && MD->isVirtual()) {
  8580. if (Diagnose)
  8581. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  8582. return false;
  8583. }
  8584. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  8585. // A [special member] for class X is trivial if [...]
  8586. // -- class X has no virtual functions and no virtual base classes
  8587. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  8588. if (!Diagnose)
  8589. return false;
  8590. if (RD->getNumVBases()) {
  8591. // Check for virtual bases. We already know that the corresponding
  8592. // member in all bases is trivial, so vbases must all be direct.
  8593. CXXBaseSpecifier &BS = *RD->vbases_begin();
  8594. assert(BS.isVirtual());
  8595. Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
  8596. return false;
  8597. }
  8598. // Must have a virtual method.
  8599. for (const auto *MI : RD->methods()) {
  8600. if (MI->isVirtual()) {
  8601. SourceLocation MLoc = MI->getBeginLoc();
  8602. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  8603. return false;
  8604. }
  8605. }
  8606. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  8607. }
  8608. // Looks like it's trivial!
  8609. return true;
  8610. }
  8611. namespace {
  8612. struct FindHiddenVirtualMethod {
  8613. Sema *S;
  8614. CXXMethodDecl *Method;
  8615. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  8616. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  8617. private:
  8618. /// Check whether any most overridden method from MD in Methods
  8619. static bool CheckMostOverridenMethods(
  8620. const CXXMethodDecl *MD,
  8621. const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
  8622. if (MD->size_overridden_methods() == 0)
  8623. return Methods.count(MD->getCanonicalDecl());
  8624. for (const CXXMethodDecl *O : MD->overridden_methods())
  8625. if (CheckMostOverridenMethods(O, Methods))
  8626. return true;
  8627. return false;
  8628. }
  8629. public:
  8630. /// Member lookup function that determines whether a given C++
  8631. /// method overloads virtual methods in a base class without overriding any,
  8632. /// to be used with CXXRecordDecl::lookupInBases().
  8633. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  8634. RecordDecl *BaseRecord =
  8635. Specifier->getType()->castAs<RecordType>()->getDecl();
  8636. DeclarationName Name = Method->getDeclName();
  8637. assert(Name.getNameKind() == DeclarationName::Identifier);
  8638. bool foundSameNameMethod = false;
  8639. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  8640. for (Path.Decls = BaseRecord->lookup(Name).begin();
  8641. Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
  8642. NamedDecl *D = *Path.Decls;
  8643. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  8644. MD = MD->getCanonicalDecl();
  8645. foundSameNameMethod = true;
  8646. // Interested only in hidden virtual methods.
  8647. if (!MD->isVirtual())
  8648. continue;
  8649. // If the method we are checking overrides a method from its base
  8650. // don't warn about the other overloaded methods. Clang deviates from
  8651. // GCC by only diagnosing overloads of inherited virtual functions that
  8652. // do not override any other virtual functions in the base. GCC's
  8653. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  8654. // function from a base class. These cases may be better served by a
  8655. // warning (not specific to virtual functions) on call sites when the
  8656. // call would select a different function from the base class, were it
  8657. // visible.
  8658. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  8659. if (!S->IsOverload(Method, MD, false))
  8660. return true;
  8661. // Collect the overload only if its hidden.
  8662. if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
  8663. overloadedMethods.push_back(MD);
  8664. }
  8665. }
  8666. if (foundSameNameMethod)
  8667. OverloadedMethods.append(overloadedMethods.begin(),
  8668. overloadedMethods.end());
  8669. return foundSameNameMethod;
  8670. }
  8671. };
  8672. } // end anonymous namespace
  8673. /// Add the most overridden methods from MD to Methods
  8674. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  8675. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  8676. if (MD->size_overridden_methods() == 0)
  8677. Methods.insert(MD->getCanonicalDecl());
  8678. else
  8679. for (const CXXMethodDecl *O : MD->overridden_methods())
  8680. AddMostOverridenMethods(O, Methods);
  8681. }
  8682. /// Check if a method overloads virtual methods in a base class without
  8683. /// overriding any.
  8684. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  8685. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  8686. if (!MD->getDeclName().isIdentifier())
  8687. return;
  8688. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  8689. /*bool RecordPaths=*/false,
  8690. /*bool DetectVirtual=*/false);
  8691. FindHiddenVirtualMethod FHVM;
  8692. FHVM.Method = MD;
  8693. FHVM.S = this;
  8694. // Keep the base methods that were overridden or introduced in the subclass
  8695. // by 'using' in a set. A base method not in this set is hidden.
  8696. CXXRecordDecl *DC = MD->getParent();
  8697. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  8698. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  8699. NamedDecl *ND = *I;
  8700. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  8701. ND = shad->getTargetDecl();
  8702. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  8703. AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
  8704. }
  8705. if (DC->lookupInBases(FHVM, Paths))
  8706. OverloadedMethods = FHVM.OverloadedMethods;
  8707. }
  8708. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  8709. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  8710. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  8711. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  8712. PartialDiagnostic PD = PDiag(
  8713. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  8714. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  8715. Diag(overloadedMD->getLocation(), PD);
  8716. }
  8717. }
  8718. /// Diagnose methods which overload virtual methods in a base class
  8719. /// without overriding any.
  8720. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  8721. if (MD->isInvalidDecl())
  8722. return;
  8723. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  8724. return;
  8725. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  8726. FindHiddenVirtualMethods(MD, OverloadedMethods);
  8727. if (!OverloadedMethods.empty()) {
  8728. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  8729. << MD << (OverloadedMethods.size() > 1);
  8730. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  8731. }
  8732. }
  8733. void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
  8734. auto PrintDiagAndRemoveAttr = [&](unsigned N) {
  8735. // No diagnostics if this is a template instantiation.
  8736. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
  8737. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  8738. diag::ext_cannot_use_trivial_abi) << &RD;
  8739. Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
  8740. diag::note_cannot_use_trivial_abi_reason) << &RD << N;
  8741. }
  8742. RD.dropAttr<TrivialABIAttr>();
  8743. };
  8744. // Ill-formed if the copy and move constructors are deleted.
  8745. auto HasNonDeletedCopyOrMoveConstructor = [&]() {
  8746. // If the type is dependent, then assume it might have
  8747. // implicit copy or move ctor because we won't know yet at this point.
  8748. if (RD.isDependentType())
  8749. return true;
  8750. if (RD.needsImplicitCopyConstructor() &&
  8751. !RD.defaultedCopyConstructorIsDeleted())
  8752. return true;
  8753. if (RD.needsImplicitMoveConstructor() &&
  8754. !RD.defaultedMoveConstructorIsDeleted())
  8755. return true;
  8756. for (const CXXConstructorDecl *CD : RD.ctors())
  8757. if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
  8758. return true;
  8759. return false;
  8760. };
  8761. if (!HasNonDeletedCopyOrMoveConstructor()) {
  8762. PrintDiagAndRemoveAttr(0);
  8763. return;
  8764. }
  8765. // Ill-formed if the struct has virtual functions.
  8766. if (RD.isPolymorphic()) {
  8767. PrintDiagAndRemoveAttr(1);
  8768. return;
  8769. }
  8770. for (const auto &B : RD.bases()) {
  8771. // Ill-formed if the base class is non-trivial for the purpose of calls or a
  8772. // virtual base.
  8773. if (!B.getType()->isDependentType() &&
  8774. !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
  8775. PrintDiagAndRemoveAttr(2);
  8776. return;
  8777. }
  8778. if (B.isVirtual()) {
  8779. PrintDiagAndRemoveAttr(3);
  8780. return;
  8781. }
  8782. }
  8783. for (const auto *FD : RD.fields()) {
  8784. // Ill-formed if the field is an ObjectiveC pointer or of a type that is
  8785. // non-trivial for the purpose of calls.
  8786. QualType FT = FD->getType();
  8787. if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
  8788. PrintDiagAndRemoveAttr(4);
  8789. return;
  8790. }
  8791. if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
  8792. if (!RT->isDependentType() &&
  8793. !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
  8794. PrintDiagAndRemoveAttr(5);
  8795. return;
  8796. }
  8797. }
  8798. }
  8799. void Sema::ActOnFinishCXXMemberSpecification(
  8800. Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
  8801. SourceLocation RBrac, const ParsedAttributesView &AttrList) {
  8802. if (!TagDecl)
  8803. return;
  8804. AdjustDeclIfTemplate(TagDecl);
  8805. for (const ParsedAttr &AL : AttrList) {
  8806. if (AL.getKind() != ParsedAttr::AT_Visibility)
  8807. continue;
  8808. AL.setInvalid();
  8809. Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
  8810. }
  8811. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  8812. // strict aliasing violation!
  8813. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  8814. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  8815. CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
  8816. }
  8817. /// Find the equality comparison functions that should be implicitly declared
  8818. /// in a given class definition, per C++2a [class.compare.default]p3.
  8819. static void findImplicitlyDeclaredEqualityComparisons(
  8820. ASTContext &Ctx, CXXRecordDecl *RD,
  8821. llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
  8822. DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
  8823. if (!RD->lookup(EqEq).empty())
  8824. // Member operator== explicitly declared: no implicit operator==s.
  8825. return;
  8826. // Traverse friends looking for an '==' or a '<=>'.
  8827. for (FriendDecl *Friend : RD->friends()) {
  8828. FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
  8829. if (!FD) continue;
  8830. if (FD->getOverloadedOperator() == OO_EqualEqual) {
  8831. // Friend operator== explicitly declared: no implicit operator==s.
  8832. Spaceships.clear();
  8833. return;
  8834. }
  8835. if (FD->getOverloadedOperator() == OO_Spaceship &&
  8836. FD->isExplicitlyDefaulted())
  8837. Spaceships.push_back(FD);
  8838. }
  8839. // Look for members named 'operator<=>'.
  8840. DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
  8841. for (NamedDecl *ND : RD->lookup(Cmp)) {
  8842. // Note that we could find a non-function here (either a function template
  8843. // or a using-declaration). Neither case results in an implicit
  8844. // 'operator=='.
  8845. if (auto *FD = dyn_cast<FunctionDecl>(ND))
  8846. if (FD->isExplicitlyDefaulted())
  8847. Spaceships.push_back(FD);
  8848. }
  8849. }
  8850. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  8851. /// special functions, such as the default constructor, copy
  8852. /// constructor, or destructor, to the given C++ class (C++
  8853. /// [special]p1). This routine can only be executed just before the
  8854. /// definition of the class is complete.
  8855. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  8856. // Don't add implicit special members to templated classes.
  8857. // FIXME: This means unqualified lookups for 'operator=' within a class
  8858. // template don't work properly.
  8859. if (!ClassDecl->isDependentType()) {
  8860. if (ClassDecl->needsImplicitDefaultConstructor()) {
  8861. ++getASTContext().NumImplicitDefaultConstructors;
  8862. if (ClassDecl->hasInheritedConstructor())
  8863. DeclareImplicitDefaultConstructor(ClassDecl);
  8864. }
  8865. if (ClassDecl->needsImplicitCopyConstructor()) {
  8866. ++getASTContext().NumImplicitCopyConstructors;
  8867. // If the properties or semantics of the copy constructor couldn't be
  8868. // determined while the class was being declared, force a declaration
  8869. // of it now.
  8870. if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
  8871. ClassDecl->hasInheritedConstructor())
  8872. DeclareImplicitCopyConstructor(ClassDecl);
  8873. // For the MS ABI we need to know whether the copy ctor is deleted. A
  8874. // prerequisite for deleting the implicit copy ctor is that the class has
  8875. // a move ctor or move assignment that is either user-declared or whose
  8876. // semantics are inherited from a subobject. FIXME: We should provide a
  8877. // more direct way for CodeGen to ask whether the constructor was deleted.
  8878. else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  8879. (ClassDecl->hasUserDeclaredMoveConstructor() ||
  8880. ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  8881. ClassDecl->hasUserDeclaredMoveAssignment() ||
  8882. ClassDecl->needsOverloadResolutionForMoveAssignment()))
  8883. DeclareImplicitCopyConstructor(ClassDecl);
  8884. }
  8885. if (getLangOpts().CPlusPlus11 &&
  8886. ClassDecl->needsImplicitMoveConstructor()) {
  8887. ++getASTContext().NumImplicitMoveConstructors;
  8888. if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
  8889. ClassDecl->hasInheritedConstructor())
  8890. DeclareImplicitMoveConstructor(ClassDecl);
  8891. }
  8892. if (ClassDecl->needsImplicitCopyAssignment()) {
  8893. ++getASTContext().NumImplicitCopyAssignmentOperators;
  8894. // If we have a dynamic class, then the copy assignment operator may be
  8895. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  8896. // it shows up in the right place in the vtable and that we diagnose
  8897. // problems with the implicit exception specification.
  8898. if (ClassDecl->isDynamicClass() ||
  8899. ClassDecl->needsOverloadResolutionForCopyAssignment() ||
  8900. ClassDecl->hasInheritedAssignment())
  8901. DeclareImplicitCopyAssignment(ClassDecl);
  8902. }
  8903. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  8904. ++getASTContext().NumImplicitMoveAssignmentOperators;
  8905. // Likewise for the move assignment operator.
  8906. if (ClassDecl->isDynamicClass() ||
  8907. ClassDecl->needsOverloadResolutionForMoveAssignment() ||
  8908. ClassDecl->hasInheritedAssignment())
  8909. DeclareImplicitMoveAssignment(ClassDecl);
  8910. }
  8911. if (ClassDecl->needsImplicitDestructor()) {
  8912. ++getASTContext().NumImplicitDestructors;
  8913. // If we have a dynamic class, then the destructor may be virtual, so we
  8914. // have to declare the destructor immediately. This ensures that, e.g., it
  8915. // shows up in the right place in the vtable and that we diagnose problems
  8916. // with the implicit exception specification.
  8917. if (ClassDecl->isDynamicClass() ||
  8918. ClassDecl->needsOverloadResolutionForDestructor())
  8919. DeclareImplicitDestructor(ClassDecl);
  8920. }
  8921. }
  8922. // C++2a [class.compare.default]p3:
  8923. // If the member-specification does not explicitly declare any member or
  8924. // friend named operator==, an == operator function is declared implicitly
  8925. // for each defaulted three-way comparison operator function defined in
  8926. // the member-specification
  8927. // FIXME: Consider doing this lazily.
  8928. // We do this during the initial parse for a class template, not during
  8929. // instantiation, so that we can handle unqualified lookups for 'operator=='
  8930. // when parsing the template.
  8931. if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
  8932. llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
  8933. findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
  8934. DefaultedSpaceships);
  8935. for (auto *FD : DefaultedSpaceships)
  8936. DeclareImplicitEqualityComparison(ClassDecl, FD);
  8937. }
  8938. }
  8939. unsigned
  8940. Sema::ActOnReenterTemplateScope(Decl *D,
  8941. llvm::function_ref<Scope *()> EnterScope) {
  8942. if (!D)
  8943. return 0;
  8944. AdjustDeclIfTemplate(D);
  8945. // In order to get name lookup right, reenter template scopes in order from
  8946. // outermost to innermost.
  8947. SmallVector<TemplateParameterList *, 4> ParameterLists;
  8948. DeclContext *LookupDC = dyn_cast<DeclContext>(D);
  8949. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  8950. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  8951. ParameterLists.push_back(DD->getTemplateParameterList(i));
  8952. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  8953. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  8954. ParameterLists.push_back(FTD->getTemplateParameters());
  8955. } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  8956. LookupDC = VD->getDeclContext();
  8957. if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
  8958. ParameterLists.push_back(VTD->getTemplateParameters());
  8959. else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
  8960. ParameterLists.push_back(PSD->getTemplateParameters());
  8961. }
  8962. } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  8963. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  8964. ParameterLists.push_back(TD->getTemplateParameterList(i));
  8965. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  8966. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  8967. ParameterLists.push_back(CTD->getTemplateParameters());
  8968. else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  8969. ParameterLists.push_back(PSD->getTemplateParameters());
  8970. }
  8971. }
  8972. // FIXME: Alias declarations and concepts.
  8973. unsigned Count = 0;
  8974. Scope *InnermostTemplateScope = nullptr;
  8975. for (TemplateParameterList *Params : ParameterLists) {
  8976. // Ignore explicit specializations; they don't contribute to the template
  8977. // depth.
  8978. if (Params->size() == 0)
  8979. continue;
  8980. InnermostTemplateScope = EnterScope();
  8981. for (NamedDecl *Param : *Params) {
  8982. if (Param->getDeclName()) {
  8983. InnermostTemplateScope->AddDecl(Param);
  8984. IdResolver.AddDecl(Param);
  8985. }
  8986. }
  8987. ++Count;
  8988. }
  8989. // Associate the new template scopes with the corresponding entities.
  8990. if (InnermostTemplateScope) {
  8991. assert(LookupDC && "no enclosing DeclContext for template lookup");
  8992. EnterTemplatedContext(InnermostTemplateScope, LookupDC);
  8993. }
  8994. return Count;
  8995. }
  8996. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  8997. if (!RecordD) return;
  8998. AdjustDeclIfTemplate(RecordD);
  8999. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  9000. PushDeclContext(S, Record);
  9001. }
  9002. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  9003. if (!RecordD) return;
  9004. PopDeclContext();
  9005. }
  9006. /// This is used to implement the constant expression evaluation part of the
  9007. /// attribute enable_if extension. There is nothing in standard C++ which would
  9008. /// require reentering parameters.
  9009. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  9010. if (!Param)
  9011. return;
  9012. S->AddDecl(Param);
  9013. if (Param->getDeclName())
  9014. IdResolver.AddDecl(Param);
  9015. }
  9016. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  9017. /// parsing a top-level (non-nested) C++ class, and we are now
  9018. /// parsing those parts of the given Method declaration that could
  9019. /// not be parsed earlier (C++ [class.mem]p2), such as default
  9020. /// arguments. This action should enter the scope of the given
  9021. /// Method declaration as if we had just parsed the qualified method
  9022. /// name. However, it should not bring the parameters into scope;
  9023. /// that will be performed by ActOnDelayedCXXMethodParameter.
  9024. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  9025. }
  9026. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  9027. /// C++ method declaration. We're (re-)introducing the given
  9028. /// function parameter into scope for use in parsing later parts of
  9029. /// the method declaration. For example, we could see an
  9030. /// ActOnParamDefaultArgument event for this parameter.
  9031. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  9032. if (!ParamD)
  9033. return;
  9034. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  9035. S->AddDecl(Param);
  9036. if (Param->getDeclName())
  9037. IdResolver.AddDecl(Param);
  9038. }
  9039. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  9040. /// processing the delayed method declaration for Method. The method
  9041. /// declaration is now considered finished. There may be a separate
  9042. /// ActOnStartOfFunctionDef action later (not necessarily
  9043. /// immediately!) for this method, if it was also defined inside the
  9044. /// class body.
  9045. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  9046. if (!MethodD)
  9047. return;
  9048. AdjustDeclIfTemplate(MethodD);
  9049. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  9050. // Now that we have our default arguments, check the constructor
  9051. // again. It could produce additional diagnostics or affect whether
  9052. // the class has implicitly-declared destructors, among other
  9053. // things.
  9054. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  9055. CheckConstructor(Constructor);
  9056. // Check the default arguments, which we may have added.
  9057. if (!Method->isInvalidDecl())
  9058. CheckCXXDefaultArguments(Method);
  9059. }
  9060. // Emit the given diagnostic for each non-address-space qualifier.
  9061. // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
  9062. static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
  9063. const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9064. if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
  9065. bool DiagOccured = false;
  9066. FTI.MethodQualifiers->forEachQualifier(
  9067. [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
  9068. SourceLocation SL) {
  9069. // This diagnostic should be emitted on any qualifier except an addr
  9070. // space qualifier. However, forEachQualifier currently doesn't visit
  9071. // addr space qualifiers, so there's no way to write this condition
  9072. // right now; we just diagnose on everything.
  9073. S.Diag(SL, DiagID) << QualName << SourceRange(SL);
  9074. DiagOccured = true;
  9075. });
  9076. if (DiagOccured)
  9077. D.setInvalidType();
  9078. }
  9079. }
  9080. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  9081. /// the well-formedness of the constructor declarator @p D with type @p
  9082. /// R. If there are any errors in the declarator, this routine will
  9083. /// emit diagnostics and set the invalid bit to true. In any case, the type
  9084. /// will be updated to reflect a well-formed type for the constructor and
  9085. /// returned.
  9086. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  9087. StorageClass &SC) {
  9088. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  9089. // C++ [class.ctor]p3:
  9090. // A constructor shall not be virtual (10.3) or static (9.4). A
  9091. // constructor can be invoked for a const, volatile or const
  9092. // volatile object. A constructor shall not be declared const,
  9093. // volatile, or const volatile (9.3.2).
  9094. if (isVirtual) {
  9095. if (!D.isInvalidType())
  9096. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  9097. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  9098. << SourceRange(D.getIdentifierLoc());
  9099. D.setInvalidType();
  9100. }
  9101. if (SC == SC_Static) {
  9102. if (!D.isInvalidType())
  9103. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  9104. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  9105. << SourceRange(D.getIdentifierLoc());
  9106. D.setInvalidType();
  9107. SC = SC_None;
  9108. }
  9109. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  9110. diagnoseIgnoredQualifiers(
  9111. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  9112. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  9113. D.getDeclSpec().getRestrictSpecLoc(),
  9114. D.getDeclSpec().getAtomicSpecLoc());
  9115. D.setInvalidType();
  9116. }
  9117. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
  9118. // C++0x [class.ctor]p4:
  9119. // A constructor shall not be declared with a ref-qualifier.
  9120. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9121. if (FTI.hasRefQualifier()) {
  9122. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  9123. << FTI.RefQualifierIsLValueRef
  9124. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  9125. D.setInvalidType();
  9126. }
  9127. // Rebuild the function type "R" without any type qualifiers (in
  9128. // case any of the errors above fired) and with "void" as the
  9129. // return type, since constructors don't have return types.
  9130. const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
  9131. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  9132. return R;
  9133. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  9134. EPI.TypeQuals = Qualifiers();
  9135. EPI.RefQualifier = RQ_None;
  9136. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
  9137. }
  9138. /// CheckConstructor - Checks a fully-formed constructor for
  9139. /// well-formedness, issuing any diagnostics required. Returns true if
  9140. /// the constructor declarator is invalid.
  9141. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  9142. CXXRecordDecl *ClassDecl
  9143. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  9144. if (!ClassDecl)
  9145. return Constructor->setInvalidDecl();
  9146. // C++ [class.copy]p3:
  9147. // A declaration of a constructor for a class X is ill-formed if
  9148. // its first parameter is of type (optionally cv-qualified) X and
  9149. // either there are no other parameters or else all other
  9150. // parameters have default arguments.
  9151. if (!Constructor->isInvalidDecl() &&
  9152. Constructor->hasOneParamOrDefaultArgs() &&
  9153. Constructor->getTemplateSpecializationKind() !=
  9154. TSK_ImplicitInstantiation) {
  9155. QualType ParamType = Constructor->getParamDecl(0)->getType();
  9156. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  9157. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  9158. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  9159. const char *ConstRef
  9160. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  9161. : " const &";
  9162. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  9163. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  9164. // FIXME: Rather that making the constructor invalid, we should endeavor
  9165. // to fix the type.
  9166. Constructor->setInvalidDecl();
  9167. }
  9168. }
  9169. }
  9170. /// CheckDestructor - Checks a fully-formed destructor definition for
  9171. /// well-formedness, issuing any diagnostics required. Returns true
  9172. /// on error.
  9173. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  9174. CXXRecordDecl *RD = Destructor->getParent();
  9175. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  9176. SourceLocation Loc;
  9177. if (!Destructor->isImplicit())
  9178. Loc = Destructor->getLocation();
  9179. else
  9180. Loc = RD->getLocation();
  9181. // If we have a virtual destructor, look up the deallocation function
  9182. if (FunctionDecl *OperatorDelete =
  9183. FindDeallocationFunctionForDestructor(Loc, RD)) {
  9184. Expr *ThisArg = nullptr;
  9185. // If the notional 'delete this' expression requires a non-trivial
  9186. // conversion from 'this' to the type of a destroying operator delete's
  9187. // first parameter, perform that conversion now.
  9188. if (OperatorDelete->isDestroyingOperatorDelete()) {
  9189. QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
  9190. if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
  9191. // C++ [class.dtor]p13:
  9192. // ... as if for the expression 'delete this' appearing in a
  9193. // non-virtual destructor of the destructor's class.
  9194. ContextRAII SwitchContext(*this, Destructor);
  9195. ExprResult This =
  9196. ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
  9197. assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
  9198. This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
  9199. if (This.isInvalid()) {
  9200. // FIXME: Register this as a context note so that it comes out
  9201. // in the right order.
  9202. Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
  9203. return true;
  9204. }
  9205. ThisArg = This.get();
  9206. }
  9207. }
  9208. DiagnoseUseOfDecl(OperatorDelete, Loc);
  9209. MarkFunctionReferenced(Loc, OperatorDelete);
  9210. Destructor->setOperatorDelete(OperatorDelete, ThisArg);
  9211. }
  9212. }
  9213. return false;
  9214. }
  9215. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  9216. /// the well-formednes of the destructor declarator @p D with type @p
  9217. /// R. If there are any errors in the declarator, this routine will
  9218. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  9219. /// will be updated to reflect a well-formed type for the destructor and
  9220. /// returned.
  9221. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  9222. StorageClass& SC) {
  9223. // C++ [class.dtor]p1:
  9224. // [...] A typedef-name that names a class is a class-name
  9225. // (7.1.3); however, a typedef-name that names a class shall not
  9226. // be used as the identifier in the declarator for a destructor
  9227. // declaration.
  9228. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  9229. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  9230. Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
  9231. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  9232. else if (const TemplateSpecializationType *TST =
  9233. DeclaratorType->getAs<TemplateSpecializationType>())
  9234. if (TST->isTypeAlias())
  9235. Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
  9236. << DeclaratorType << 1;
  9237. // C++ [class.dtor]p2:
  9238. // A destructor is used to destroy objects of its class type. A
  9239. // destructor takes no parameters, and no return type can be
  9240. // specified for it (not even void). The address of a destructor
  9241. // shall not be taken. A destructor shall not be static. A
  9242. // destructor can be invoked for a const, volatile or const
  9243. // volatile object. A destructor shall not be declared const,
  9244. // volatile or const volatile (9.3.2).
  9245. if (SC == SC_Static) {
  9246. if (!D.isInvalidType())
  9247. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  9248. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  9249. << SourceRange(D.getIdentifierLoc())
  9250. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  9251. SC = SC_None;
  9252. }
  9253. if (!D.isInvalidType()) {
  9254. // Destructors don't have return types, but the parser will
  9255. // happily parse something like:
  9256. //
  9257. // class X {
  9258. // float ~X();
  9259. // };
  9260. //
  9261. // The return type will be eliminated later.
  9262. if (D.getDeclSpec().hasTypeSpecifier())
  9263. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  9264. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  9265. << SourceRange(D.getIdentifierLoc());
  9266. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  9267. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  9268. SourceLocation(),
  9269. D.getDeclSpec().getConstSpecLoc(),
  9270. D.getDeclSpec().getVolatileSpecLoc(),
  9271. D.getDeclSpec().getRestrictSpecLoc(),
  9272. D.getDeclSpec().getAtomicSpecLoc());
  9273. D.setInvalidType();
  9274. }
  9275. }
  9276. checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
  9277. // C++0x [class.dtor]p2:
  9278. // A destructor shall not be declared with a ref-qualifier.
  9279. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  9280. if (FTI.hasRefQualifier()) {
  9281. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  9282. << FTI.RefQualifierIsLValueRef
  9283. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  9284. D.setInvalidType();
  9285. }
  9286. // Make sure we don't have any parameters.
  9287. if (FTIHasNonVoidParameters(FTI)) {
  9288. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  9289. // Delete the parameters.
  9290. FTI.freeParams();
  9291. D.setInvalidType();
  9292. }
  9293. // Make sure the destructor isn't variadic.
  9294. if (FTI.isVariadic) {
  9295. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  9296. D.setInvalidType();
  9297. }
  9298. // Rebuild the function type "R" without any type qualifiers or
  9299. // parameters (in case any of the errors above fired) and with
  9300. // "void" as the return type, since destructors don't have return
  9301. // types.
  9302. if (!D.isInvalidType())
  9303. return R;
  9304. const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
  9305. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  9306. EPI.Variadic = false;
  9307. EPI.TypeQuals = Qualifiers();
  9308. EPI.RefQualifier = RQ_None;
  9309. return Context.getFunctionType(Context.VoidTy, None, EPI);
  9310. }
  9311. static void extendLeft(SourceRange &R, SourceRange Before) {
  9312. if (Before.isInvalid())
  9313. return;
  9314. R.setBegin(Before.getBegin());
  9315. if (R.getEnd().isInvalid())
  9316. R.setEnd(Before.getEnd());
  9317. }
  9318. static void extendRight(SourceRange &R, SourceRange After) {
  9319. if (After.isInvalid())
  9320. return;
  9321. if (R.getBegin().isInvalid())
  9322. R.setBegin(After.getBegin());
  9323. R.setEnd(After.getEnd());
  9324. }
  9325. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  9326. /// well-formednes of the conversion function declarator @p D with
  9327. /// type @p R. If there are any errors in the declarator, this routine
  9328. /// will emit diagnostics and return true. Otherwise, it will return
  9329. /// false. Either way, the type @p R will be updated to reflect a
  9330. /// well-formed type for the conversion operator.
  9331. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  9332. StorageClass& SC) {
  9333. // C++ [class.conv.fct]p1:
  9334. // Neither parameter types nor return type can be specified. The
  9335. // type of a conversion function (8.3.5) is "function taking no
  9336. // parameter returning conversion-type-id."
  9337. if (SC == SC_Static) {
  9338. if (!D.isInvalidType())
  9339. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  9340. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  9341. << D.getName().getSourceRange();
  9342. D.setInvalidType();
  9343. SC = SC_None;
  9344. }
  9345. TypeSourceInfo *ConvTSI = nullptr;
  9346. QualType ConvType =
  9347. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  9348. const DeclSpec &DS = D.getDeclSpec();
  9349. if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
  9350. // Conversion functions don't have return types, but the parser will
  9351. // happily parse something like:
  9352. //
  9353. // class X {
  9354. // float operator bool();
  9355. // };
  9356. //
  9357. // The return type will be changed later anyway.
  9358. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  9359. << SourceRange(DS.getTypeSpecTypeLoc())
  9360. << SourceRange(D.getIdentifierLoc());
  9361. D.setInvalidType();
  9362. } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
  9363. // It's also plausible that the user writes type qualifiers in the wrong
  9364. // place, such as:
  9365. // struct S { const operator int(); };
  9366. // FIXME: we could provide a fixit to move the qualifiers onto the
  9367. // conversion type.
  9368. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  9369. << SourceRange(D.getIdentifierLoc()) << 0;
  9370. D.setInvalidType();
  9371. }
  9372. const auto *Proto = R->castAs<FunctionProtoType>();
  9373. // Make sure we don't have any parameters.
  9374. if (Proto->getNumParams() > 0) {
  9375. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  9376. // Delete the parameters.
  9377. D.getFunctionTypeInfo().freeParams();
  9378. D.setInvalidType();
  9379. } else if (Proto->isVariadic()) {
  9380. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  9381. D.setInvalidType();
  9382. }
  9383. // Diagnose "&operator bool()" and other such nonsense. This
  9384. // is actually a gcc extension which we don't support.
  9385. if (Proto->getReturnType() != ConvType) {
  9386. bool NeedsTypedef = false;
  9387. SourceRange Before, After;
  9388. // Walk the chunks and extract information on them for our diagnostic.
  9389. bool PastFunctionChunk = false;
  9390. for (auto &Chunk : D.type_objects()) {
  9391. switch (Chunk.Kind) {
  9392. case DeclaratorChunk::Function:
  9393. if (!PastFunctionChunk) {
  9394. if (Chunk.Fun.HasTrailingReturnType) {
  9395. TypeSourceInfo *TRT = nullptr;
  9396. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  9397. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  9398. }
  9399. PastFunctionChunk = true;
  9400. break;
  9401. }
  9402. LLVM_FALLTHROUGH;
  9403. case DeclaratorChunk::Array:
  9404. NeedsTypedef = true;
  9405. extendRight(After, Chunk.getSourceRange());
  9406. break;
  9407. case DeclaratorChunk::Pointer:
  9408. case DeclaratorChunk::BlockPointer:
  9409. case DeclaratorChunk::Reference:
  9410. case DeclaratorChunk::MemberPointer:
  9411. case DeclaratorChunk::Pipe:
  9412. extendLeft(Before, Chunk.getSourceRange());
  9413. break;
  9414. case DeclaratorChunk::Paren:
  9415. extendLeft(Before, Chunk.Loc);
  9416. extendRight(After, Chunk.EndLoc);
  9417. break;
  9418. }
  9419. }
  9420. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  9421. After.isValid() ? After.getBegin() :
  9422. D.getIdentifierLoc();
  9423. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  9424. DB << Before << After;
  9425. if (!NeedsTypedef) {
  9426. DB << /*don't need a typedef*/0;
  9427. // If we can provide a correct fix-it hint, do so.
  9428. if (After.isInvalid() && ConvTSI) {
  9429. SourceLocation InsertLoc =
  9430. getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
  9431. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  9432. << FixItHint::CreateInsertionFromRange(
  9433. InsertLoc, CharSourceRange::getTokenRange(Before))
  9434. << FixItHint::CreateRemoval(Before);
  9435. }
  9436. } else if (!Proto->getReturnType()->isDependentType()) {
  9437. DB << /*typedef*/1 << Proto->getReturnType();
  9438. } else if (getLangOpts().CPlusPlus11) {
  9439. DB << /*alias template*/2 << Proto->getReturnType();
  9440. } else {
  9441. DB << /*might not be fixable*/3;
  9442. }
  9443. // Recover by incorporating the other type chunks into the result type.
  9444. // Note, this does *not* change the name of the function. This is compatible
  9445. // with the GCC extension:
  9446. // struct S { &operator int(); } s;
  9447. // int &r = s.operator int(); // ok in GCC
  9448. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  9449. ConvType = Proto->getReturnType();
  9450. }
  9451. // C++ [class.conv.fct]p4:
  9452. // The conversion-type-id shall not represent a function type nor
  9453. // an array type.
  9454. if (ConvType->isArrayType()) {
  9455. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  9456. ConvType = Context.getPointerType(ConvType);
  9457. D.setInvalidType();
  9458. } else if (ConvType->isFunctionType()) {
  9459. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  9460. ConvType = Context.getPointerType(ConvType);
  9461. D.setInvalidType();
  9462. }
  9463. // Rebuild the function type "R" without any parameters (in case any
  9464. // of the errors above fired) and with the conversion type as the
  9465. // return type.
  9466. if (D.isInvalidType())
  9467. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
  9468. // C++0x explicit conversion operators.
  9469. if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
  9470. Diag(DS.getExplicitSpecLoc(),
  9471. getLangOpts().CPlusPlus11
  9472. ? diag::warn_cxx98_compat_explicit_conversion_functions
  9473. : diag::ext_explicit_conversion_functions)
  9474. << SourceRange(DS.getExplicitSpecRange());
  9475. }
  9476. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  9477. /// the declaration of the given C++ conversion function. This routine
  9478. /// is responsible for recording the conversion function in the C++
  9479. /// class, if possible.
  9480. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  9481. assert(Conversion && "Expected to receive a conversion function declaration");
  9482. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  9483. // Make sure we aren't redeclaring the conversion function.
  9484. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  9485. // C++ [class.conv.fct]p1:
  9486. // [...] A conversion function is never used to convert a
  9487. // (possibly cv-qualified) object to the (possibly cv-qualified)
  9488. // same object type (or a reference to it), to a (possibly
  9489. // cv-qualified) base class of that type (or a reference to it),
  9490. // or to (possibly cv-qualified) void.
  9491. QualType ClassType
  9492. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  9493. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  9494. ConvType = ConvTypeRef->getPointeeType();
  9495. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  9496. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  9497. /* Suppress diagnostics for instantiations. */;
  9498. else if (Conversion->size_overridden_methods() != 0)
  9499. /* Suppress diagnostics for overriding virtual function in a base class. */;
  9500. else if (ConvType->isRecordType()) {
  9501. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  9502. if (ConvType == ClassType)
  9503. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  9504. << ClassType;
  9505. else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
  9506. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  9507. << ClassType << ConvType;
  9508. } else if (ConvType->isVoidType()) {
  9509. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  9510. << ClassType << ConvType;
  9511. }
  9512. if (FunctionTemplateDecl *ConversionTemplate
  9513. = Conversion->getDescribedFunctionTemplate())
  9514. return ConversionTemplate;
  9515. return Conversion;
  9516. }
  9517. namespace {
  9518. /// Utility class to accumulate and print a diagnostic listing the invalid
  9519. /// specifier(s) on a declaration.
  9520. struct BadSpecifierDiagnoser {
  9521. BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
  9522. : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
  9523. ~BadSpecifierDiagnoser() {
  9524. Diagnostic << Specifiers;
  9525. }
  9526. template<typename T> void check(SourceLocation SpecLoc, T Spec) {
  9527. return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
  9528. }
  9529. void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
  9530. return check(SpecLoc,
  9531. DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
  9532. }
  9533. void check(SourceLocation SpecLoc, const char *Spec) {
  9534. if (SpecLoc.isInvalid()) return;
  9535. Diagnostic << SourceRange(SpecLoc, SpecLoc);
  9536. if (!Specifiers.empty()) Specifiers += " ";
  9537. Specifiers += Spec;
  9538. }
  9539. Sema &S;
  9540. Sema::SemaDiagnosticBuilder Diagnostic;
  9541. std::string Specifiers;
  9542. };
  9543. }
  9544. /// Check the validity of a declarator that we parsed for a deduction-guide.
  9545. /// These aren't actually declarators in the grammar, so we need to check that
  9546. /// the user didn't specify any pieces that are not part of the deduction-guide
  9547. /// grammar.
  9548. void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
  9549. StorageClass &SC) {
  9550. TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
  9551. TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
  9552. assert(GuidedTemplateDecl && "missing template decl for deduction guide");
  9553. // C++ [temp.deduct.guide]p3:
  9554. // A deduction-gide shall be declared in the same scope as the
  9555. // corresponding class template.
  9556. if (!CurContext->getRedeclContext()->Equals(
  9557. GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
  9558. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
  9559. << GuidedTemplateDecl;
  9560. Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
  9561. }
  9562. auto &DS = D.getMutableDeclSpec();
  9563. // We leave 'friend' and 'virtual' to be rejected in the normal way.
  9564. if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
  9565. DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
  9566. DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
  9567. BadSpecifierDiagnoser Diagnoser(
  9568. *this, D.getIdentifierLoc(),
  9569. diag::err_deduction_guide_invalid_specifier);
  9570. Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
  9571. DS.ClearStorageClassSpecs();
  9572. SC = SC_None;
  9573. // 'explicit' is permitted.
  9574. Diagnoser.check(DS.getInlineSpecLoc(), "inline");
  9575. Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
  9576. Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
  9577. DS.ClearConstexprSpec();
  9578. Diagnoser.check(DS.getConstSpecLoc(), "const");
  9579. Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
  9580. Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
  9581. Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
  9582. Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
  9583. DS.ClearTypeQualifiers();
  9584. Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
  9585. Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
  9586. Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
  9587. Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
  9588. DS.ClearTypeSpecType();
  9589. }
  9590. if (D.isInvalidType())
  9591. return;
  9592. // Check the declarator is simple enough.
  9593. bool FoundFunction = false;
  9594. for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
  9595. if (Chunk.Kind == DeclaratorChunk::Paren)
  9596. continue;
  9597. if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
  9598. Diag(D.getDeclSpec().getBeginLoc(),
  9599. diag::err_deduction_guide_with_complex_decl)
  9600. << D.getSourceRange();
  9601. break;
  9602. }
  9603. if (!Chunk.Fun.hasTrailingReturnType()) {
  9604. Diag(D.getName().getBeginLoc(),
  9605. diag::err_deduction_guide_no_trailing_return_type);
  9606. break;
  9607. }
  9608. // Check that the return type is written as a specialization of
  9609. // the template specified as the deduction-guide's name.
  9610. ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
  9611. TypeSourceInfo *TSI = nullptr;
  9612. QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
  9613. assert(TSI && "deduction guide has valid type but invalid return type?");
  9614. bool AcceptableReturnType = false;
  9615. bool MightInstantiateToSpecialization = false;
  9616. if (auto RetTST =
  9617. TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
  9618. TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
  9619. bool TemplateMatches =
  9620. Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
  9621. if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
  9622. AcceptableReturnType = true;
  9623. else {
  9624. // This could still instantiate to the right type, unless we know it
  9625. // names the wrong class template.
  9626. auto *TD = SpecifiedName.getAsTemplateDecl();
  9627. MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
  9628. !TemplateMatches);
  9629. }
  9630. } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
  9631. MightInstantiateToSpecialization = true;
  9632. }
  9633. if (!AcceptableReturnType) {
  9634. Diag(TSI->getTypeLoc().getBeginLoc(),
  9635. diag::err_deduction_guide_bad_trailing_return_type)
  9636. << GuidedTemplate << TSI->getType()
  9637. << MightInstantiateToSpecialization
  9638. << TSI->getTypeLoc().getSourceRange();
  9639. }
  9640. // Keep going to check that we don't have any inner declarator pieces (we
  9641. // could still have a function returning a pointer to a function).
  9642. FoundFunction = true;
  9643. }
  9644. if (D.isFunctionDefinition())
  9645. Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
  9646. }
  9647. //===----------------------------------------------------------------------===//
  9648. // Namespace Handling
  9649. //===----------------------------------------------------------------------===//
  9650. /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
  9651. /// reopened.
  9652. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  9653. SourceLocation Loc,
  9654. IdentifierInfo *II, bool *IsInline,
  9655. NamespaceDecl *PrevNS) {
  9656. assert(*IsInline != PrevNS->isInline());
  9657. if (PrevNS->isInline())
  9658. // The user probably just forgot the 'inline', so suggest that it
  9659. // be added back.
  9660. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  9661. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  9662. else
  9663. S.Diag(Loc, diag::err_inline_namespace_mismatch);
  9664. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  9665. *IsInline = PrevNS->isInline();
  9666. }
  9667. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  9668. /// definition.
  9669. Decl *Sema::ActOnStartNamespaceDef(
  9670. Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
  9671. SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
  9672. const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
  9673. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  9674. // For anonymous namespace, take the location of the left brace.
  9675. SourceLocation Loc = II ? IdentLoc : LBrace;
  9676. bool IsInline = InlineLoc.isValid();
  9677. bool IsInvalid = false;
  9678. bool IsStd = false;
  9679. bool AddToKnown = false;
  9680. Scope *DeclRegionScope = NamespcScope->getParent();
  9681. NamespaceDecl *PrevNS = nullptr;
  9682. if (II) {
  9683. // C++ [namespace.def]p2:
  9684. // The identifier in an original-namespace-definition shall not
  9685. // have been previously defined in the declarative region in
  9686. // which the original-namespace-definition appears. The
  9687. // identifier in an original-namespace-definition is the name of
  9688. // the namespace. Subsequently in that declarative region, it is
  9689. // treated as an original-namespace-name.
  9690. //
  9691. // Since namespace names are unique in their scope, and we don't
  9692. // look through using directives, just look for any ordinary names
  9693. // as if by qualified name lookup.
  9694. LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
  9695. ForExternalRedeclaration);
  9696. LookupQualifiedName(R, CurContext->getRedeclContext());
  9697. NamedDecl *PrevDecl =
  9698. R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
  9699. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  9700. if (PrevNS) {
  9701. // This is an extended namespace definition.
  9702. if (IsInline != PrevNS->isInline())
  9703. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  9704. &IsInline, PrevNS);
  9705. } else if (PrevDecl) {
  9706. // This is an invalid name redefinition.
  9707. Diag(Loc, diag::err_redefinition_different_kind)
  9708. << II;
  9709. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9710. IsInvalid = true;
  9711. // Continue on to push Namespc as current DeclContext and return it.
  9712. } else if (II->isStr("std") &&
  9713. CurContext->getRedeclContext()->isTranslationUnit()) {
  9714. // This is the first "real" definition of the namespace "std", so update
  9715. // our cache of the "std" namespace to point at this definition.
  9716. PrevNS = getStdNamespace();
  9717. IsStd = true;
  9718. AddToKnown = !IsInline;
  9719. } else {
  9720. // We've seen this namespace for the first time.
  9721. AddToKnown = !IsInline;
  9722. }
  9723. } else {
  9724. // Anonymous namespaces.
  9725. // Determine whether the parent already has an anonymous namespace.
  9726. DeclContext *Parent = CurContext->getRedeclContext();
  9727. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  9728. PrevNS = TU->getAnonymousNamespace();
  9729. } else {
  9730. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  9731. PrevNS = ND->getAnonymousNamespace();
  9732. }
  9733. if (PrevNS && IsInline != PrevNS->isInline())
  9734. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  9735. &IsInline, PrevNS);
  9736. }
  9737. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  9738. StartLoc, Loc, II, PrevNS);
  9739. if (IsInvalid)
  9740. Namespc->setInvalidDecl();
  9741. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  9742. AddPragmaAttributes(DeclRegionScope, Namespc);
  9743. // FIXME: Should we be merging attributes?
  9744. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  9745. PushNamespaceVisibilityAttr(Attr, Loc);
  9746. if (IsStd)
  9747. StdNamespace = Namespc;
  9748. if (AddToKnown)
  9749. KnownNamespaces[Namespc] = false;
  9750. if (II) {
  9751. PushOnScopeChains(Namespc, DeclRegionScope);
  9752. } else {
  9753. // Link the anonymous namespace into its parent.
  9754. DeclContext *Parent = CurContext->getRedeclContext();
  9755. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  9756. TU->setAnonymousNamespace(Namespc);
  9757. } else {
  9758. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  9759. }
  9760. CurContext->addDecl(Namespc);
  9761. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  9762. // behaves as if it were replaced by
  9763. // namespace unique { /* empty body */ }
  9764. // using namespace unique;
  9765. // namespace unique { namespace-body }
  9766. // where all occurrences of 'unique' in a translation unit are
  9767. // replaced by the same identifier and this identifier differs
  9768. // from all other identifiers in the entire program.
  9769. // We just create the namespace with an empty name and then add an
  9770. // implicit using declaration, just like the standard suggests.
  9771. //
  9772. // CodeGen enforces the "universally unique" aspect by giving all
  9773. // declarations semantically contained within an anonymous
  9774. // namespace internal linkage.
  9775. if (!PrevNS) {
  9776. UD = UsingDirectiveDecl::Create(Context, Parent,
  9777. /* 'using' */ LBrace,
  9778. /* 'namespace' */ SourceLocation(),
  9779. /* qualifier */ NestedNameSpecifierLoc(),
  9780. /* identifier */ SourceLocation(),
  9781. Namespc,
  9782. /* Ancestor */ Parent);
  9783. UD->setImplicit();
  9784. Parent->addDecl(UD);
  9785. }
  9786. }
  9787. ActOnDocumentableDecl(Namespc);
  9788. // Although we could have an invalid decl (i.e. the namespace name is a
  9789. // redefinition), push it as current DeclContext and try to continue parsing.
  9790. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  9791. // for the namespace has the declarations that showed up in that particular
  9792. // namespace definition.
  9793. PushDeclContext(NamespcScope, Namespc);
  9794. return Namespc;
  9795. }
  9796. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  9797. /// is a namespace alias, returns the namespace it points to.
  9798. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  9799. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  9800. return AD->getNamespace();
  9801. return dyn_cast_or_null<NamespaceDecl>(D);
  9802. }
  9803. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  9804. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  9805. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  9806. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  9807. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  9808. Namespc->setRBraceLoc(RBrace);
  9809. PopDeclContext();
  9810. if (Namespc->hasAttr<VisibilityAttr>())
  9811. PopPragmaVisibility(true, RBrace);
  9812. // If this namespace contains an export-declaration, export it now.
  9813. if (DeferredExportedNamespaces.erase(Namespc))
  9814. Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  9815. }
  9816. CXXRecordDecl *Sema::getStdBadAlloc() const {
  9817. return cast_or_null<CXXRecordDecl>(
  9818. StdBadAlloc.get(Context.getExternalSource()));
  9819. }
  9820. EnumDecl *Sema::getStdAlignValT() const {
  9821. return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
  9822. }
  9823. NamespaceDecl *Sema::getStdNamespace() const {
  9824. return cast_or_null<NamespaceDecl>(
  9825. StdNamespace.get(Context.getExternalSource()));
  9826. }
  9827. NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
  9828. if (!StdExperimentalNamespaceCache) {
  9829. if (auto Std = getStdNamespace()) {
  9830. LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
  9831. SourceLocation(), LookupNamespaceName);
  9832. if (!LookupQualifiedName(Result, Std) ||
  9833. !(StdExperimentalNamespaceCache =
  9834. Result.getAsSingle<NamespaceDecl>()))
  9835. Result.suppressDiagnostics();
  9836. }
  9837. }
  9838. return StdExperimentalNamespaceCache;
  9839. }
  9840. namespace {
  9841. enum UnsupportedSTLSelect {
  9842. USS_InvalidMember,
  9843. USS_MissingMember,
  9844. USS_NonTrivial,
  9845. USS_Other
  9846. };
  9847. struct InvalidSTLDiagnoser {
  9848. Sema &S;
  9849. SourceLocation Loc;
  9850. QualType TyForDiags;
  9851. QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
  9852. const VarDecl *VD = nullptr) {
  9853. {
  9854. auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
  9855. << TyForDiags << ((int)Sel);
  9856. if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
  9857. assert(!Name.empty());
  9858. D << Name;
  9859. }
  9860. }
  9861. if (Sel == USS_InvalidMember) {
  9862. S.Diag(VD->getLocation(), diag::note_var_declared_here)
  9863. << VD << VD->getSourceRange();
  9864. }
  9865. return QualType();
  9866. }
  9867. };
  9868. } // namespace
  9869. QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
  9870. SourceLocation Loc,
  9871. ComparisonCategoryUsage Usage) {
  9872. assert(getLangOpts().CPlusPlus &&
  9873. "Looking for comparison category type outside of C++.");
  9874. // Use an elaborated type for diagnostics which has a name containing the
  9875. // prepended 'std' namespace but not any inline namespace names.
  9876. auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
  9877. auto *NNS =
  9878. NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
  9879. return Context.getElaboratedType(ETK_None, NNS, Info->getType());
  9880. };
  9881. // Check if we've already successfully checked the comparison category type
  9882. // before. If so, skip checking it again.
  9883. ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
  9884. if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
  9885. // The only thing we need to check is that the type has a reachable
  9886. // definition in the current context.
  9887. if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
  9888. return QualType();
  9889. return Info->getType();
  9890. }
  9891. // If lookup failed
  9892. if (!Info) {
  9893. std::string NameForDiags = "std::";
  9894. NameForDiags += ComparisonCategories::getCategoryString(Kind);
  9895. Diag(Loc, diag::err_implied_comparison_category_type_not_found)
  9896. << NameForDiags << (int)Usage;
  9897. return QualType();
  9898. }
  9899. assert(Info->Kind == Kind);
  9900. assert(Info->Record);
  9901. // Update the Record decl in case we encountered a forward declaration on our
  9902. // first pass. FIXME: This is a bit of a hack.
  9903. if (Info->Record->hasDefinition())
  9904. Info->Record = Info->Record->getDefinition();
  9905. if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
  9906. return QualType();
  9907. InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
  9908. if (!Info->Record->isTriviallyCopyable())
  9909. return UnsupportedSTLError(USS_NonTrivial);
  9910. for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
  9911. CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
  9912. // Tolerate empty base classes.
  9913. if (Base->isEmpty())
  9914. continue;
  9915. // Reject STL implementations which have at least one non-empty base.
  9916. return UnsupportedSTLError();
  9917. }
  9918. // Check that the STL has implemented the types using a single integer field.
  9919. // This expectation allows better codegen for builtin operators. We require:
  9920. // (1) The class has exactly one field.
  9921. // (2) The field is an integral or enumeration type.
  9922. auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
  9923. if (std::distance(FIt, FEnd) != 1 ||
  9924. !FIt->getType()->isIntegralOrEnumerationType()) {
  9925. return UnsupportedSTLError();
  9926. }
  9927. // Build each of the require values and store them in Info.
  9928. for (ComparisonCategoryResult CCR :
  9929. ComparisonCategories::getPossibleResultsForType(Kind)) {
  9930. StringRef MemName = ComparisonCategories::getResultString(CCR);
  9931. ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
  9932. if (!ValInfo)
  9933. return UnsupportedSTLError(USS_MissingMember, MemName);
  9934. VarDecl *VD = ValInfo->VD;
  9935. assert(VD && "should not be null!");
  9936. // Attempt to diagnose reasons why the STL definition of this type
  9937. // might be foobar, including it failing to be a constant expression.
  9938. // TODO Handle more ways the lookup or result can be invalid.
  9939. if (!VD->isStaticDataMember() ||
  9940. !VD->isUsableInConstantExpressions(Context))
  9941. return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
  9942. // Attempt to evaluate the var decl as a constant expression and extract
  9943. // the value of its first field as a ICE. If this fails, the STL
  9944. // implementation is not supported.
  9945. if (!ValInfo->hasValidIntValue())
  9946. return UnsupportedSTLError();
  9947. MarkVariableReferenced(Loc, VD);
  9948. }
  9949. // We've successfully built the required types and expressions. Update
  9950. // the cache and return the newly cached value.
  9951. FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
  9952. return Info->getType();
  9953. }
  9954. /// Retrieve the special "std" namespace, which may require us to
  9955. /// implicitly define the namespace.
  9956. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  9957. if (!StdNamespace) {
  9958. // The "std" namespace has not yet been defined, so build one implicitly.
  9959. StdNamespace = NamespaceDecl::Create(Context,
  9960. Context.getTranslationUnitDecl(),
  9961. /*Inline=*/false,
  9962. SourceLocation(), SourceLocation(),
  9963. &PP.getIdentifierTable().get("std"),
  9964. /*PrevDecl=*/nullptr);
  9965. getStdNamespace()->setImplicit(true);
  9966. }
  9967. return getStdNamespace();
  9968. }
  9969. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  9970. assert(getLangOpts().CPlusPlus &&
  9971. "Looking for std::initializer_list outside of C++.");
  9972. // We're looking for implicit instantiations of
  9973. // template <typename E> class std::initializer_list.
  9974. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  9975. return false;
  9976. ClassTemplateDecl *Template = nullptr;
  9977. const TemplateArgument *Arguments = nullptr;
  9978. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  9979. ClassTemplateSpecializationDecl *Specialization =
  9980. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  9981. if (!Specialization)
  9982. return false;
  9983. Template = Specialization->getSpecializedTemplate();
  9984. Arguments = Specialization->getTemplateArgs().data();
  9985. } else if (const TemplateSpecializationType *TST =
  9986. Ty->getAs<TemplateSpecializationType>()) {
  9987. Template = dyn_cast_or_null<ClassTemplateDecl>(
  9988. TST->getTemplateName().getAsTemplateDecl());
  9989. Arguments = TST->getArgs();
  9990. }
  9991. if (!Template)
  9992. return false;
  9993. if (!StdInitializerList) {
  9994. // Haven't recognized std::initializer_list yet, maybe this is it.
  9995. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  9996. if (TemplateClass->getIdentifier() !=
  9997. &PP.getIdentifierTable().get("initializer_list") ||
  9998. !getStdNamespace()->InEnclosingNamespaceSetOf(
  9999. TemplateClass->getDeclContext()))
  10000. return false;
  10001. // This is a template called std::initializer_list, but is it the right
  10002. // template?
  10003. TemplateParameterList *Params = Template->getTemplateParameters();
  10004. if (Params->getMinRequiredArguments() != 1)
  10005. return false;
  10006. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  10007. return false;
  10008. // It's the right template.
  10009. StdInitializerList = Template;
  10010. }
  10011. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  10012. return false;
  10013. // This is an instance of std::initializer_list. Find the argument type.
  10014. if (Element)
  10015. *Element = Arguments[0].getAsType();
  10016. return true;
  10017. }
  10018. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  10019. NamespaceDecl *Std = S.getStdNamespace();
  10020. if (!Std) {
  10021. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  10022. return nullptr;
  10023. }
  10024. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  10025. Loc, Sema::LookupOrdinaryName);
  10026. if (!S.LookupQualifiedName(Result, Std)) {
  10027. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  10028. return nullptr;
  10029. }
  10030. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  10031. if (!Template) {
  10032. Result.suppressDiagnostics();
  10033. // We found something weird. Complain about the first thing we found.
  10034. NamedDecl *Found = *Result.begin();
  10035. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  10036. return nullptr;
  10037. }
  10038. // We found some template called std::initializer_list. Now verify that it's
  10039. // correct.
  10040. TemplateParameterList *Params = Template->getTemplateParameters();
  10041. if (Params->getMinRequiredArguments() != 1 ||
  10042. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  10043. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  10044. return nullptr;
  10045. }
  10046. return Template;
  10047. }
  10048. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  10049. if (!StdInitializerList) {
  10050. StdInitializerList = LookupStdInitializerList(*this, Loc);
  10051. if (!StdInitializerList)
  10052. return QualType();
  10053. }
  10054. TemplateArgumentListInfo Args(Loc, Loc);
  10055. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  10056. Context.getTrivialTypeSourceInfo(Element,
  10057. Loc)));
  10058. return Context.getCanonicalType(
  10059. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  10060. }
  10061. bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
  10062. // C++ [dcl.init.list]p2:
  10063. // A constructor is an initializer-list constructor if its first parameter
  10064. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  10065. // std::initializer_list<E> for some type E, and either there are no other
  10066. // parameters or else all other parameters have default arguments.
  10067. if (!Ctor->hasOneParamOrDefaultArgs())
  10068. return false;
  10069. QualType ArgType = Ctor->getParamDecl(0)->getType();
  10070. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  10071. ArgType = RT->getPointeeType().getUnqualifiedType();
  10072. return isStdInitializerList(ArgType, nullptr);
  10073. }
  10074. /// Determine whether a using statement is in a context where it will be
  10075. /// apply in all contexts.
  10076. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  10077. switch (CurContext->getDeclKind()) {
  10078. case Decl::TranslationUnit:
  10079. return true;
  10080. case Decl::LinkageSpec:
  10081. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  10082. default:
  10083. return false;
  10084. }
  10085. }
  10086. namespace {
  10087. // Callback to only accept typo corrections that are namespaces.
  10088. class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
  10089. public:
  10090. bool ValidateCandidate(const TypoCorrection &candidate) override {
  10091. if (NamedDecl *ND = candidate.getCorrectionDecl())
  10092. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  10093. return false;
  10094. }
  10095. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  10096. return std::make_unique<NamespaceValidatorCCC>(*this);
  10097. }
  10098. };
  10099. }
  10100. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  10101. CXXScopeSpec &SS,
  10102. SourceLocation IdentLoc,
  10103. IdentifierInfo *Ident) {
  10104. R.clear();
  10105. NamespaceValidatorCCC CCC{};
  10106. if (TypoCorrection Corrected =
  10107. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
  10108. Sema::CTK_ErrorRecovery)) {
  10109. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  10110. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  10111. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  10112. Ident->getName().equals(CorrectedStr);
  10113. S.diagnoseTypo(Corrected,
  10114. S.PDiag(diag::err_using_directive_member_suggest)
  10115. << Ident << DC << DroppedSpecifier << SS.getRange(),
  10116. S.PDiag(diag::note_namespace_defined_here));
  10117. } else {
  10118. S.diagnoseTypo(Corrected,
  10119. S.PDiag(diag::err_using_directive_suggest) << Ident,
  10120. S.PDiag(diag::note_namespace_defined_here));
  10121. }
  10122. R.addDecl(Corrected.getFoundDecl());
  10123. return true;
  10124. }
  10125. return false;
  10126. }
  10127. Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
  10128. SourceLocation NamespcLoc, CXXScopeSpec &SS,
  10129. SourceLocation IdentLoc,
  10130. IdentifierInfo *NamespcName,
  10131. const ParsedAttributesView &AttrList) {
  10132. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  10133. assert(NamespcName && "Invalid NamespcName.");
  10134. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  10135. // This can only happen along a recovery path.
  10136. while (S->isTemplateParamScope())
  10137. S = S->getParent();
  10138. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  10139. UsingDirectiveDecl *UDir = nullptr;
  10140. NestedNameSpecifier *Qualifier = nullptr;
  10141. if (SS.isSet())
  10142. Qualifier = SS.getScopeRep();
  10143. // Lookup namespace name.
  10144. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  10145. LookupParsedName(R, S, &SS);
  10146. if (R.isAmbiguous())
  10147. return nullptr;
  10148. if (R.empty()) {
  10149. R.clear();
  10150. // Allow "using namespace std;" or "using namespace ::std;" even if
  10151. // "std" hasn't been defined yet, for GCC compatibility.
  10152. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  10153. NamespcName->isStr("std")) {
  10154. Diag(IdentLoc, diag::ext_using_undefined_std);
  10155. R.addDecl(getOrCreateStdNamespace());
  10156. R.resolveKind();
  10157. }
  10158. // Otherwise, attempt typo correction.
  10159. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  10160. }
  10161. if (!R.empty()) {
  10162. NamedDecl *Named = R.getRepresentativeDecl();
  10163. NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
  10164. assert(NS && "expected namespace decl");
  10165. // The use of a nested name specifier may trigger deprecation warnings.
  10166. DiagnoseUseOfDecl(Named, IdentLoc);
  10167. // C++ [namespace.udir]p1:
  10168. // A using-directive specifies that the names in the nominated
  10169. // namespace can be used in the scope in which the
  10170. // using-directive appears after the using-directive. During
  10171. // unqualified name lookup (3.4.1), the names appear as if they
  10172. // were declared in the nearest enclosing namespace which
  10173. // contains both the using-directive and the nominated
  10174. // namespace. [Note: in this context, "contains" means "contains
  10175. // directly or indirectly". ]
  10176. // Find enclosing context containing both using-directive and
  10177. // nominated namespace.
  10178. DeclContext *CommonAncestor = NS;
  10179. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  10180. CommonAncestor = CommonAncestor->getParent();
  10181. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  10182. SS.getWithLocInContext(Context),
  10183. IdentLoc, Named, CommonAncestor);
  10184. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  10185. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  10186. Diag(IdentLoc, diag::warn_using_directive_in_header);
  10187. }
  10188. PushUsingDirective(S, UDir);
  10189. } else {
  10190. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  10191. }
  10192. if (UDir)
  10193. ProcessDeclAttributeList(S, UDir, AttrList);
  10194. return UDir;
  10195. }
  10196. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  10197. // If the scope has an associated entity and the using directive is at
  10198. // namespace or translation unit scope, add the UsingDirectiveDecl into
  10199. // its lookup structure so qualified name lookup can find it.
  10200. DeclContext *Ctx = S->getEntity();
  10201. if (Ctx && !Ctx->isFunctionOrMethod())
  10202. Ctx->addDecl(UDir);
  10203. else
  10204. // Otherwise, it is at block scope. The using-directives will affect lookup
  10205. // only to the end of the scope.
  10206. S->PushUsingDirective(UDir);
  10207. }
  10208. Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
  10209. SourceLocation UsingLoc,
  10210. SourceLocation TypenameLoc, CXXScopeSpec &SS,
  10211. UnqualifiedId &Name,
  10212. SourceLocation EllipsisLoc,
  10213. const ParsedAttributesView &AttrList) {
  10214. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  10215. if (SS.isEmpty()) {
  10216. Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
  10217. return nullptr;
  10218. }
  10219. switch (Name.getKind()) {
  10220. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  10221. case UnqualifiedIdKind::IK_Identifier:
  10222. case UnqualifiedIdKind::IK_OperatorFunctionId:
  10223. case UnqualifiedIdKind::IK_LiteralOperatorId:
  10224. case UnqualifiedIdKind::IK_ConversionFunctionId:
  10225. break;
  10226. case UnqualifiedIdKind::IK_ConstructorName:
  10227. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  10228. // C++11 inheriting constructors.
  10229. Diag(Name.getBeginLoc(),
  10230. getLangOpts().CPlusPlus11
  10231. ? diag::warn_cxx98_compat_using_decl_constructor
  10232. : diag::err_using_decl_constructor)
  10233. << SS.getRange();
  10234. if (getLangOpts().CPlusPlus11) break;
  10235. return nullptr;
  10236. case UnqualifiedIdKind::IK_DestructorName:
  10237. Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
  10238. return nullptr;
  10239. case UnqualifiedIdKind::IK_TemplateId:
  10240. Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
  10241. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  10242. return nullptr;
  10243. case UnqualifiedIdKind::IK_DeductionGuideName:
  10244. llvm_unreachable("cannot parse qualified deduction guide name");
  10245. }
  10246. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  10247. DeclarationName TargetName = TargetNameInfo.getName();
  10248. if (!TargetName)
  10249. return nullptr;
  10250. // Warn about access declarations.
  10251. if (UsingLoc.isInvalid()) {
  10252. Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
  10253. ? diag::err_access_decl
  10254. : diag::warn_access_decl_deprecated)
  10255. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  10256. }
  10257. if (EllipsisLoc.isInvalid()) {
  10258. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  10259. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  10260. return nullptr;
  10261. } else {
  10262. if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
  10263. !TargetNameInfo.containsUnexpandedParameterPack()) {
  10264. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  10265. << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
  10266. EllipsisLoc = SourceLocation();
  10267. }
  10268. }
  10269. NamedDecl *UD =
  10270. BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
  10271. SS, TargetNameInfo, EllipsisLoc, AttrList,
  10272. /*IsInstantiation*/ false,
  10273. AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
  10274. if (UD)
  10275. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  10276. return UD;
  10277. }
  10278. Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
  10279. SourceLocation UsingLoc,
  10280. SourceLocation EnumLoc,
  10281. const DeclSpec &DS) {
  10282. switch (DS.getTypeSpecType()) {
  10283. case DeclSpec::TST_error:
  10284. // This will already have been diagnosed
  10285. return nullptr;
  10286. case DeclSpec::TST_enum:
  10287. break;
  10288. case DeclSpec::TST_typename:
  10289. Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
  10290. return nullptr;
  10291. default:
  10292. llvm_unreachable("unexpected DeclSpec type");
  10293. }
  10294. // As with enum-decls, we ignore attributes for now.
  10295. auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
  10296. if (auto *Def = Enum->getDefinition())
  10297. Enum = Def;
  10298. auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
  10299. DS.getTypeSpecTypeNameLoc(), Enum);
  10300. if (UD)
  10301. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  10302. return UD;
  10303. }
  10304. /// Determine whether a using declaration considers the given
  10305. /// declarations as "equivalent", e.g., if they are redeclarations of
  10306. /// the same entity or are both typedefs of the same type.
  10307. static bool
  10308. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  10309. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  10310. return true;
  10311. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  10312. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  10313. return Context.hasSameType(TD1->getUnderlyingType(),
  10314. TD2->getUnderlyingType());
  10315. // Two using_if_exists using-declarations are equivalent if both are
  10316. // unresolved.
  10317. if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
  10318. isa<UnresolvedUsingIfExistsDecl>(D2))
  10319. return true;
  10320. return false;
  10321. }
  10322. /// Determines whether to create a using shadow decl for a particular
  10323. /// decl, given the set of decls existing prior to this using lookup.
  10324. bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
  10325. const LookupResult &Previous,
  10326. UsingShadowDecl *&PrevShadow) {
  10327. // Diagnose finding a decl which is not from a base class of the
  10328. // current class. We do this now because there are cases where this
  10329. // function will silently decide not to build a shadow decl, which
  10330. // will pre-empt further diagnostics.
  10331. //
  10332. // We don't need to do this in C++11 because we do the check once on
  10333. // the qualifier.
  10334. //
  10335. // FIXME: diagnose the following if we care enough:
  10336. // struct A { int foo; };
  10337. // struct B : A { using A::foo; };
  10338. // template <class T> struct C : A {};
  10339. // template <class T> struct D : C<T> { using B::foo; } // <---
  10340. // This is invalid (during instantiation) in C++03 because B::foo
  10341. // resolves to the using decl in B, which is not a base class of D<T>.
  10342. // We can't diagnose it immediately because C<T> is an unknown
  10343. // specialization. The UsingShadowDecl in D<T> then points directly
  10344. // to A::foo, which will look well-formed when we instantiate.
  10345. // The right solution is to not collapse the shadow-decl chain.
  10346. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
  10347. if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
  10348. DeclContext *OrigDC = Orig->getDeclContext();
  10349. // Handle enums and anonymous structs.
  10350. if (isa<EnumDecl>(OrigDC))
  10351. OrigDC = OrigDC->getParent();
  10352. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  10353. while (OrigRec->isAnonymousStructOrUnion())
  10354. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  10355. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  10356. if (OrigDC == CurContext) {
  10357. Diag(Using->getLocation(),
  10358. diag::err_using_decl_nested_name_specifier_is_current_class)
  10359. << Using->getQualifierLoc().getSourceRange();
  10360. Diag(Orig->getLocation(), diag::note_using_decl_target);
  10361. Using->setInvalidDecl();
  10362. return true;
  10363. }
  10364. Diag(Using->getQualifierLoc().getBeginLoc(),
  10365. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  10366. << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
  10367. << Using->getQualifierLoc().getSourceRange();
  10368. Diag(Orig->getLocation(), diag::note_using_decl_target);
  10369. Using->setInvalidDecl();
  10370. return true;
  10371. }
  10372. }
  10373. if (Previous.empty()) return false;
  10374. NamedDecl *Target = Orig;
  10375. if (isa<UsingShadowDecl>(Target))
  10376. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  10377. // If the target happens to be one of the previous declarations, we
  10378. // don't have a conflict.
  10379. //
  10380. // FIXME: but we might be increasing its access, in which case we
  10381. // should redeclare it.
  10382. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  10383. bool FoundEquivalentDecl = false;
  10384. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  10385. I != E; ++I) {
  10386. NamedDecl *D = (*I)->getUnderlyingDecl();
  10387. // We can have UsingDecls in our Previous results because we use the same
  10388. // LookupResult for checking whether the UsingDecl itself is a valid
  10389. // redeclaration.
  10390. if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
  10391. continue;
  10392. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  10393. // C++ [class.mem]p19:
  10394. // If T is the name of a class, then [every named member other than
  10395. // a non-static data member] shall have a name different from T
  10396. if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
  10397. !isa<IndirectFieldDecl>(Target) &&
  10398. !isa<UnresolvedUsingValueDecl>(Target) &&
  10399. DiagnoseClassNameShadow(
  10400. CurContext,
  10401. DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
  10402. return true;
  10403. }
  10404. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  10405. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  10406. PrevShadow = Shadow;
  10407. FoundEquivalentDecl = true;
  10408. } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
  10409. // We don't conflict with an existing using shadow decl of an equivalent
  10410. // declaration, but we're not a redeclaration of it.
  10411. FoundEquivalentDecl = true;
  10412. }
  10413. if (isVisible(D))
  10414. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  10415. }
  10416. if (FoundEquivalentDecl)
  10417. return false;
  10418. // Always emit a diagnostic for a mismatch between an unresolved
  10419. // using_if_exists and a resolved using declaration in either direction.
  10420. if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
  10421. (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
  10422. if (!NonTag && !Tag)
  10423. return false;
  10424. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10425. Diag(Target->getLocation(), diag::note_using_decl_target);
  10426. Diag((NonTag ? NonTag : Tag)->getLocation(),
  10427. diag::note_using_decl_conflict);
  10428. BUD->setInvalidDecl();
  10429. return true;
  10430. }
  10431. if (FunctionDecl *FD = Target->getAsFunction()) {
  10432. NamedDecl *OldDecl = nullptr;
  10433. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  10434. /*IsForUsingDecl*/ true)) {
  10435. case Ovl_Overload:
  10436. return false;
  10437. case Ovl_NonFunction:
  10438. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10439. break;
  10440. // We found a decl with the exact signature.
  10441. case Ovl_Match:
  10442. // If we're in a record, we want to hide the target, so we
  10443. // return true (without a diagnostic) to tell the caller not to
  10444. // build a shadow decl.
  10445. if (CurContext->isRecord())
  10446. return true;
  10447. // If we're not in a record, this is an error.
  10448. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10449. break;
  10450. }
  10451. Diag(Target->getLocation(), diag::note_using_decl_target);
  10452. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  10453. BUD->setInvalidDecl();
  10454. return true;
  10455. }
  10456. // Target is not a function.
  10457. if (isa<TagDecl>(Target)) {
  10458. // No conflict between a tag and a non-tag.
  10459. if (!Tag) return false;
  10460. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10461. Diag(Target->getLocation(), diag::note_using_decl_target);
  10462. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  10463. BUD->setInvalidDecl();
  10464. return true;
  10465. }
  10466. // No conflict between a tag and a non-tag.
  10467. if (!NonTag) return false;
  10468. Diag(BUD->getLocation(), diag::err_using_decl_conflict);
  10469. Diag(Target->getLocation(), diag::note_using_decl_target);
  10470. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  10471. BUD->setInvalidDecl();
  10472. return true;
  10473. }
  10474. /// Determine whether a direct base class is a virtual base class.
  10475. static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
  10476. if (!Derived->getNumVBases())
  10477. return false;
  10478. for (auto &B : Derived->bases())
  10479. if (B.getType()->getAsCXXRecordDecl() == Base)
  10480. return B.isVirtual();
  10481. llvm_unreachable("not a direct base class");
  10482. }
  10483. /// Builds a shadow declaration corresponding to a 'using' declaration.
  10484. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
  10485. NamedDecl *Orig,
  10486. UsingShadowDecl *PrevDecl) {
  10487. // If we resolved to another shadow declaration, just coalesce them.
  10488. NamedDecl *Target = Orig;
  10489. if (isa<UsingShadowDecl>(Target)) {
  10490. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  10491. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  10492. }
  10493. NamedDecl *NonTemplateTarget = Target;
  10494. if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
  10495. NonTemplateTarget = TargetTD->getTemplatedDecl();
  10496. UsingShadowDecl *Shadow;
  10497. if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
  10498. UsingDecl *Using = cast<UsingDecl>(BUD);
  10499. bool IsVirtualBase =
  10500. isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
  10501. Using->getQualifier()->getAsRecordDecl());
  10502. Shadow = ConstructorUsingShadowDecl::Create(
  10503. Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
  10504. } else {
  10505. Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
  10506. Target->getDeclName(), BUD, Target);
  10507. }
  10508. BUD->addShadowDecl(Shadow);
  10509. Shadow->setAccess(BUD->getAccess());
  10510. if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
  10511. Shadow->setInvalidDecl();
  10512. Shadow->setPreviousDecl(PrevDecl);
  10513. if (S)
  10514. PushOnScopeChains(Shadow, S);
  10515. else
  10516. CurContext->addDecl(Shadow);
  10517. return Shadow;
  10518. }
  10519. /// Hides a using shadow declaration. This is required by the current
  10520. /// using-decl implementation when a resolvable using declaration in a
  10521. /// class is followed by a declaration which would hide or override
  10522. /// one or more of the using decl's targets; for example:
  10523. ///
  10524. /// struct Base { void foo(int); };
  10525. /// struct Derived : Base {
  10526. /// using Base::foo;
  10527. /// void foo(int);
  10528. /// };
  10529. ///
  10530. /// The governing language is C++03 [namespace.udecl]p12:
  10531. ///
  10532. /// When a using-declaration brings names from a base class into a
  10533. /// derived class scope, member functions in the derived class
  10534. /// override and/or hide member functions with the same name and
  10535. /// parameter types in a base class (rather than conflicting).
  10536. ///
  10537. /// There are two ways to implement this:
  10538. /// (1) optimistically create shadow decls when they're not hidden
  10539. /// by existing declarations, or
  10540. /// (2) don't create any shadow decls (or at least don't make them
  10541. /// visible) until we've fully parsed/instantiated the class.
  10542. /// The problem with (1) is that we might have to retroactively remove
  10543. /// a shadow decl, which requires several O(n) operations because the
  10544. /// decl structures are (very reasonably) not designed for removal.
  10545. /// (2) avoids this but is very fiddly and phase-dependent.
  10546. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  10547. if (Shadow->getDeclName().getNameKind() ==
  10548. DeclarationName::CXXConversionFunctionName)
  10549. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  10550. // Remove it from the DeclContext...
  10551. Shadow->getDeclContext()->removeDecl(Shadow);
  10552. // ...and the scope, if applicable...
  10553. if (S) {
  10554. S->RemoveDecl(Shadow);
  10555. IdResolver.RemoveDecl(Shadow);
  10556. }
  10557. // ...and the using decl.
  10558. Shadow->getIntroducer()->removeShadowDecl(Shadow);
  10559. // TODO: complain somehow if Shadow was used. It shouldn't
  10560. // be possible for this to happen, because...?
  10561. }
  10562. /// Find the base specifier for a base class with the given type.
  10563. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  10564. QualType DesiredBase,
  10565. bool &AnyDependentBases) {
  10566. // Check whether the named type is a direct base class.
  10567. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
  10568. .getUnqualifiedType();
  10569. for (auto &Base : Derived->bases()) {
  10570. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  10571. if (CanonicalDesiredBase == BaseType)
  10572. return &Base;
  10573. if (BaseType->isDependentType())
  10574. AnyDependentBases = true;
  10575. }
  10576. return nullptr;
  10577. }
  10578. namespace {
  10579. class UsingValidatorCCC final : public CorrectionCandidateCallback {
  10580. public:
  10581. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  10582. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  10583. : HasTypenameKeyword(HasTypenameKeyword),
  10584. IsInstantiation(IsInstantiation), OldNNS(NNS),
  10585. RequireMemberOf(RequireMemberOf) {}
  10586. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  10587. NamedDecl *ND = Candidate.getCorrectionDecl();
  10588. // Keywords are not valid here.
  10589. if (!ND || isa<NamespaceDecl>(ND))
  10590. return false;
  10591. // Completely unqualified names are invalid for a 'using' declaration.
  10592. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  10593. return false;
  10594. // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
  10595. // reject.
  10596. if (RequireMemberOf) {
  10597. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  10598. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  10599. // No-one ever wants a using-declaration to name an injected-class-name
  10600. // of a base class, unless they're declaring an inheriting constructor.
  10601. ASTContext &Ctx = ND->getASTContext();
  10602. if (!Ctx.getLangOpts().CPlusPlus11)
  10603. return false;
  10604. QualType FoundType = Ctx.getRecordType(FoundRecord);
  10605. // Check that the injected-class-name is named as a member of its own
  10606. // type; we don't want to suggest 'using Derived::Base;', since that
  10607. // means something else.
  10608. NestedNameSpecifier *Specifier =
  10609. Candidate.WillReplaceSpecifier()
  10610. ? Candidate.getCorrectionSpecifier()
  10611. : OldNNS;
  10612. if (!Specifier->getAsType() ||
  10613. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  10614. return false;
  10615. // Check that this inheriting constructor declaration actually names a
  10616. // direct base class of the current class.
  10617. bool AnyDependentBases = false;
  10618. if (!findDirectBaseWithType(RequireMemberOf,
  10619. Ctx.getRecordType(FoundRecord),
  10620. AnyDependentBases) &&
  10621. !AnyDependentBases)
  10622. return false;
  10623. } else {
  10624. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  10625. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  10626. return false;
  10627. // FIXME: Check that the base class member is accessible?
  10628. }
  10629. } else {
  10630. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  10631. if (FoundRecord && FoundRecord->isInjectedClassName())
  10632. return false;
  10633. }
  10634. if (isa<TypeDecl>(ND))
  10635. return HasTypenameKeyword || !IsInstantiation;
  10636. return !HasTypenameKeyword;
  10637. }
  10638. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  10639. return std::make_unique<UsingValidatorCCC>(*this);
  10640. }
  10641. private:
  10642. bool HasTypenameKeyword;
  10643. bool IsInstantiation;
  10644. NestedNameSpecifier *OldNNS;
  10645. CXXRecordDecl *RequireMemberOf;
  10646. };
  10647. } // end anonymous namespace
  10648. /// Remove decls we can't actually see from a lookup being used to declare
  10649. /// shadow using decls.
  10650. ///
  10651. /// \param S - The scope of the potential shadow decl
  10652. /// \param Previous - The lookup of a potential shadow decl's name.
  10653. void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
  10654. // It is really dumb that we have to do this.
  10655. LookupResult::Filter F = Previous.makeFilter();
  10656. while (F.hasNext()) {
  10657. NamedDecl *D = F.next();
  10658. if (!isDeclInScope(D, CurContext, S))
  10659. F.erase();
  10660. // If we found a local extern declaration that's not ordinarily visible,
  10661. // and this declaration is being added to a non-block scope, ignore it.
  10662. // We're only checking for scope conflicts here, not also for violations
  10663. // of the linkage rules.
  10664. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  10665. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  10666. F.erase();
  10667. }
  10668. F.done();
  10669. }
  10670. /// Builds a using declaration.
  10671. ///
  10672. /// \param IsInstantiation - Whether this call arises from an
  10673. /// instantiation of an unresolved using declaration. We treat
  10674. /// the lookup differently for these declarations.
  10675. NamedDecl *Sema::BuildUsingDeclaration(
  10676. Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
  10677. bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
  10678. DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
  10679. const ParsedAttributesView &AttrList, bool IsInstantiation,
  10680. bool IsUsingIfExists) {
  10681. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  10682. SourceLocation IdentLoc = NameInfo.getLoc();
  10683. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  10684. // FIXME: We ignore attributes for now.
  10685. // For an inheriting constructor declaration, the name of the using
  10686. // declaration is the name of a constructor in this class, not in the
  10687. // base class.
  10688. DeclarationNameInfo UsingName = NameInfo;
  10689. if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
  10690. if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
  10691. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  10692. Context.getCanonicalType(Context.getRecordType(RD))));
  10693. // Do the redeclaration lookup in the current scope.
  10694. LookupResult Previous(*this, UsingName, LookupUsingDeclName,
  10695. ForVisibleRedeclaration);
  10696. Previous.setHideTags(false);
  10697. if (S) {
  10698. LookupName(Previous, S);
  10699. FilterUsingLookup(S, Previous);
  10700. } else {
  10701. assert(IsInstantiation && "no scope in non-instantiation");
  10702. if (CurContext->isRecord())
  10703. LookupQualifiedName(Previous, CurContext);
  10704. else {
  10705. // No redeclaration check is needed here; in non-member contexts we
  10706. // diagnosed all possible conflicts with other using-declarations when
  10707. // building the template:
  10708. //
  10709. // For a dependent non-type using declaration, the only valid case is
  10710. // if we instantiate to a single enumerator. We check for conflicts
  10711. // between shadow declarations we introduce, and we check in the template
  10712. // definition for conflicts between a non-type using declaration and any
  10713. // other declaration, which together covers all cases.
  10714. //
  10715. // A dependent typename using declaration will never successfully
  10716. // instantiate, since it will always name a class member, so we reject
  10717. // that in the template definition.
  10718. }
  10719. }
  10720. // Check for invalid redeclarations.
  10721. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  10722. SS, IdentLoc, Previous))
  10723. return nullptr;
  10724. // 'using_if_exists' doesn't make sense on an inherited constructor.
  10725. if (IsUsingIfExists && UsingName.getName().getNameKind() ==
  10726. DeclarationName::CXXConstructorName) {
  10727. Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
  10728. return nullptr;
  10729. }
  10730. DeclContext *LookupContext = computeDeclContext(SS);
  10731. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  10732. if (!LookupContext || EllipsisLoc.isValid()) {
  10733. NamedDecl *D;
  10734. // Dependent scope, or an unexpanded pack
  10735. if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
  10736. SS, NameInfo, IdentLoc))
  10737. return nullptr;
  10738. if (HasTypenameKeyword) {
  10739. // FIXME: not all declaration name kinds are legal here
  10740. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  10741. UsingLoc, TypenameLoc,
  10742. QualifierLoc,
  10743. IdentLoc, NameInfo.getName(),
  10744. EllipsisLoc);
  10745. } else {
  10746. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  10747. QualifierLoc, NameInfo, EllipsisLoc);
  10748. }
  10749. D->setAccess(AS);
  10750. CurContext->addDecl(D);
  10751. ProcessDeclAttributeList(S, D, AttrList);
  10752. return D;
  10753. }
  10754. auto Build = [&](bool Invalid) {
  10755. UsingDecl *UD =
  10756. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  10757. UsingName, HasTypenameKeyword);
  10758. UD->setAccess(AS);
  10759. CurContext->addDecl(UD);
  10760. ProcessDeclAttributeList(S, UD, AttrList);
  10761. UD->setInvalidDecl(Invalid);
  10762. return UD;
  10763. };
  10764. auto BuildInvalid = [&]{ return Build(true); };
  10765. auto BuildValid = [&]{ return Build(false); };
  10766. if (RequireCompleteDeclContext(SS, LookupContext))
  10767. return BuildInvalid();
  10768. // Look up the target name.
  10769. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  10770. // Unlike most lookups, we don't always want to hide tag
  10771. // declarations: tag names are visible through the using declaration
  10772. // even if hidden by ordinary names, *except* in a dependent context
  10773. // where they may be used by two-phase lookup.
  10774. if (!IsInstantiation)
  10775. R.setHideTags(false);
  10776. // For the purposes of this lookup, we have a base object type
  10777. // equal to that of the current context.
  10778. if (CurContext->isRecord()) {
  10779. R.setBaseObjectType(
  10780. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  10781. }
  10782. LookupQualifiedName(R, LookupContext);
  10783. // Validate the context, now we have a lookup
  10784. if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
  10785. IdentLoc, &R))
  10786. return nullptr;
  10787. if (R.empty() && IsUsingIfExists)
  10788. R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
  10789. UsingName.getName()),
  10790. AS_public);
  10791. // Try to correct typos if possible. If constructor name lookup finds no
  10792. // results, that means the named class has no explicit constructors, and we
  10793. // suppressed declaring implicit ones (probably because it's dependent or
  10794. // invalid).
  10795. if (R.empty() &&
  10796. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  10797. // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
  10798. // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
  10799. // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
  10800. auto *II = NameInfo.getName().getAsIdentifierInfo();
  10801. if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
  10802. CurContext->isStdNamespace() &&
  10803. isa<TranslationUnitDecl>(LookupContext) &&
  10804. getSourceManager().isInSystemHeader(UsingLoc))
  10805. return nullptr;
  10806. UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  10807. dyn_cast<CXXRecordDecl>(CurContext));
  10808. if (TypoCorrection Corrected =
  10809. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  10810. CTK_ErrorRecovery)) {
  10811. // We reject candidates where DroppedSpecifier == true, hence the
  10812. // literal '0' below.
  10813. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  10814. << NameInfo.getName() << LookupContext << 0
  10815. << SS.getRange());
  10816. // If we picked a correction with no attached Decl we can't do anything
  10817. // useful with it, bail out.
  10818. NamedDecl *ND = Corrected.getCorrectionDecl();
  10819. if (!ND)
  10820. return BuildInvalid();
  10821. // If we corrected to an inheriting constructor, handle it as one.
  10822. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  10823. if (RD && RD->isInjectedClassName()) {
  10824. // The parent of the injected class name is the class itself.
  10825. RD = cast<CXXRecordDecl>(RD->getParent());
  10826. // Fix up the information we'll use to build the using declaration.
  10827. if (Corrected.WillReplaceSpecifier()) {
  10828. NestedNameSpecifierLocBuilder Builder;
  10829. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  10830. QualifierLoc.getSourceRange());
  10831. QualifierLoc = Builder.getWithLocInContext(Context);
  10832. }
  10833. // In this case, the name we introduce is the name of a derived class
  10834. // constructor.
  10835. auto *CurClass = cast<CXXRecordDecl>(CurContext);
  10836. UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
  10837. Context.getCanonicalType(Context.getRecordType(CurClass))));
  10838. UsingName.setNamedTypeInfo(nullptr);
  10839. for (auto *Ctor : LookupConstructors(RD))
  10840. R.addDecl(Ctor);
  10841. R.resolveKind();
  10842. } else {
  10843. // FIXME: Pick up all the declarations if we found an overloaded
  10844. // function.
  10845. UsingName.setName(ND->getDeclName());
  10846. R.addDecl(ND);
  10847. }
  10848. } else {
  10849. Diag(IdentLoc, diag::err_no_member)
  10850. << NameInfo.getName() << LookupContext << SS.getRange();
  10851. return BuildInvalid();
  10852. }
  10853. }
  10854. if (R.isAmbiguous())
  10855. return BuildInvalid();
  10856. if (HasTypenameKeyword) {
  10857. // If we asked for a typename and got a non-type decl, error out.
  10858. if (!R.getAsSingle<TypeDecl>() &&
  10859. !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
  10860. Diag(IdentLoc, diag::err_using_typename_non_type);
  10861. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  10862. Diag((*I)->getUnderlyingDecl()->getLocation(),
  10863. diag::note_using_decl_target);
  10864. return BuildInvalid();
  10865. }
  10866. } else {
  10867. // If we asked for a non-typename and we got a type, error out,
  10868. // but only if this is an instantiation of an unresolved using
  10869. // decl. Otherwise just silently find the type name.
  10870. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  10871. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  10872. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  10873. return BuildInvalid();
  10874. }
  10875. }
  10876. // C++14 [namespace.udecl]p6:
  10877. // A using-declaration shall not name a namespace.
  10878. if (R.getAsSingle<NamespaceDecl>()) {
  10879. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  10880. << SS.getRange();
  10881. return BuildInvalid();
  10882. }
  10883. UsingDecl *UD = BuildValid();
  10884. // Some additional rules apply to inheriting constructors.
  10885. if (UsingName.getName().getNameKind() ==
  10886. DeclarationName::CXXConstructorName) {
  10887. // Suppress access diagnostics; the access check is instead performed at the
  10888. // point of use for an inheriting constructor.
  10889. R.suppressDiagnostics();
  10890. if (CheckInheritingConstructorUsingDecl(UD))
  10891. return UD;
  10892. }
  10893. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  10894. UsingShadowDecl *PrevDecl = nullptr;
  10895. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  10896. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  10897. }
  10898. return UD;
  10899. }
  10900. NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
  10901. SourceLocation UsingLoc,
  10902. SourceLocation EnumLoc,
  10903. SourceLocation NameLoc,
  10904. EnumDecl *ED) {
  10905. bool Invalid = false;
  10906. if (CurContext->getRedeclContext()->isRecord()) {
  10907. /// In class scope, check if this is a duplicate, for better a diagnostic.
  10908. DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
  10909. LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
  10910. ForVisibleRedeclaration);
  10911. LookupName(Previous, S);
  10912. for (NamedDecl *D : Previous)
  10913. if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
  10914. if (UED->getEnumDecl() == ED) {
  10915. Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
  10916. << SourceRange(EnumLoc, NameLoc);
  10917. Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
  10918. Invalid = true;
  10919. break;
  10920. }
  10921. }
  10922. if (RequireCompleteEnumDecl(ED, NameLoc))
  10923. Invalid = true;
  10924. UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
  10925. EnumLoc, NameLoc, ED);
  10926. UD->setAccess(AS);
  10927. CurContext->addDecl(UD);
  10928. if (Invalid) {
  10929. UD->setInvalidDecl();
  10930. return UD;
  10931. }
  10932. // Create the shadow decls for each enumerator
  10933. for (EnumConstantDecl *EC : ED->enumerators()) {
  10934. UsingShadowDecl *PrevDecl = nullptr;
  10935. DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
  10936. LookupResult Previous(*this, DNI, LookupOrdinaryName,
  10937. ForVisibleRedeclaration);
  10938. LookupName(Previous, S);
  10939. FilterUsingLookup(S, Previous);
  10940. if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
  10941. BuildUsingShadowDecl(S, UD, EC, PrevDecl);
  10942. }
  10943. return UD;
  10944. }
  10945. NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
  10946. ArrayRef<NamedDecl *> Expansions) {
  10947. assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
  10948. isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
  10949. isa<UsingPackDecl>(InstantiatedFrom));
  10950. auto *UPD =
  10951. UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
  10952. UPD->setAccess(InstantiatedFrom->getAccess());
  10953. CurContext->addDecl(UPD);
  10954. return UPD;
  10955. }
  10956. /// Additional checks for a using declaration referring to a constructor name.
  10957. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  10958. assert(!UD->hasTypename() && "expecting a constructor name");
  10959. const Type *SourceType = UD->getQualifier()->getAsType();
  10960. assert(SourceType &&
  10961. "Using decl naming constructor doesn't have type in scope spec.");
  10962. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  10963. // Check whether the named type is a direct base class.
  10964. bool AnyDependentBases = false;
  10965. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  10966. AnyDependentBases);
  10967. if (!Base && !AnyDependentBases) {
  10968. Diag(UD->getUsingLoc(),
  10969. diag::err_using_decl_constructor_not_in_direct_base)
  10970. << UD->getNameInfo().getSourceRange()
  10971. << QualType(SourceType, 0) << TargetClass;
  10972. UD->setInvalidDecl();
  10973. return true;
  10974. }
  10975. if (Base)
  10976. Base->setInheritConstructors();
  10977. return false;
  10978. }
  10979. /// Checks that the given using declaration is not an invalid
  10980. /// redeclaration. Note that this is checking only for the using decl
  10981. /// itself, not for any ill-formedness among the UsingShadowDecls.
  10982. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  10983. bool HasTypenameKeyword,
  10984. const CXXScopeSpec &SS,
  10985. SourceLocation NameLoc,
  10986. const LookupResult &Prev) {
  10987. NestedNameSpecifier *Qual = SS.getScopeRep();
  10988. // C++03 [namespace.udecl]p8:
  10989. // C++0x [namespace.udecl]p10:
  10990. // A using-declaration is a declaration and can therefore be used
  10991. // repeatedly where (and only where) multiple declarations are
  10992. // allowed.
  10993. //
  10994. // That's in non-member contexts.
  10995. if (!CurContext->getRedeclContext()->isRecord()) {
  10996. // A dependent qualifier outside a class can only ever resolve to an
  10997. // enumeration type. Therefore it conflicts with any other non-type
  10998. // declaration in the same scope.
  10999. // FIXME: How should we check for dependent type-type conflicts at block
  11000. // scope?
  11001. if (Qual->isDependent() && !HasTypenameKeyword) {
  11002. for (auto *D : Prev) {
  11003. if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
  11004. bool OldCouldBeEnumerator =
  11005. isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
  11006. Diag(NameLoc,
  11007. OldCouldBeEnumerator ? diag::err_redefinition
  11008. : diag::err_redefinition_different_kind)
  11009. << Prev.getLookupName();
  11010. Diag(D->getLocation(), diag::note_previous_definition);
  11011. return true;
  11012. }
  11013. }
  11014. }
  11015. return false;
  11016. }
  11017. const NestedNameSpecifier *CNNS =
  11018. Context.getCanonicalNestedNameSpecifier(Qual);
  11019. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  11020. NamedDecl *D = *I;
  11021. bool DTypename;
  11022. NestedNameSpecifier *DQual;
  11023. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  11024. DTypename = UD->hasTypename();
  11025. DQual = UD->getQualifier();
  11026. } else if (UnresolvedUsingValueDecl *UD
  11027. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  11028. DTypename = false;
  11029. DQual = UD->getQualifier();
  11030. } else if (UnresolvedUsingTypenameDecl *UD
  11031. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  11032. DTypename = true;
  11033. DQual = UD->getQualifier();
  11034. } else continue;
  11035. // using decls differ if one says 'typename' and the other doesn't.
  11036. // FIXME: non-dependent using decls?
  11037. if (HasTypenameKeyword != DTypename) continue;
  11038. // using decls differ if they name different scopes (but note that
  11039. // template instantiation can cause this check to trigger when it
  11040. // didn't before instantiation).
  11041. if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
  11042. continue;
  11043. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  11044. Diag(D->getLocation(), diag::note_using_decl) << 1;
  11045. return true;
  11046. }
  11047. return false;
  11048. }
  11049. /// Checks that the given nested-name qualifier used in a using decl
  11050. /// in the current context is appropriately related to the current
  11051. /// scope. If an error is found, diagnoses it and returns true.
  11052. /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
  11053. /// result of that lookup. UD is likewise nullptr, except when we have an
  11054. /// already-populated UsingDecl whose shadow decls contain the same information
  11055. /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
  11056. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
  11057. const CXXScopeSpec &SS,
  11058. const DeclarationNameInfo &NameInfo,
  11059. SourceLocation NameLoc,
  11060. const LookupResult *R, const UsingDecl *UD) {
  11061. DeclContext *NamedContext = computeDeclContext(SS);
  11062. assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
  11063. "resolvable context must have exactly one set of decls");
  11064. // C++ 20 permits using an enumerator that does not have a class-hierarchy
  11065. // relationship.
  11066. bool Cxx20Enumerator = false;
  11067. if (NamedContext) {
  11068. EnumConstantDecl *EC = nullptr;
  11069. if (R)
  11070. EC = R->getAsSingle<EnumConstantDecl>();
  11071. else if (UD && UD->shadow_size() == 1)
  11072. EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
  11073. if (EC)
  11074. Cxx20Enumerator = getLangOpts().CPlusPlus20;
  11075. if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
  11076. // C++14 [namespace.udecl]p7:
  11077. // A using-declaration shall not name a scoped enumerator.
  11078. // C++20 p1099 permits enumerators.
  11079. if (EC && R && ED->isScoped())
  11080. Diag(SS.getBeginLoc(),
  11081. getLangOpts().CPlusPlus20
  11082. ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
  11083. : diag::ext_using_decl_scoped_enumerator)
  11084. << SS.getRange();
  11085. // We want to consider the scope of the enumerator
  11086. NamedContext = ED->getDeclContext();
  11087. }
  11088. }
  11089. if (!CurContext->isRecord()) {
  11090. // C++03 [namespace.udecl]p3:
  11091. // C++0x [namespace.udecl]p8:
  11092. // A using-declaration for a class member shall be a member-declaration.
  11093. // C++20 [namespace.udecl]p7
  11094. // ... other than an enumerator ...
  11095. // If we weren't able to compute a valid scope, it might validly be a
  11096. // dependent class or enumeration scope. If we have a 'typename' keyword,
  11097. // the scope must resolve to a class type.
  11098. if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
  11099. : !HasTypename)
  11100. return false; // OK
  11101. Diag(NameLoc,
  11102. Cxx20Enumerator
  11103. ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
  11104. : diag::err_using_decl_can_not_refer_to_class_member)
  11105. << SS.getRange();
  11106. if (Cxx20Enumerator)
  11107. return false; // OK
  11108. auto *RD = NamedContext
  11109. ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
  11110. : nullptr;
  11111. if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
  11112. // See if there's a helpful fixit
  11113. if (!R) {
  11114. // We will have already diagnosed the problem on the template
  11115. // definition, Maybe we should do so again?
  11116. } else if (R->getAsSingle<TypeDecl>()) {
  11117. if (getLangOpts().CPlusPlus11) {
  11118. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  11119. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  11120. << 0 // alias declaration
  11121. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  11122. NameInfo.getName().getAsString() +
  11123. " = ");
  11124. } else {
  11125. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  11126. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
  11127. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  11128. << 1 // typedef declaration
  11129. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  11130. << FixItHint::CreateInsertion(
  11131. InsertLoc, " " + NameInfo.getName().getAsString());
  11132. }
  11133. } else if (R->getAsSingle<VarDecl>()) {
  11134. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  11135. // repeating the type of the static data member here.
  11136. FixItHint FixIt;
  11137. if (getLangOpts().CPlusPlus11) {
  11138. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  11139. FixIt = FixItHint::CreateReplacement(
  11140. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  11141. }
  11142. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  11143. << 2 // reference declaration
  11144. << FixIt;
  11145. } else if (R->getAsSingle<EnumConstantDecl>()) {
  11146. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  11147. // repeating the type of the enumeration here, and we can't do so if
  11148. // the type is anonymous.
  11149. FixItHint FixIt;
  11150. if (getLangOpts().CPlusPlus11) {
  11151. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  11152. FixIt = FixItHint::CreateReplacement(
  11153. UsingLoc,
  11154. "constexpr auto " + NameInfo.getName().getAsString() + " = ");
  11155. }
  11156. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  11157. << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
  11158. << FixIt;
  11159. }
  11160. }
  11161. return true; // Fail
  11162. }
  11163. // If the named context is dependent, we can't decide much.
  11164. if (!NamedContext) {
  11165. // FIXME: in C++0x, we can diagnose if we can prove that the
  11166. // nested-name-specifier does not refer to a base class, which is
  11167. // still possible in some cases.
  11168. // Otherwise we have to conservatively report that things might be
  11169. // okay.
  11170. return false;
  11171. }
  11172. // The current scope is a record.
  11173. if (!NamedContext->isRecord()) {
  11174. // Ideally this would point at the last name in the specifier,
  11175. // but we don't have that level of source info.
  11176. Diag(SS.getBeginLoc(),
  11177. Cxx20Enumerator
  11178. ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
  11179. : diag::err_using_decl_nested_name_specifier_is_not_class)
  11180. << SS.getScopeRep() << SS.getRange();
  11181. if (Cxx20Enumerator)
  11182. return false; // OK
  11183. return true;
  11184. }
  11185. if (!NamedContext->isDependentContext() &&
  11186. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  11187. return true;
  11188. if (getLangOpts().CPlusPlus11) {
  11189. // C++11 [namespace.udecl]p3:
  11190. // In a using-declaration used as a member-declaration, the
  11191. // nested-name-specifier shall name a base class of the class
  11192. // being defined.
  11193. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  11194. cast<CXXRecordDecl>(NamedContext))) {
  11195. if (Cxx20Enumerator) {
  11196. Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
  11197. << SS.getRange();
  11198. return false;
  11199. }
  11200. if (CurContext == NamedContext) {
  11201. Diag(SS.getBeginLoc(),
  11202. diag::err_using_decl_nested_name_specifier_is_current_class)
  11203. << SS.getRange();
  11204. return !getLangOpts().CPlusPlus20;
  11205. }
  11206. if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
  11207. Diag(SS.getBeginLoc(),
  11208. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  11209. << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
  11210. << SS.getRange();
  11211. }
  11212. return true;
  11213. }
  11214. return false;
  11215. }
  11216. // C++03 [namespace.udecl]p4:
  11217. // A using-declaration used as a member-declaration shall refer
  11218. // to a member of a base class of the class being defined [etc.].
  11219. // Salient point: SS doesn't have to name a base class as long as
  11220. // lookup only finds members from base classes. Therefore we can
  11221. // diagnose here only if we can prove that that can't happen,
  11222. // i.e. if the class hierarchies provably don't intersect.
  11223. // TODO: it would be nice if "definitely valid" results were cached
  11224. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  11225. // need to be repeated.
  11226. llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
  11227. auto Collect = [&Bases](const CXXRecordDecl *Base) {
  11228. Bases.insert(Base);
  11229. return true;
  11230. };
  11231. // Collect all bases. Return false if we find a dependent base.
  11232. if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
  11233. return false;
  11234. // Returns true if the base is dependent or is one of the accumulated base
  11235. // classes.
  11236. auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
  11237. return !Bases.count(Base);
  11238. };
  11239. // Return false if the class has a dependent base or if it or one
  11240. // of its bases is present in the base set of the current context.
  11241. if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
  11242. !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
  11243. return false;
  11244. Diag(SS.getRange().getBegin(),
  11245. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  11246. << SS.getScopeRep()
  11247. << cast<CXXRecordDecl>(CurContext)
  11248. << SS.getRange();
  11249. return true;
  11250. }
  11251. Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
  11252. MultiTemplateParamsArg TemplateParamLists,
  11253. SourceLocation UsingLoc, UnqualifiedId &Name,
  11254. const ParsedAttributesView &AttrList,
  11255. TypeResult Type, Decl *DeclFromDeclSpec) {
  11256. // Skip up to the relevant declaration scope.
  11257. while (S->isTemplateParamScope())
  11258. S = S->getParent();
  11259. assert((S->getFlags() & Scope::DeclScope) &&
  11260. "got alias-declaration outside of declaration scope");
  11261. if (Type.isInvalid())
  11262. return nullptr;
  11263. bool Invalid = false;
  11264. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  11265. TypeSourceInfo *TInfo = nullptr;
  11266. GetTypeFromParser(Type.get(), &TInfo);
  11267. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  11268. return nullptr;
  11269. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  11270. UPPC_DeclarationType)) {
  11271. Invalid = true;
  11272. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  11273. TInfo->getTypeLoc().getBeginLoc());
  11274. }
  11275. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  11276. TemplateParamLists.size()
  11277. ? forRedeclarationInCurContext()
  11278. : ForVisibleRedeclaration);
  11279. LookupName(Previous, S);
  11280. // Warn about shadowing the name of a template parameter.
  11281. if (Previous.isSingleResult() &&
  11282. Previous.getFoundDecl()->isTemplateParameter()) {
  11283. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  11284. Previous.clear();
  11285. }
  11286. assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
  11287. "name in alias declaration must be an identifier");
  11288. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  11289. Name.StartLocation,
  11290. Name.Identifier, TInfo);
  11291. NewTD->setAccess(AS);
  11292. if (Invalid)
  11293. NewTD->setInvalidDecl();
  11294. ProcessDeclAttributeList(S, NewTD, AttrList);
  11295. AddPragmaAttributes(S, NewTD);
  11296. CheckTypedefForVariablyModifiedType(S, NewTD);
  11297. Invalid |= NewTD->isInvalidDecl();
  11298. bool Redeclaration = false;
  11299. NamedDecl *NewND;
  11300. if (TemplateParamLists.size()) {
  11301. TypeAliasTemplateDecl *OldDecl = nullptr;
  11302. TemplateParameterList *OldTemplateParams = nullptr;
  11303. if (TemplateParamLists.size() != 1) {
  11304. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  11305. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  11306. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  11307. }
  11308. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  11309. // Check that we can declare a template here.
  11310. if (CheckTemplateDeclScope(S, TemplateParams))
  11311. return nullptr;
  11312. // Only consider previous declarations in the same scope.
  11313. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  11314. /*ExplicitInstantiationOrSpecialization*/false);
  11315. if (!Previous.empty()) {
  11316. Redeclaration = true;
  11317. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  11318. if (!OldDecl && !Invalid) {
  11319. Diag(UsingLoc, diag::err_redefinition_different_kind)
  11320. << Name.Identifier;
  11321. NamedDecl *OldD = Previous.getRepresentativeDecl();
  11322. if (OldD->getLocation().isValid())
  11323. Diag(OldD->getLocation(), diag::note_previous_definition);
  11324. Invalid = true;
  11325. }
  11326. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  11327. if (TemplateParameterListsAreEqual(TemplateParams,
  11328. OldDecl->getTemplateParameters(),
  11329. /*Complain=*/true,
  11330. TPL_TemplateMatch))
  11331. OldTemplateParams =
  11332. OldDecl->getMostRecentDecl()->getTemplateParameters();
  11333. else
  11334. Invalid = true;
  11335. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  11336. if (!Invalid &&
  11337. !Context.hasSameType(OldTD->getUnderlyingType(),
  11338. NewTD->getUnderlyingType())) {
  11339. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  11340. // but we can't reasonably accept it.
  11341. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  11342. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  11343. if (OldTD->getLocation().isValid())
  11344. Diag(OldTD->getLocation(), diag::note_previous_definition);
  11345. Invalid = true;
  11346. }
  11347. }
  11348. }
  11349. // Merge any previous default template arguments into our parameters,
  11350. // and check the parameter list.
  11351. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  11352. TPC_TypeAliasTemplate))
  11353. return nullptr;
  11354. TypeAliasTemplateDecl *NewDecl =
  11355. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  11356. Name.Identifier, TemplateParams,
  11357. NewTD);
  11358. NewTD->setDescribedAliasTemplate(NewDecl);
  11359. NewDecl->setAccess(AS);
  11360. if (Invalid)
  11361. NewDecl->setInvalidDecl();
  11362. else if (OldDecl) {
  11363. NewDecl->setPreviousDecl(OldDecl);
  11364. CheckRedeclarationInModule(NewDecl, OldDecl);
  11365. }
  11366. NewND = NewDecl;
  11367. } else {
  11368. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  11369. setTagNameForLinkagePurposes(TD, NewTD);
  11370. handleTagNumbering(TD, S);
  11371. }
  11372. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  11373. NewND = NewTD;
  11374. }
  11375. PushOnScopeChains(NewND, S);
  11376. ActOnDocumentableDecl(NewND);
  11377. return NewND;
  11378. }
  11379. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  11380. SourceLocation AliasLoc,
  11381. IdentifierInfo *Alias, CXXScopeSpec &SS,
  11382. SourceLocation IdentLoc,
  11383. IdentifierInfo *Ident) {
  11384. // Lookup the namespace name.
  11385. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  11386. LookupParsedName(R, S, &SS);
  11387. if (R.isAmbiguous())
  11388. return nullptr;
  11389. if (R.empty()) {
  11390. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  11391. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  11392. return nullptr;
  11393. }
  11394. }
  11395. assert(!R.isAmbiguous() && !R.empty());
  11396. NamedDecl *ND = R.getRepresentativeDecl();
  11397. // Check if we have a previous declaration with the same name.
  11398. LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
  11399. ForVisibleRedeclaration);
  11400. LookupName(PrevR, S);
  11401. // Check we're not shadowing a template parameter.
  11402. if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
  11403. DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
  11404. PrevR.clear();
  11405. }
  11406. // Filter out any other lookup result from an enclosing scope.
  11407. FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
  11408. /*AllowInlineNamespace*/false);
  11409. // Find the previous declaration and check that we can redeclare it.
  11410. NamespaceAliasDecl *Prev = nullptr;
  11411. if (PrevR.isSingleResult()) {
  11412. NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
  11413. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  11414. // We already have an alias with the same name that points to the same
  11415. // namespace; check that it matches.
  11416. if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  11417. Prev = AD;
  11418. } else if (isVisible(PrevDecl)) {
  11419. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  11420. << Alias;
  11421. Diag(AD->getLocation(), diag::note_previous_namespace_alias)
  11422. << AD->getNamespace();
  11423. return nullptr;
  11424. }
  11425. } else if (isVisible(PrevDecl)) {
  11426. unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
  11427. ? diag::err_redefinition
  11428. : diag::err_redefinition_different_kind;
  11429. Diag(AliasLoc, DiagID) << Alias;
  11430. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11431. return nullptr;
  11432. }
  11433. }
  11434. // The use of a nested name specifier may trigger deprecation warnings.
  11435. DiagnoseUseOfDecl(ND, IdentLoc);
  11436. NamespaceAliasDecl *AliasDecl =
  11437. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  11438. Alias, SS.getWithLocInContext(Context),
  11439. IdentLoc, ND);
  11440. if (Prev)
  11441. AliasDecl->setPreviousDecl(Prev);
  11442. PushOnScopeChains(AliasDecl, S);
  11443. return AliasDecl;
  11444. }
  11445. namespace {
  11446. struct SpecialMemberExceptionSpecInfo
  11447. : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
  11448. SourceLocation Loc;
  11449. Sema::ImplicitExceptionSpecification ExceptSpec;
  11450. SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
  11451. Sema::CXXSpecialMember CSM,
  11452. Sema::InheritedConstructorInfo *ICI,
  11453. SourceLocation Loc)
  11454. : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
  11455. bool visitBase(CXXBaseSpecifier *Base);
  11456. bool visitField(FieldDecl *FD);
  11457. void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  11458. unsigned Quals);
  11459. void visitSubobjectCall(Subobject Subobj,
  11460. Sema::SpecialMemberOverloadResult SMOR);
  11461. };
  11462. }
  11463. bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
  11464. auto *RT = Base->getType()->getAs<RecordType>();
  11465. if (!RT)
  11466. return false;
  11467. auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
  11468. Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
  11469. if (auto *BaseCtor = SMOR.getMethod()) {
  11470. visitSubobjectCall(Base, BaseCtor);
  11471. return false;
  11472. }
  11473. visitClassSubobject(BaseClass, Base, 0);
  11474. return false;
  11475. }
  11476. bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
  11477. if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
  11478. Expr *E = FD->getInClassInitializer();
  11479. if (!E)
  11480. // FIXME: It's a little wasteful to build and throw away a
  11481. // CXXDefaultInitExpr here.
  11482. // FIXME: We should have a single context note pointing at Loc, and
  11483. // this location should be MD->getLocation() instead, since that's
  11484. // the location where we actually use the default init expression.
  11485. E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
  11486. if (E)
  11487. ExceptSpec.CalledExpr(E);
  11488. } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
  11489. ->getAs<RecordType>()) {
  11490. visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
  11491. FD->getType().getCVRQualifiers());
  11492. }
  11493. return false;
  11494. }
  11495. void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
  11496. Subobject Subobj,
  11497. unsigned Quals) {
  11498. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  11499. bool IsMutable = Field && Field->isMutable();
  11500. visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
  11501. }
  11502. void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
  11503. Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
  11504. // Note, if lookup fails, it doesn't matter what exception specification we
  11505. // choose because the special member will be deleted.
  11506. if (CXXMethodDecl *MD = SMOR.getMethod())
  11507. ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
  11508. }
  11509. bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
  11510. llvm::APSInt Result;
  11511. ExprResult Converted = CheckConvertedConstantExpression(
  11512. ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
  11513. ExplicitSpec.setExpr(Converted.get());
  11514. if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
  11515. ExplicitSpec.setKind(Result.getBoolValue()
  11516. ? ExplicitSpecKind::ResolvedTrue
  11517. : ExplicitSpecKind::ResolvedFalse);
  11518. return true;
  11519. }
  11520. ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
  11521. return false;
  11522. }
  11523. ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
  11524. ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
  11525. if (!ExplicitExpr->isTypeDependent())
  11526. tryResolveExplicitSpecifier(ES);
  11527. return ES;
  11528. }
  11529. static Sema::ImplicitExceptionSpecification
  11530. ComputeDefaultedSpecialMemberExceptionSpec(
  11531. Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
  11532. Sema::InheritedConstructorInfo *ICI) {
  11533. ComputingExceptionSpec CES(S, MD, Loc);
  11534. CXXRecordDecl *ClassDecl = MD->getParent();
  11535. // C++ [except.spec]p14:
  11536. // An implicitly declared special member function (Clause 12) shall have an
  11537. // exception-specification. [...]
  11538. SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
  11539. if (ClassDecl->isInvalidDecl())
  11540. return Info.ExceptSpec;
  11541. // FIXME: If this diagnostic fires, we're probably missing a check for
  11542. // attempting to resolve an exception specification before it's known
  11543. // at a higher level.
  11544. if (S.RequireCompleteType(MD->getLocation(),
  11545. S.Context.getRecordType(ClassDecl),
  11546. diag::err_exception_spec_incomplete_type))
  11547. return Info.ExceptSpec;
  11548. // C++1z [except.spec]p7:
  11549. // [Look for exceptions thrown by] a constructor selected [...] to
  11550. // initialize a potentially constructed subobject,
  11551. // C++1z [except.spec]p8:
  11552. // The exception specification for an implicitly-declared destructor, or a
  11553. // destructor without a noexcept-specifier, is potentially-throwing if and
  11554. // only if any of the destructors for any of its potentially constructed
  11555. // subojects is potentially throwing.
  11556. // FIXME: We respect the first rule but ignore the "potentially constructed"
  11557. // in the second rule to resolve a core issue (no number yet) that would have
  11558. // us reject:
  11559. // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
  11560. // struct B : A {};
  11561. // struct C : B { void f(); };
  11562. // ... due to giving B::~B() a non-throwing exception specification.
  11563. Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
  11564. : Info.VisitAllBases);
  11565. return Info.ExceptSpec;
  11566. }
  11567. namespace {
  11568. /// RAII object to register a special member as being currently declared.
  11569. struct DeclaringSpecialMember {
  11570. Sema &S;
  11571. Sema::SpecialMemberDecl D;
  11572. Sema::ContextRAII SavedContext;
  11573. bool WasAlreadyBeingDeclared;
  11574. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  11575. : S(S), D(RD, CSM), SavedContext(S, RD) {
  11576. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  11577. if (WasAlreadyBeingDeclared)
  11578. // This almost never happens, but if it does, ensure that our cache
  11579. // doesn't contain a stale result.
  11580. S.SpecialMemberCache.clear();
  11581. else {
  11582. // Register a note to be produced if we encounter an error while
  11583. // declaring the special member.
  11584. Sema::CodeSynthesisContext Ctx;
  11585. Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
  11586. // FIXME: We don't have a location to use here. Using the class's
  11587. // location maintains the fiction that we declare all special members
  11588. // with the class, but (1) it's not clear that lying about that helps our
  11589. // users understand what's going on, and (2) there may be outer contexts
  11590. // on the stack (some of which are relevant) and printing them exposes
  11591. // our lies.
  11592. Ctx.PointOfInstantiation = RD->getLocation();
  11593. Ctx.Entity = RD;
  11594. Ctx.SpecialMember = CSM;
  11595. S.pushCodeSynthesisContext(Ctx);
  11596. }
  11597. }
  11598. ~DeclaringSpecialMember() {
  11599. if (!WasAlreadyBeingDeclared) {
  11600. S.SpecialMembersBeingDeclared.erase(D);
  11601. S.popCodeSynthesisContext();
  11602. }
  11603. }
  11604. /// Are we already trying to declare this special member?
  11605. bool isAlreadyBeingDeclared() const {
  11606. return WasAlreadyBeingDeclared;
  11607. }
  11608. };
  11609. }
  11610. void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
  11611. // Look up any existing declarations, but don't trigger declaration of all
  11612. // implicit special members with this name.
  11613. DeclarationName Name = FD->getDeclName();
  11614. LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
  11615. ForExternalRedeclaration);
  11616. for (auto *D : FD->getParent()->lookup(Name))
  11617. if (auto *Acceptable = R.getAcceptableDecl(D))
  11618. R.addDecl(Acceptable);
  11619. R.resolveKind();
  11620. R.suppressDiagnostics();
  11621. CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
  11622. }
  11623. void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
  11624. QualType ResultTy,
  11625. ArrayRef<QualType> Args) {
  11626. // Build an exception specification pointing back at this constructor.
  11627. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
  11628. LangAS AS = getDefaultCXXMethodAddrSpace();
  11629. if (AS != LangAS::Default) {
  11630. EPI.TypeQuals.addAddressSpace(AS);
  11631. }
  11632. auto QT = Context.getFunctionType(ResultTy, Args, EPI);
  11633. SpecialMem->setType(QT);
  11634. // During template instantiation of implicit special member functions we need
  11635. // a reliable TypeSourceInfo for the function prototype in order to allow
  11636. // functions to be substituted.
  11637. if (inTemplateInstantiation() &&
  11638. cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
  11639. TypeSourceInfo *TSI =
  11640. Context.getTrivialTypeSourceInfo(SpecialMem->getType());
  11641. SpecialMem->setTypeSourceInfo(TSI);
  11642. }
  11643. }
  11644. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  11645. CXXRecordDecl *ClassDecl) {
  11646. // C++ [class.ctor]p5:
  11647. // A default constructor for a class X is a constructor of class X
  11648. // that can be called without an argument. If there is no
  11649. // user-declared constructor for class X, a default constructor is
  11650. // implicitly declared. An implicitly-declared default constructor
  11651. // is an inline public member of its class.
  11652. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  11653. "Should not build implicit default constructor!");
  11654. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  11655. if (DSM.isAlreadyBeingDeclared())
  11656. return nullptr;
  11657. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11658. CXXDefaultConstructor,
  11659. false);
  11660. // Create the actual constructor declaration.
  11661. CanQualType ClassType
  11662. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  11663. SourceLocation ClassLoc = ClassDecl->getLocation();
  11664. DeclarationName Name
  11665. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  11666. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11667. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  11668. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
  11669. /*TInfo=*/nullptr, ExplicitSpecifier(),
  11670. getCurFPFeatures().isFPConstrained(),
  11671. /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  11672. Constexpr ? ConstexprSpecKind::Constexpr
  11673. : ConstexprSpecKind::Unspecified);
  11674. DefaultCon->setAccess(AS_public);
  11675. DefaultCon->setDefaulted();
  11676. if (getLangOpts().CUDA) {
  11677. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  11678. DefaultCon,
  11679. /* ConstRHS */ false,
  11680. /* Diagnose */ false);
  11681. }
  11682. setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
  11683. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  11684. // constructors is easy to compute.
  11685. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  11686. // Note that we have declared this constructor.
  11687. ++getASTContext().NumImplicitDefaultConstructorsDeclared;
  11688. Scope *S = getScopeForContext(ClassDecl);
  11689. CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
  11690. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  11691. SetDeclDeleted(DefaultCon, ClassLoc);
  11692. if (S)
  11693. PushOnScopeChains(DefaultCon, S, false);
  11694. ClassDecl->addDecl(DefaultCon);
  11695. return DefaultCon;
  11696. }
  11697. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  11698. CXXConstructorDecl *Constructor) {
  11699. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  11700. !Constructor->doesThisDeclarationHaveABody() &&
  11701. !Constructor->isDeleted()) &&
  11702. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  11703. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  11704. return;
  11705. CXXRecordDecl *ClassDecl = Constructor->getParent();
  11706. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  11707. SynthesizedFunctionScope Scope(*this, Constructor);
  11708. // The exception specification is needed because we are defining the
  11709. // function.
  11710. ResolveExceptionSpec(CurrentLocation,
  11711. Constructor->getType()->castAs<FunctionProtoType>());
  11712. MarkVTableUsed(CurrentLocation, ClassDecl);
  11713. // Add a context note for diagnostics produced after this point.
  11714. Scope.addContextNote(CurrentLocation);
  11715. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
  11716. Constructor->setInvalidDecl();
  11717. return;
  11718. }
  11719. SourceLocation Loc = Constructor->getEndLoc().isValid()
  11720. ? Constructor->getEndLoc()
  11721. : Constructor->getLocation();
  11722. Constructor->setBody(new (Context) CompoundStmt(Loc));
  11723. Constructor->markUsed(Context);
  11724. if (ASTMutationListener *L = getASTMutationListener()) {
  11725. L->CompletedImplicitDefinition(Constructor);
  11726. }
  11727. DiagnoseUninitializedFields(*this, Constructor);
  11728. }
  11729. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  11730. // Perform any delayed checks on exception specifications.
  11731. CheckDelayedMemberExceptionSpecs();
  11732. }
  11733. /// Find or create the fake constructor we synthesize to model constructing an
  11734. /// object of a derived class via a constructor of a base class.
  11735. CXXConstructorDecl *
  11736. Sema::findInheritingConstructor(SourceLocation Loc,
  11737. CXXConstructorDecl *BaseCtor,
  11738. ConstructorUsingShadowDecl *Shadow) {
  11739. CXXRecordDecl *Derived = Shadow->getParent();
  11740. SourceLocation UsingLoc = Shadow->getLocation();
  11741. // FIXME: Add a new kind of DeclarationName for an inherited constructor.
  11742. // For now we use the name of the base class constructor as a member of the
  11743. // derived class to indicate a (fake) inherited constructor name.
  11744. DeclarationName Name = BaseCtor->getDeclName();
  11745. // Check to see if we already have a fake constructor for this inherited
  11746. // constructor call.
  11747. for (NamedDecl *Ctor : Derived->lookup(Name))
  11748. if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
  11749. ->getInheritedConstructor()
  11750. .getConstructor(),
  11751. BaseCtor))
  11752. return cast<CXXConstructorDecl>(Ctor);
  11753. DeclarationNameInfo NameInfo(Name, UsingLoc);
  11754. TypeSourceInfo *TInfo =
  11755. Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
  11756. FunctionProtoTypeLoc ProtoLoc =
  11757. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  11758. // Check the inherited constructor is valid and find the list of base classes
  11759. // from which it was inherited.
  11760. InheritedConstructorInfo ICI(*this, Loc, Shadow);
  11761. bool Constexpr =
  11762. BaseCtor->isConstexpr() &&
  11763. defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
  11764. false, BaseCtor, &ICI);
  11765. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  11766. Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
  11767. BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
  11768. /*isInline=*/true,
  11769. /*isImplicitlyDeclared=*/true,
  11770. Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
  11771. InheritedConstructor(Shadow, BaseCtor),
  11772. BaseCtor->getTrailingRequiresClause());
  11773. if (Shadow->isInvalidDecl())
  11774. DerivedCtor->setInvalidDecl();
  11775. // Build an unevaluated exception specification for this fake constructor.
  11776. const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
  11777. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  11778. EPI.ExceptionSpec.Type = EST_Unevaluated;
  11779. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  11780. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  11781. FPT->getParamTypes(), EPI));
  11782. // Build the parameter declarations.
  11783. SmallVector<ParmVarDecl *, 16> ParamDecls;
  11784. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  11785. TypeSourceInfo *TInfo =
  11786. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  11787. ParmVarDecl *PD = ParmVarDecl::Create(
  11788. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  11789. FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
  11790. PD->setScopeInfo(0, I);
  11791. PD->setImplicit();
  11792. // Ensure attributes are propagated onto parameters (this matters for
  11793. // format, pass_object_size, ...).
  11794. mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
  11795. ParamDecls.push_back(PD);
  11796. ProtoLoc.setParam(I, PD);
  11797. }
  11798. // Set up the new constructor.
  11799. assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
  11800. DerivedCtor->setAccess(BaseCtor->getAccess());
  11801. DerivedCtor->setParams(ParamDecls);
  11802. Derived->addDecl(DerivedCtor);
  11803. if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
  11804. SetDeclDeleted(DerivedCtor, UsingLoc);
  11805. return DerivedCtor;
  11806. }
  11807. void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
  11808. InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
  11809. Ctor->getInheritedConstructor().getShadowDecl());
  11810. ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
  11811. /*Diagnose*/true);
  11812. }
  11813. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  11814. CXXConstructorDecl *Constructor) {
  11815. CXXRecordDecl *ClassDecl = Constructor->getParent();
  11816. assert(Constructor->getInheritedConstructor() &&
  11817. !Constructor->doesThisDeclarationHaveABody() &&
  11818. !Constructor->isDeleted());
  11819. if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
  11820. return;
  11821. // Initializations are performed "as if by a defaulted default constructor",
  11822. // so enter the appropriate scope.
  11823. SynthesizedFunctionScope Scope(*this, Constructor);
  11824. // The exception specification is needed because we are defining the
  11825. // function.
  11826. ResolveExceptionSpec(CurrentLocation,
  11827. Constructor->getType()->castAs<FunctionProtoType>());
  11828. MarkVTableUsed(CurrentLocation, ClassDecl);
  11829. // Add a context note for diagnostics produced after this point.
  11830. Scope.addContextNote(CurrentLocation);
  11831. ConstructorUsingShadowDecl *Shadow =
  11832. Constructor->getInheritedConstructor().getShadowDecl();
  11833. CXXConstructorDecl *InheritedCtor =
  11834. Constructor->getInheritedConstructor().getConstructor();
  11835. // [class.inhctor.init]p1:
  11836. // initialization proceeds as if a defaulted default constructor is used to
  11837. // initialize the D object and each base class subobject from which the
  11838. // constructor was inherited
  11839. InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
  11840. CXXRecordDecl *RD = Shadow->getParent();
  11841. SourceLocation InitLoc = Shadow->getLocation();
  11842. // Build explicit initializers for all base classes from which the
  11843. // constructor was inherited.
  11844. SmallVector<CXXCtorInitializer*, 8> Inits;
  11845. for (bool VBase : {false, true}) {
  11846. for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
  11847. if (B.isVirtual() != VBase)
  11848. continue;
  11849. auto *BaseRD = B.getType()->getAsCXXRecordDecl();
  11850. if (!BaseRD)
  11851. continue;
  11852. auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
  11853. if (!BaseCtor.first)
  11854. continue;
  11855. MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
  11856. ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
  11857. InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
  11858. auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
  11859. Inits.push_back(new (Context) CXXCtorInitializer(
  11860. Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
  11861. SourceLocation()));
  11862. }
  11863. }
  11864. // We now proceed as if for a defaulted default constructor, with the relevant
  11865. // initializers replaced.
  11866. if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
  11867. Constructor->setInvalidDecl();
  11868. return;
  11869. }
  11870. Constructor->setBody(new (Context) CompoundStmt(InitLoc));
  11871. Constructor->markUsed(Context);
  11872. if (ASTMutationListener *L = getASTMutationListener()) {
  11873. L->CompletedImplicitDefinition(Constructor);
  11874. }
  11875. DiagnoseUninitializedFields(*this, Constructor);
  11876. }
  11877. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  11878. // C++ [class.dtor]p2:
  11879. // If a class has no user-declared destructor, a destructor is
  11880. // declared implicitly. An implicitly-declared destructor is an
  11881. // inline public member of its class.
  11882. assert(ClassDecl->needsImplicitDestructor());
  11883. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  11884. if (DSM.isAlreadyBeingDeclared())
  11885. return nullptr;
  11886. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  11887. CXXDestructor,
  11888. false);
  11889. // Create the actual destructor declaration.
  11890. CanQualType ClassType
  11891. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  11892. SourceLocation ClassLoc = ClassDecl->getLocation();
  11893. DeclarationName Name
  11894. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  11895. DeclarationNameInfo NameInfo(Name, ClassLoc);
  11896. CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
  11897. Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
  11898. getCurFPFeatures().isFPConstrained(),
  11899. /*isInline=*/true,
  11900. /*isImplicitlyDeclared=*/true,
  11901. Constexpr ? ConstexprSpecKind::Constexpr
  11902. : ConstexprSpecKind::Unspecified);
  11903. Destructor->setAccess(AS_public);
  11904. Destructor->setDefaulted();
  11905. if (getLangOpts().CUDA) {
  11906. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  11907. Destructor,
  11908. /* ConstRHS */ false,
  11909. /* Diagnose */ false);
  11910. }
  11911. setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
  11912. // We don't need to use SpecialMemberIsTrivial here; triviality for
  11913. // destructors is easy to compute.
  11914. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  11915. Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
  11916. ClassDecl->hasTrivialDestructorForCall());
  11917. // Note that we have declared this destructor.
  11918. ++getASTContext().NumImplicitDestructorsDeclared;
  11919. Scope *S = getScopeForContext(ClassDecl);
  11920. CheckImplicitSpecialMemberDeclaration(S, Destructor);
  11921. // We can't check whether an implicit destructor is deleted before we complete
  11922. // the definition of the class, because its validity depends on the alignment
  11923. // of the class. We'll check this from ActOnFields once the class is complete.
  11924. if (ClassDecl->isCompleteDefinition() &&
  11925. ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  11926. SetDeclDeleted(Destructor, ClassLoc);
  11927. // Introduce this destructor into its scope.
  11928. if (S)
  11929. PushOnScopeChains(Destructor, S, false);
  11930. ClassDecl->addDecl(Destructor);
  11931. return Destructor;
  11932. }
  11933. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  11934. CXXDestructorDecl *Destructor) {
  11935. assert((Destructor->isDefaulted() &&
  11936. !Destructor->doesThisDeclarationHaveABody() &&
  11937. !Destructor->isDeleted()) &&
  11938. "DefineImplicitDestructor - call it for implicit default dtor");
  11939. if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
  11940. return;
  11941. CXXRecordDecl *ClassDecl = Destructor->getParent();
  11942. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  11943. SynthesizedFunctionScope Scope(*this, Destructor);
  11944. // The exception specification is needed because we are defining the
  11945. // function.
  11946. ResolveExceptionSpec(CurrentLocation,
  11947. Destructor->getType()->castAs<FunctionProtoType>());
  11948. MarkVTableUsed(CurrentLocation, ClassDecl);
  11949. // Add a context note for diagnostics produced after this point.
  11950. Scope.addContextNote(CurrentLocation);
  11951. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11952. Destructor->getParent());
  11953. if (CheckDestructor(Destructor)) {
  11954. Destructor->setInvalidDecl();
  11955. return;
  11956. }
  11957. SourceLocation Loc = Destructor->getEndLoc().isValid()
  11958. ? Destructor->getEndLoc()
  11959. : Destructor->getLocation();
  11960. Destructor->setBody(new (Context) CompoundStmt(Loc));
  11961. Destructor->markUsed(Context);
  11962. if (ASTMutationListener *L = getASTMutationListener()) {
  11963. L->CompletedImplicitDefinition(Destructor);
  11964. }
  11965. }
  11966. void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
  11967. CXXDestructorDecl *Destructor) {
  11968. if (Destructor->isInvalidDecl())
  11969. return;
  11970. CXXRecordDecl *ClassDecl = Destructor->getParent();
  11971. assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  11972. "implicit complete dtors unneeded outside MS ABI");
  11973. assert(ClassDecl->getNumVBases() > 0 &&
  11974. "complete dtor only exists for classes with vbases");
  11975. SynthesizedFunctionScope Scope(*this, Destructor);
  11976. // Add a context note for diagnostics produced after this point.
  11977. Scope.addContextNote(CurrentLocation);
  11978. MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
  11979. }
  11980. /// Perform any semantic analysis which needs to be delayed until all
  11981. /// pending class member declarations have been parsed.
  11982. void Sema::ActOnFinishCXXMemberDecls() {
  11983. // If the context is an invalid C++ class, just suppress these checks.
  11984. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  11985. if (Record->isInvalidDecl()) {
  11986. DelayedOverridingExceptionSpecChecks.clear();
  11987. DelayedEquivalentExceptionSpecChecks.clear();
  11988. return;
  11989. }
  11990. checkForMultipleExportedDefaultConstructors(*this, Record);
  11991. }
  11992. }
  11993. void Sema::ActOnFinishCXXNonNestedClass() {
  11994. referenceDLLExportedClassMethods();
  11995. if (!DelayedDllExportMemberFunctions.empty()) {
  11996. SmallVector<CXXMethodDecl*, 4> WorkList;
  11997. std::swap(DelayedDllExportMemberFunctions, WorkList);
  11998. for (CXXMethodDecl *M : WorkList) {
  11999. DefineDefaultedFunction(*this, M, M->getLocation());
  12000. // Pass the method to the consumer to get emitted. This is not necessary
  12001. // for explicit instantiation definitions, as they will get emitted
  12002. // anyway.
  12003. if (M->getParent()->getTemplateSpecializationKind() !=
  12004. TSK_ExplicitInstantiationDefinition)
  12005. ActOnFinishInlineFunctionDef(M);
  12006. }
  12007. }
  12008. }
  12009. void Sema::referenceDLLExportedClassMethods() {
  12010. if (!DelayedDllExportClasses.empty()) {
  12011. // Calling ReferenceDllExportedMembers might cause the current function to
  12012. // be called again, so use a local copy of DelayedDllExportClasses.
  12013. SmallVector<CXXRecordDecl *, 4> WorkList;
  12014. std::swap(DelayedDllExportClasses, WorkList);
  12015. for (CXXRecordDecl *Class : WorkList)
  12016. ReferenceDllExportedMembers(*this, Class);
  12017. }
  12018. }
  12019. void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
  12020. assert(getLangOpts().CPlusPlus11 &&
  12021. "adjusting dtor exception specs was introduced in c++11");
  12022. if (Destructor->isDependentContext())
  12023. return;
  12024. // C++11 [class.dtor]p3:
  12025. // A declaration of a destructor that does not have an exception-
  12026. // specification is implicitly considered to have the same exception-
  12027. // specification as an implicit declaration.
  12028. const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
  12029. if (DtorType->hasExceptionSpec())
  12030. return;
  12031. // Replace the destructor's type, building off the existing one. Fortunately,
  12032. // the only thing of interest in the destructor type is its extended info.
  12033. // The return and arguments are fixed.
  12034. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  12035. EPI.ExceptionSpec.Type = EST_Unevaluated;
  12036. EPI.ExceptionSpec.SourceDecl = Destructor;
  12037. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
  12038. // FIXME: If the destructor has a body that could throw, and the newly created
  12039. // spec doesn't allow exceptions, we should emit a warning, because this
  12040. // change in behavior can break conforming C++03 programs at runtime.
  12041. // However, we don't have a body or an exception specification yet, so it
  12042. // needs to be done somewhere else.
  12043. }
  12044. namespace {
  12045. /// An abstract base class for all helper classes used in building the
  12046. // copy/move operators. These classes serve as factory functions and help us
  12047. // avoid using the same Expr* in the AST twice.
  12048. class ExprBuilder {
  12049. ExprBuilder(const ExprBuilder&) = delete;
  12050. ExprBuilder &operator=(const ExprBuilder&) = delete;
  12051. protected:
  12052. static Expr *assertNotNull(Expr *E) {
  12053. assert(E && "Expression construction must not fail.");
  12054. return E;
  12055. }
  12056. public:
  12057. ExprBuilder() {}
  12058. virtual ~ExprBuilder() {}
  12059. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  12060. };
  12061. class RefBuilder: public ExprBuilder {
  12062. VarDecl *Var;
  12063. QualType VarType;
  12064. public:
  12065. Expr *build(Sema &S, SourceLocation Loc) const override {
  12066. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
  12067. }
  12068. RefBuilder(VarDecl *Var, QualType VarType)
  12069. : Var(Var), VarType(VarType) {}
  12070. };
  12071. class ThisBuilder: public ExprBuilder {
  12072. public:
  12073. Expr *build(Sema &S, SourceLocation Loc) const override {
  12074. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  12075. }
  12076. };
  12077. class CastBuilder: public ExprBuilder {
  12078. const ExprBuilder &Builder;
  12079. QualType Type;
  12080. ExprValueKind Kind;
  12081. const CXXCastPath &Path;
  12082. public:
  12083. Expr *build(Sema &S, SourceLocation Loc) const override {
  12084. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  12085. CK_UncheckedDerivedToBase, Kind,
  12086. &Path).get());
  12087. }
  12088. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  12089. const CXXCastPath &Path)
  12090. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  12091. };
  12092. class DerefBuilder: public ExprBuilder {
  12093. const ExprBuilder &Builder;
  12094. public:
  12095. Expr *build(Sema &S, SourceLocation Loc) const override {
  12096. return assertNotNull(
  12097. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  12098. }
  12099. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  12100. };
  12101. class MemberBuilder: public ExprBuilder {
  12102. const ExprBuilder &Builder;
  12103. QualType Type;
  12104. CXXScopeSpec SS;
  12105. bool IsArrow;
  12106. LookupResult &MemberLookup;
  12107. public:
  12108. Expr *build(Sema &S, SourceLocation Loc) const override {
  12109. return assertNotNull(S.BuildMemberReferenceExpr(
  12110. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  12111. nullptr, MemberLookup, nullptr, nullptr).get());
  12112. }
  12113. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  12114. LookupResult &MemberLookup)
  12115. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  12116. MemberLookup(MemberLookup) {}
  12117. };
  12118. class MoveCastBuilder: public ExprBuilder {
  12119. const ExprBuilder &Builder;
  12120. public:
  12121. Expr *build(Sema &S, SourceLocation Loc) const override {
  12122. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  12123. }
  12124. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  12125. };
  12126. class LvalueConvBuilder: public ExprBuilder {
  12127. const ExprBuilder &Builder;
  12128. public:
  12129. Expr *build(Sema &S, SourceLocation Loc) const override {
  12130. return assertNotNull(
  12131. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  12132. }
  12133. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  12134. };
  12135. class SubscriptBuilder: public ExprBuilder {
  12136. const ExprBuilder &Base;
  12137. const ExprBuilder &Index;
  12138. public:
  12139. Expr *build(Sema &S, SourceLocation Loc) const override {
  12140. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  12141. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  12142. }
  12143. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  12144. : Base(Base), Index(Index) {}
  12145. };
  12146. } // end anonymous namespace
  12147. /// When generating a defaulted copy or move assignment operator, if a field
  12148. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  12149. /// do so. This optimization only applies for arrays of scalars, and for arrays
  12150. /// of class type where the selected copy/move-assignment operator is trivial.
  12151. static StmtResult
  12152. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  12153. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  12154. // Compute the size of the memory buffer to be copied.
  12155. QualType SizeType = S.Context.getSizeType();
  12156. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  12157. S.Context.getTypeSizeInChars(T).getQuantity());
  12158. // Take the address of the field references for "from" and "to". We
  12159. // directly construct UnaryOperators here because semantic analysis
  12160. // does not permit us to take the address of an xvalue.
  12161. Expr *From = FromB.build(S, Loc);
  12162. From = UnaryOperator::Create(
  12163. S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
  12164. VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
  12165. Expr *To = ToB.build(S, Loc);
  12166. To = UnaryOperator::Create(
  12167. S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
  12168. VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
  12169. const Type *E = T->getBaseElementTypeUnsafe();
  12170. bool NeedsCollectableMemCpy =
  12171. E->isRecordType() &&
  12172. E->castAs<RecordType>()->getDecl()->hasObjectMember();
  12173. // Create a reference to the __builtin_objc_memmove_collectable function
  12174. StringRef MemCpyName = NeedsCollectableMemCpy ?
  12175. "__builtin_objc_memmove_collectable" :
  12176. "__builtin_memcpy";
  12177. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  12178. Sema::LookupOrdinaryName);
  12179. S.LookupName(R, S.TUScope, true);
  12180. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  12181. if (!MemCpy)
  12182. // Something went horribly wrong earlier, and we will have complained
  12183. // about it.
  12184. return StmtError();
  12185. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  12186. VK_PRValue, Loc, nullptr);
  12187. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  12188. Expr *CallArgs[] = {
  12189. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  12190. };
  12191. ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  12192. Loc, CallArgs, Loc);
  12193. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  12194. return Call.getAs<Stmt>();
  12195. }
  12196. /// Builds a statement that copies/moves the given entity from \p From to
  12197. /// \c To.
  12198. ///
  12199. /// This routine is used to copy/move the members of a class with an
  12200. /// implicitly-declared copy/move assignment operator. When the entities being
  12201. /// copied are arrays, this routine builds for loops to copy them.
  12202. ///
  12203. /// \param S The Sema object used for type-checking.
  12204. ///
  12205. /// \param Loc The location where the implicit copy/move is being generated.
  12206. ///
  12207. /// \param T The type of the expressions being copied/moved. Both expressions
  12208. /// must have this type.
  12209. ///
  12210. /// \param To The expression we are copying/moving to.
  12211. ///
  12212. /// \param From The expression we are copying/moving from.
  12213. ///
  12214. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  12215. /// Otherwise, it's a non-static member subobject.
  12216. ///
  12217. /// \param Copying Whether we're copying or moving.
  12218. ///
  12219. /// \param Depth Internal parameter recording the depth of the recursion.
  12220. ///
  12221. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  12222. /// if a memcpy should be used instead.
  12223. static StmtResult
  12224. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  12225. const ExprBuilder &To, const ExprBuilder &From,
  12226. bool CopyingBaseSubobject, bool Copying,
  12227. unsigned Depth = 0) {
  12228. // C++11 [class.copy]p28:
  12229. // Each subobject is assigned in the manner appropriate to its type:
  12230. //
  12231. // - if the subobject is of class type, as if by a call to operator= with
  12232. // the subobject as the object expression and the corresponding
  12233. // subobject of x as a single function argument (as if by explicit
  12234. // qualification; that is, ignoring any possible virtual overriding
  12235. // functions in more derived classes);
  12236. //
  12237. // C++03 [class.copy]p13:
  12238. // - if the subobject is of class type, the copy assignment operator for
  12239. // the class is used (as if by explicit qualification; that is,
  12240. // ignoring any possible virtual overriding functions in more derived
  12241. // classes);
  12242. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  12243. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  12244. // Look for operator=.
  12245. DeclarationName Name
  12246. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  12247. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  12248. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  12249. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  12250. // operator.
  12251. if (!S.getLangOpts().CPlusPlus11) {
  12252. LookupResult::Filter F = OpLookup.makeFilter();
  12253. while (F.hasNext()) {
  12254. NamedDecl *D = F.next();
  12255. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  12256. if (Method->isCopyAssignmentOperator() ||
  12257. (!Copying && Method->isMoveAssignmentOperator()))
  12258. continue;
  12259. F.erase();
  12260. }
  12261. F.done();
  12262. }
  12263. // Suppress the protected check (C++ [class.protected]) for each of the
  12264. // assignment operators we found. This strange dance is required when
  12265. // we're assigning via a base classes's copy-assignment operator. To
  12266. // ensure that we're getting the right base class subobject (without
  12267. // ambiguities), we need to cast "this" to that subobject type; to
  12268. // ensure that we don't go through the virtual call mechanism, we need
  12269. // to qualify the operator= name with the base class (see below). However,
  12270. // this means that if the base class has a protected copy assignment
  12271. // operator, the protected member access check will fail. So, we
  12272. // rewrite "protected" access to "public" access in this case, since we
  12273. // know by construction that we're calling from a derived class.
  12274. if (CopyingBaseSubobject) {
  12275. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  12276. L != LEnd; ++L) {
  12277. if (L.getAccess() == AS_protected)
  12278. L.setAccess(AS_public);
  12279. }
  12280. }
  12281. // Create the nested-name-specifier that will be used to qualify the
  12282. // reference to operator=; this is required to suppress the virtual
  12283. // call mechanism.
  12284. CXXScopeSpec SS;
  12285. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  12286. SS.MakeTrivial(S.Context,
  12287. NestedNameSpecifier::Create(S.Context, nullptr, false,
  12288. CanonicalT),
  12289. Loc);
  12290. // Create the reference to operator=.
  12291. ExprResult OpEqualRef
  12292. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
  12293. SS, /*TemplateKWLoc=*/SourceLocation(),
  12294. /*FirstQualifierInScope=*/nullptr,
  12295. OpLookup,
  12296. /*TemplateArgs=*/nullptr, /*S*/nullptr,
  12297. /*SuppressQualifierCheck=*/true);
  12298. if (OpEqualRef.isInvalid())
  12299. return StmtError();
  12300. // Build the call to the assignment operator.
  12301. Expr *FromInst = From.build(S, Loc);
  12302. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  12303. OpEqualRef.getAs<Expr>(),
  12304. Loc, FromInst, Loc);
  12305. if (Call.isInvalid())
  12306. return StmtError();
  12307. // If we built a call to a trivial 'operator=' while copying an array,
  12308. // bail out. We'll replace the whole shebang with a memcpy.
  12309. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  12310. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  12311. return StmtResult((Stmt*)nullptr);
  12312. // Convert to an expression-statement, and clean up any produced
  12313. // temporaries.
  12314. return S.ActOnExprStmt(Call);
  12315. }
  12316. // - if the subobject is of scalar type, the built-in assignment
  12317. // operator is used.
  12318. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  12319. if (!ArrayTy) {
  12320. ExprResult Assignment = S.CreateBuiltinBinOp(
  12321. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  12322. if (Assignment.isInvalid())
  12323. return StmtError();
  12324. return S.ActOnExprStmt(Assignment);
  12325. }
  12326. // - if the subobject is an array, each element is assigned, in the
  12327. // manner appropriate to the element type;
  12328. // Construct a loop over the array bounds, e.g.,
  12329. //
  12330. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  12331. //
  12332. // that will copy each of the array elements.
  12333. QualType SizeType = S.Context.getSizeType();
  12334. // Create the iteration variable.
  12335. IdentifierInfo *IterationVarName = nullptr;
  12336. {
  12337. SmallString<8> Str;
  12338. llvm::raw_svector_ostream OS(Str);
  12339. OS << "__i" << Depth;
  12340. IterationVarName = &S.Context.Idents.get(OS.str());
  12341. }
  12342. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  12343. IterationVarName, SizeType,
  12344. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  12345. SC_None);
  12346. // Initialize the iteration variable to zero.
  12347. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  12348. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  12349. // Creates a reference to the iteration variable.
  12350. RefBuilder IterationVarRef(IterationVar, SizeType);
  12351. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  12352. // Create the DeclStmt that holds the iteration variable.
  12353. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  12354. // Subscript the "from" and "to" expressions with the iteration variable.
  12355. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  12356. MoveCastBuilder FromIndexMove(FromIndexCopy);
  12357. const ExprBuilder *FromIndex;
  12358. if (Copying)
  12359. FromIndex = &FromIndexCopy;
  12360. else
  12361. FromIndex = &FromIndexMove;
  12362. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  12363. // Build the copy/move for an individual element of the array.
  12364. StmtResult Copy =
  12365. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  12366. ToIndex, *FromIndex, CopyingBaseSubobject,
  12367. Copying, Depth + 1);
  12368. // Bail out if copying fails or if we determined that we should use memcpy.
  12369. if (Copy.isInvalid() || !Copy.get())
  12370. return Copy;
  12371. // Create the comparison against the array bound.
  12372. llvm::APInt Upper
  12373. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  12374. Expr *Comparison = BinaryOperator::Create(
  12375. S.Context, IterationVarRefRVal.build(S, Loc),
  12376. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
  12377. S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
  12378. S.CurFPFeatureOverrides());
  12379. // Create the pre-increment of the iteration variable. We can determine
  12380. // whether the increment will overflow based on the value of the array
  12381. // bound.
  12382. Expr *Increment = UnaryOperator::Create(
  12383. S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
  12384. OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
  12385. // Construct the loop that copies all elements of this array.
  12386. return S.ActOnForStmt(
  12387. Loc, Loc, InitStmt,
  12388. S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
  12389. S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
  12390. }
  12391. static StmtResult
  12392. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  12393. const ExprBuilder &To, const ExprBuilder &From,
  12394. bool CopyingBaseSubobject, bool Copying) {
  12395. // Maybe we should use a memcpy?
  12396. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  12397. T.isTriviallyCopyableType(S.Context))
  12398. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  12399. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  12400. CopyingBaseSubobject,
  12401. Copying, 0));
  12402. // If we ended up picking a trivial assignment operator for an array of a
  12403. // non-trivially-copyable class type, just emit a memcpy.
  12404. if (!Result.isInvalid() && !Result.get())
  12405. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  12406. return Result;
  12407. }
  12408. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  12409. // Note: The following rules are largely analoguous to the copy
  12410. // constructor rules. Note that virtual bases are not taken into account
  12411. // for determining the argument type of the operator. Note also that
  12412. // operators taking an object instead of a reference are allowed.
  12413. assert(ClassDecl->needsImplicitCopyAssignment());
  12414. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  12415. if (DSM.isAlreadyBeingDeclared())
  12416. return nullptr;
  12417. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  12418. LangAS AS = getDefaultCXXMethodAddrSpace();
  12419. if (AS != LangAS::Default)
  12420. ArgType = Context.getAddrSpaceQualType(ArgType, AS);
  12421. QualType RetType = Context.getLValueReferenceType(ArgType);
  12422. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  12423. if (Const)
  12424. ArgType = ArgType.withConst();
  12425. ArgType = Context.getLValueReferenceType(ArgType);
  12426. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  12427. CXXCopyAssignment,
  12428. Const);
  12429. // An implicitly-declared copy assignment operator is an inline public
  12430. // member of its class.
  12431. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  12432. SourceLocation ClassLoc = ClassDecl->getLocation();
  12433. DeclarationNameInfo NameInfo(Name, ClassLoc);
  12434. CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
  12435. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  12436. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  12437. getCurFPFeatures().isFPConstrained(),
  12438. /*isInline=*/true,
  12439. Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
  12440. SourceLocation());
  12441. CopyAssignment->setAccess(AS_public);
  12442. CopyAssignment->setDefaulted();
  12443. CopyAssignment->setImplicit();
  12444. if (getLangOpts().CUDA) {
  12445. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  12446. CopyAssignment,
  12447. /* ConstRHS */ Const,
  12448. /* Diagnose */ false);
  12449. }
  12450. setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
  12451. // Add the parameter to the operator.
  12452. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  12453. ClassLoc, ClassLoc,
  12454. /*Id=*/nullptr, ArgType,
  12455. /*TInfo=*/nullptr, SC_None,
  12456. nullptr);
  12457. CopyAssignment->setParams(FromParam);
  12458. CopyAssignment->setTrivial(
  12459. ClassDecl->needsOverloadResolutionForCopyAssignment()
  12460. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  12461. : ClassDecl->hasTrivialCopyAssignment());
  12462. // Note that we have added this copy-assignment operator.
  12463. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
  12464. Scope *S = getScopeForContext(ClassDecl);
  12465. CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
  12466. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
  12467. ClassDecl->setImplicitCopyAssignmentIsDeleted();
  12468. SetDeclDeleted(CopyAssignment, ClassLoc);
  12469. }
  12470. if (S)
  12471. PushOnScopeChains(CopyAssignment, S, false);
  12472. ClassDecl->addDecl(CopyAssignment);
  12473. return CopyAssignment;
  12474. }
  12475. /// Diagnose an implicit copy operation for a class which is odr-used, but
  12476. /// which is deprecated because the class has a user-declared copy constructor,
  12477. /// copy assignment operator, or destructor.
  12478. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
  12479. assert(CopyOp->isImplicit());
  12480. CXXRecordDecl *RD = CopyOp->getParent();
  12481. CXXMethodDecl *UserDeclaredOperation = nullptr;
  12482. // In Microsoft mode, assignment operations don't affect constructors and
  12483. // vice versa.
  12484. if (RD->hasUserDeclaredDestructor()) {
  12485. UserDeclaredOperation = RD->getDestructor();
  12486. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  12487. RD->hasUserDeclaredCopyConstructor() &&
  12488. !S.getLangOpts().MSVCCompat) {
  12489. // Find any user-declared copy constructor.
  12490. for (auto *I : RD->ctors()) {
  12491. if (I->isCopyConstructor()) {
  12492. UserDeclaredOperation = I;
  12493. break;
  12494. }
  12495. }
  12496. assert(UserDeclaredOperation);
  12497. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  12498. RD->hasUserDeclaredCopyAssignment() &&
  12499. !S.getLangOpts().MSVCCompat) {
  12500. // Find any user-declared move assignment operator.
  12501. for (auto *I : RD->methods()) {
  12502. if (I->isCopyAssignmentOperator()) {
  12503. UserDeclaredOperation = I;
  12504. break;
  12505. }
  12506. }
  12507. assert(UserDeclaredOperation);
  12508. }
  12509. if (UserDeclaredOperation) {
  12510. bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
  12511. bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
  12512. bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
  12513. unsigned DiagID =
  12514. (UDOIsUserProvided && UDOIsDestructor)
  12515. ? diag::warn_deprecated_copy_with_user_provided_dtor
  12516. : (UDOIsUserProvided && !UDOIsDestructor)
  12517. ? diag::warn_deprecated_copy_with_user_provided_copy
  12518. : (!UDOIsUserProvided && UDOIsDestructor)
  12519. ? diag::warn_deprecated_copy_with_dtor
  12520. : diag::warn_deprecated_copy;
  12521. S.Diag(UserDeclaredOperation->getLocation(), DiagID)
  12522. << RD << IsCopyAssignment;
  12523. }
  12524. }
  12525. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  12526. CXXMethodDecl *CopyAssignOperator) {
  12527. assert((CopyAssignOperator->isDefaulted() &&
  12528. CopyAssignOperator->isOverloadedOperator() &&
  12529. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  12530. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  12531. !CopyAssignOperator->isDeleted()) &&
  12532. "DefineImplicitCopyAssignment called for wrong function");
  12533. if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
  12534. return;
  12535. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  12536. if (ClassDecl->isInvalidDecl()) {
  12537. CopyAssignOperator->setInvalidDecl();
  12538. return;
  12539. }
  12540. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  12541. // The exception specification is needed because we are defining the
  12542. // function.
  12543. ResolveExceptionSpec(CurrentLocation,
  12544. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  12545. // Add a context note for diagnostics produced after this point.
  12546. Scope.addContextNote(CurrentLocation);
  12547. // C++11 [class.copy]p18:
  12548. // The [definition of an implicitly declared copy assignment operator] is
  12549. // deprecated if the class has a user-declared copy constructor or a
  12550. // user-declared destructor.
  12551. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  12552. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
  12553. // C++0x [class.copy]p30:
  12554. // The implicitly-defined or explicitly-defaulted copy assignment operator
  12555. // for a non-union class X performs memberwise copy assignment of its
  12556. // subobjects. The direct base classes of X are assigned first, in the
  12557. // order of their declaration in the base-specifier-list, and then the
  12558. // immediate non-static data members of X are assigned, in the order in
  12559. // which they were declared in the class definition.
  12560. // The statements that form the synthesized function body.
  12561. SmallVector<Stmt*, 8> Statements;
  12562. // The parameter for the "other" object, which we are copying from.
  12563. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  12564. Qualifiers OtherQuals = Other->getType().getQualifiers();
  12565. QualType OtherRefType = Other->getType();
  12566. if (const LValueReferenceType *OtherRef
  12567. = OtherRefType->getAs<LValueReferenceType>()) {
  12568. OtherRefType = OtherRef->getPointeeType();
  12569. OtherQuals = OtherRefType.getQualifiers();
  12570. }
  12571. // Our location for everything implicitly-generated.
  12572. SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
  12573. ? CopyAssignOperator->getEndLoc()
  12574. : CopyAssignOperator->getLocation();
  12575. // Builds a DeclRefExpr for the "other" object.
  12576. RefBuilder OtherRef(Other, OtherRefType);
  12577. // Builds the "this" pointer.
  12578. ThisBuilder This;
  12579. // Assign base classes.
  12580. bool Invalid = false;
  12581. for (auto &Base : ClassDecl->bases()) {
  12582. // Form the assignment:
  12583. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  12584. QualType BaseType = Base.getType().getUnqualifiedType();
  12585. if (!BaseType->isRecordType()) {
  12586. Invalid = true;
  12587. continue;
  12588. }
  12589. CXXCastPath BasePath;
  12590. BasePath.push_back(&Base);
  12591. // Construct the "from" expression, which is an implicit cast to the
  12592. // appropriately-qualified base type.
  12593. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  12594. VK_LValue, BasePath);
  12595. // Dereference "this".
  12596. DerefBuilder DerefThis(This);
  12597. CastBuilder To(DerefThis,
  12598. Context.getQualifiedType(
  12599. BaseType, CopyAssignOperator->getMethodQualifiers()),
  12600. VK_LValue, BasePath);
  12601. // Build the copy.
  12602. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  12603. To, From,
  12604. /*CopyingBaseSubobject=*/true,
  12605. /*Copying=*/true);
  12606. if (Copy.isInvalid()) {
  12607. CopyAssignOperator->setInvalidDecl();
  12608. return;
  12609. }
  12610. // Success! Record the copy.
  12611. Statements.push_back(Copy.getAs<Expr>());
  12612. }
  12613. // Assign non-static members.
  12614. for (auto *Field : ClassDecl->fields()) {
  12615. // FIXME: We should form some kind of AST representation for the implied
  12616. // memcpy in a union copy operation.
  12617. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  12618. continue;
  12619. if (Field->isInvalidDecl()) {
  12620. Invalid = true;
  12621. continue;
  12622. }
  12623. // Check for members of reference type; we can't copy those.
  12624. if (Field->getType()->isReferenceType()) {
  12625. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  12626. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  12627. Diag(Field->getLocation(), diag::note_declared_at);
  12628. Invalid = true;
  12629. continue;
  12630. }
  12631. // Check for members of const-qualified, non-class type.
  12632. QualType BaseType = Context.getBaseElementType(Field->getType());
  12633. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  12634. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  12635. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  12636. Diag(Field->getLocation(), diag::note_declared_at);
  12637. Invalid = true;
  12638. continue;
  12639. }
  12640. // Suppress assigning zero-width bitfields.
  12641. if (Field->isZeroLengthBitField(Context))
  12642. continue;
  12643. QualType FieldType = Field->getType().getNonReferenceType();
  12644. if (FieldType->isIncompleteArrayType()) {
  12645. assert(ClassDecl->hasFlexibleArrayMember() &&
  12646. "Incomplete array type is not valid");
  12647. continue;
  12648. }
  12649. // Build references to the field in the object we're copying from and to.
  12650. CXXScopeSpec SS; // Intentionally empty
  12651. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  12652. LookupMemberName);
  12653. MemberLookup.addDecl(Field);
  12654. MemberLookup.resolveKind();
  12655. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  12656. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  12657. // Build the copy of this field.
  12658. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  12659. To, From,
  12660. /*CopyingBaseSubobject=*/false,
  12661. /*Copying=*/true);
  12662. if (Copy.isInvalid()) {
  12663. CopyAssignOperator->setInvalidDecl();
  12664. return;
  12665. }
  12666. // Success! Record the copy.
  12667. Statements.push_back(Copy.getAs<Stmt>());
  12668. }
  12669. if (!Invalid) {
  12670. // Add a "return *this;"
  12671. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  12672. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  12673. if (Return.isInvalid())
  12674. Invalid = true;
  12675. else
  12676. Statements.push_back(Return.getAs<Stmt>());
  12677. }
  12678. if (Invalid) {
  12679. CopyAssignOperator->setInvalidDecl();
  12680. return;
  12681. }
  12682. StmtResult Body;
  12683. {
  12684. CompoundScopeRAII CompoundScope(*this);
  12685. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  12686. /*isStmtExpr=*/false);
  12687. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  12688. }
  12689. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  12690. CopyAssignOperator->markUsed(Context);
  12691. if (ASTMutationListener *L = getASTMutationListener()) {
  12692. L->CompletedImplicitDefinition(CopyAssignOperator);
  12693. }
  12694. }
  12695. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  12696. assert(ClassDecl->needsImplicitMoveAssignment());
  12697. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  12698. if (DSM.isAlreadyBeingDeclared())
  12699. return nullptr;
  12700. // Note: The following rules are largely analoguous to the move
  12701. // constructor rules.
  12702. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  12703. LangAS AS = getDefaultCXXMethodAddrSpace();
  12704. if (AS != LangAS::Default)
  12705. ArgType = Context.getAddrSpaceQualType(ArgType, AS);
  12706. QualType RetType = Context.getLValueReferenceType(ArgType);
  12707. ArgType = Context.getRValueReferenceType(ArgType);
  12708. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  12709. CXXMoveAssignment,
  12710. false);
  12711. // An implicitly-declared move assignment operator is an inline public
  12712. // member of its class.
  12713. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  12714. SourceLocation ClassLoc = ClassDecl->getLocation();
  12715. DeclarationNameInfo NameInfo(Name, ClassLoc);
  12716. CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
  12717. Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  12718. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  12719. getCurFPFeatures().isFPConstrained(),
  12720. /*isInline=*/true,
  12721. Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
  12722. SourceLocation());
  12723. MoveAssignment->setAccess(AS_public);
  12724. MoveAssignment->setDefaulted();
  12725. MoveAssignment->setImplicit();
  12726. if (getLangOpts().CUDA) {
  12727. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  12728. MoveAssignment,
  12729. /* ConstRHS */ false,
  12730. /* Diagnose */ false);
  12731. }
  12732. setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
  12733. // Add the parameter to the operator.
  12734. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  12735. ClassLoc, ClassLoc,
  12736. /*Id=*/nullptr, ArgType,
  12737. /*TInfo=*/nullptr, SC_None,
  12738. nullptr);
  12739. MoveAssignment->setParams(FromParam);
  12740. MoveAssignment->setTrivial(
  12741. ClassDecl->needsOverloadResolutionForMoveAssignment()
  12742. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  12743. : ClassDecl->hasTrivialMoveAssignment());
  12744. // Note that we have added this copy-assignment operator.
  12745. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
  12746. Scope *S = getScopeForContext(ClassDecl);
  12747. CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
  12748. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  12749. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  12750. SetDeclDeleted(MoveAssignment, ClassLoc);
  12751. }
  12752. if (S)
  12753. PushOnScopeChains(MoveAssignment, S, false);
  12754. ClassDecl->addDecl(MoveAssignment);
  12755. return MoveAssignment;
  12756. }
  12757. /// Check if we're implicitly defining a move assignment operator for a class
  12758. /// with virtual bases. Such a move assignment might move-assign the virtual
  12759. /// base multiple times.
  12760. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  12761. SourceLocation CurrentLocation) {
  12762. assert(!Class->isDependentContext() && "should not define dependent move");
  12763. // Only a virtual base could get implicitly move-assigned multiple times.
  12764. // Only a non-trivial move assignment can observe this. We only want to
  12765. // diagnose if we implicitly define an assignment operator that assigns
  12766. // two base classes, both of which move-assign the same virtual base.
  12767. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  12768. Class->getNumBases() < 2)
  12769. return;
  12770. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  12771. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  12772. VBaseMap VBases;
  12773. for (auto &BI : Class->bases()) {
  12774. Worklist.push_back(&BI);
  12775. while (!Worklist.empty()) {
  12776. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  12777. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  12778. // If the base has no non-trivial move assignment operators,
  12779. // we don't care about moves from it.
  12780. if (!Base->hasNonTrivialMoveAssignment())
  12781. continue;
  12782. // If there's nothing virtual here, skip it.
  12783. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  12784. continue;
  12785. // If we're not actually going to call a move assignment for this base,
  12786. // or the selected move assignment is trivial, skip it.
  12787. Sema::SpecialMemberOverloadResult SMOR =
  12788. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  12789. /*ConstArg*/false, /*VolatileArg*/false,
  12790. /*RValueThis*/true, /*ConstThis*/false,
  12791. /*VolatileThis*/false);
  12792. if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
  12793. !SMOR.getMethod()->isMoveAssignmentOperator())
  12794. continue;
  12795. if (BaseSpec->isVirtual()) {
  12796. // We're going to move-assign this virtual base, and its move
  12797. // assignment operator is not trivial. If this can happen for
  12798. // multiple distinct direct bases of Class, diagnose it. (If it
  12799. // only happens in one base, we'll diagnose it when synthesizing
  12800. // that base class's move assignment operator.)
  12801. CXXBaseSpecifier *&Existing =
  12802. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  12803. .first->second;
  12804. if (Existing && Existing != &BI) {
  12805. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  12806. << Class << Base;
  12807. S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
  12808. << (Base->getCanonicalDecl() ==
  12809. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  12810. << Base << Existing->getType() << Existing->getSourceRange();
  12811. S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
  12812. << (Base->getCanonicalDecl() ==
  12813. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  12814. << Base << BI.getType() << BaseSpec->getSourceRange();
  12815. // Only diagnose each vbase once.
  12816. Existing = nullptr;
  12817. }
  12818. } else {
  12819. // Only walk over bases that have defaulted move assignment operators.
  12820. // We assume that any user-provided move assignment operator handles
  12821. // the multiple-moves-of-vbase case itself somehow.
  12822. if (!SMOR.getMethod()->isDefaulted())
  12823. continue;
  12824. // We're going to move the base classes of Base. Add them to the list.
  12825. for (auto &BI : Base->bases())
  12826. Worklist.push_back(&BI);
  12827. }
  12828. }
  12829. }
  12830. }
  12831. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  12832. CXXMethodDecl *MoveAssignOperator) {
  12833. assert((MoveAssignOperator->isDefaulted() &&
  12834. MoveAssignOperator->isOverloadedOperator() &&
  12835. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  12836. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  12837. !MoveAssignOperator->isDeleted()) &&
  12838. "DefineImplicitMoveAssignment called for wrong function");
  12839. if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
  12840. return;
  12841. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  12842. if (ClassDecl->isInvalidDecl()) {
  12843. MoveAssignOperator->setInvalidDecl();
  12844. return;
  12845. }
  12846. // C++0x [class.copy]p28:
  12847. // The implicitly-defined or move assignment operator for a non-union class
  12848. // X performs memberwise move assignment of its subobjects. The direct base
  12849. // classes of X are assigned first, in the order of their declaration in the
  12850. // base-specifier-list, and then the immediate non-static data members of X
  12851. // are assigned, in the order in which they were declared in the class
  12852. // definition.
  12853. // Issue a warning if our implicit move assignment operator will move
  12854. // from a virtual base more than once.
  12855. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  12856. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  12857. // The exception specification is needed because we are defining the
  12858. // function.
  12859. ResolveExceptionSpec(CurrentLocation,
  12860. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  12861. // Add a context note for diagnostics produced after this point.
  12862. Scope.addContextNote(CurrentLocation);
  12863. // The statements that form the synthesized function body.
  12864. SmallVector<Stmt*, 8> Statements;
  12865. // The parameter for the "other" object, which we are move from.
  12866. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  12867. QualType OtherRefType =
  12868. Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
  12869. // Our location for everything implicitly-generated.
  12870. SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
  12871. ? MoveAssignOperator->getEndLoc()
  12872. : MoveAssignOperator->getLocation();
  12873. // Builds a reference to the "other" object.
  12874. RefBuilder OtherRef(Other, OtherRefType);
  12875. // Cast to rvalue.
  12876. MoveCastBuilder MoveOther(OtherRef);
  12877. // Builds the "this" pointer.
  12878. ThisBuilder This;
  12879. // Assign base classes.
  12880. bool Invalid = false;
  12881. for (auto &Base : ClassDecl->bases()) {
  12882. // C++11 [class.copy]p28:
  12883. // It is unspecified whether subobjects representing virtual base classes
  12884. // are assigned more than once by the implicitly-defined copy assignment
  12885. // operator.
  12886. // FIXME: Do not assign to a vbase that will be assigned by some other base
  12887. // class. For a move-assignment, this can result in the vbase being moved
  12888. // multiple times.
  12889. // Form the assignment:
  12890. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  12891. QualType BaseType = Base.getType().getUnqualifiedType();
  12892. if (!BaseType->isRecordType()) {
  12893. Invalid = true;
  12894. continue;
  12895. }
  12896. CXXCastPath BasePath;
  12897. BasePath.push_back(&Base);
  12898. // Construct the "from" expression, which is an implicit cast to the
  12899. // appropriately-qualified base type.
  12900. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  12901. // Dereference "this".
  12902. DerefBuilder DerefThis(This);
  12903. // Implicitly cast "this" to the appropriately-qualified base type.
  12904. CastBuilder To(DerefThis,
  12905. Context.getQualifiedType(
  12906. BaseType, MoveAssignOperator->getMethodQualifiers()),
  12907. VK_LValue, BasePath);
  12908. // Build the move.
  12909. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  12910. To, From,
  12911. /*CopyingBaseSubobject=*/true,
  12912. /*Copying=*/false);
  12913. if (Move.isInvalid()) {
  12914. MoveAssignOperator->setInvalidDecl();
  12915. return;
  12916. }
  12917. // Success! Record the move.
  12918. Statements.push_back(Move.getAs<Expr>());
  12919. }
  12920. // Assign non-static members.
  12921. for (auto *Field : ClassDecl->fields()) {
  12922. // FIXME: We should form some kind of AST representation for the implied
  12923. // memcpy in a union copy operation.
  12924. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  12925. continue;
  12926. if (Field->isInvalidDecl()) {
  12927. Invalid = true;
  12928. continue;
  12929. }
  12930. // Check for members of reference type; we can't move those.
  12931. if (Field->getType()->isReferenceType()) {
  12932. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  12933. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  12934. Diag(Field->getLocation(), diag::note_declared_at);
  12935. Invalid = true;
  12936. continue;
  12937. }
  12938. // Check for members of const-qualified, non-class type.
  12939. QualType BaseType = Context.getBaseElementType(Field->getType());
  12940. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  12941. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  12942. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  12943. Diag(Field->getLocation(), diag::note_declared_at);
  12944. Invalid = true;
  12945. continue;
  12946. }
  12947. // Suppress assigning zero-width bitfields.
  12948. if (Field->isZeroLengthBitField(Context))
  12949. continue;
  12950. QualType FieldType = Field->getType().getNonReferenceType();
  12951. if (FieldType->isIncompleteArrayType()) {
  12952. assert(ClassDecl->hasFlexibleArrayMember() &&
  12953. "Incomplete array type is not valid");
  12954. continue;
  12955. }
  12956. // Build references to the field in the object we're copying from and to.
  12957. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  12958. LookupMemberName);
  12959. MemberLookup.addDecl(Field);
  12960. MemberLookup.resolveKind();
  12961. MemberBuilder From(MoveOther, OtherRefType,
  12962. /*IsArrow=*/false, MemberLookup);
  12963. MemberBuilder To(This, getCurrentThisType(),
  12964. /*IsArrow=*/true, MemberLookup);
  12965. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  12966. "Member reference with rvalue base must be rvalue except for reference "
  12967. "members, which aren't allowed for move assignment.");
  12968. // Build the move of this field.
  12969. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  12970. To, From,
  12971. /*CopyingBaseSubobject=*/false,
  12972. /*Copying=*/false);
  12973. if (Move.isInvalid()) {
  12974. MoveAssignOperator->setInvalidDecl();
  12975. return;
  12976. }
  12977. // Success! Record the copy.
  12978. Statements.push_back(Move.getAs<Stmt>());
  12979. }
  12980. if (!Invalid) {
  12981. // Add a "return *this;"
  12982. ExprResult ThisObj =
  12983. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  12984. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  12985. if (Return.isInvalid())
  12986. Invalid = true;
  12987. else
  12988. Statements.push_back(Return.getAs<Stmt>());
  12989. }
  12990. if (Invalid) {
  12991. MoveAssignOperator->setInvalidDecl();
  12992. return;
  12993. }
  12994. StmtResult Body;
  12995. {
  12996. CompoundScopeRAII CompoundScope(*this);
  12997. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  12998. /*isStmtExpr=*/false);
  12999. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  13000. }
  13001. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  13002. MoveAssignOperator->markUsed(Context);
  13003. if (ASTMutationListener *L = getASTMutationListener()) {
  13004. L->CompletedImplicitDefinition(MoveAssignOperator);
  13005. }
  13006. }
  13007. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  13008. CXXRecordDecl *ClassDecl) {
  13009. // C++ [class.copy]p4:
  13010. // If the class definition does not explicitly declare a copy
  13011. // constructor, one is declared implicitly.
  13012. assert(ClassDecl->needsImplicitCopyConstructor());
  13013. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  13014. if (DSM.isAlreadyBeingDeclared())
  13015. return nullptr;
  13016. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  13017. QualType ArgType = ClassType;
  13018. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  13019. if (Const)
  13020. ArgType = ArgType.withConst();
  13021. LangAS AS = getDefaultCXXMethodAddrSpace();
  13022. if (AS != LangAS::Default)
  13023. ArgType = Context.getAddrSpaceQualType(ArgType, AS);
  13024. ArgType = Context.getLValueReferenceType(ArgType);
  13025. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  13026. CXXCopyConstructor,
  13027. Const);
  13028. DeclarationName Name
  13029. = Context.DeclarationNames.getCXXConstructorName(
  13030. Context.getCanonicalType(ClassType));
  13031. SourceLocation ClassLoc = ClassDecl->getLocation();
  13032. DeclarationNameInfo NameInfo(Name, ClassLoc);
  13033. // An implicitly-declared copy constructor is an inline public
  13034. // member of its class.
  13035. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  13036. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  13037. ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
  13038. /*isInline=*/true,
  13039. /*isImplicitlyDeclared=*/true,
  13040. Constexpr ? ConstexprSpecKind::Constexpr
  13041. : ConstexprSpecKind::Unspecified);
  13042. CopyConstructor->setAccess(AS_public);
  13043. CopyConstructor->setDefaulted();
  13044. if (getLangOpts().CUDA) {
  13045. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  13046. CopyConstructor,
  13047. /* ConstRHS */ Const,
  13048. /* Diagnose */ false);
  13049. }
  13050. setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
  13051. // During template instantiation of special member functions we need a
  13052. // reliable TypeSourceInfo for the parameter types in order to allow functions
  13053. // to be substituted.
  13054. TypeSourceInfo *TSI = nullptr;
  13055. if (inTemplateInstantiation() && ClassDecl->isLambda())
  13056. TSI = Context.getTrivialTypeSourceInfo(ArgType);
  13057. // Add the parameter to the constructor.
  13058. ParmVarDecl *FromParam =
  13059. ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
  13060. /*IdentifierInfo=*/nullptr, ArgType,
  13061. /*TInfo=*/TSI, SC_None, nullptr);
  13062. CopyConstructor->setParams(FromParam);
  13063. CopyConstructor->setTrivial(
  13064. ClassDecl->needsOverloadResolutionForCopyConstructor()
  13065. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  13066. : ClassDecl->hasTrivialCopyConstructor());
  13067. CopyConstructor->setTrivialForCall(
  13068. ClassDecl->hasAttr<TrivialABIAttr>() ||
  13069. (ClassDecl->needsOverloadResolutionForCopyConstructor()
  13070. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
  13071. TAH_ConsiderTrivialABI)
  13072. : ClassDecl->hasTrivialCopyConstructorForCall()));
  13073. // Note that we have declared this constructor.
  13074. ++getASTContext().NumImplicitCopyConstructorsDeclared;
  13075. Scope *S = getScopeForContext(ClassDecl);
  13076. CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
  13077. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
  13078. ClassDecl->setImplicitCopyConstructorIsDeleted();
  13079. SetDeclDeleted(CopyConstructor, ClassLoc);
  13080. }
  13081. if (S)
  13082. PushOnScopeChains(CopyConstructor, S, false);
  13083. ClassDecl->addDecl(CopyConstructor);
  13084. return CopyConstructor;
  13085. }
  13086. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  13087. CXXConstructorDecl *CopyConstructor) {
  13088. assert((CopyConstructor->isDefaulted() &&
  13089. CopyConstructor->isCopyConstructor() &&
  13090. !CopyConstructor->doesThisDeclarationHaveABody() &&
  13091. !CopyConstructor->isDeleted()) &&
  13092. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  13093. if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
  13094. return;
  13095. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  13096. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  13097. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  13098. // The exception specification is needed because we are defining the
  13099. // function.
  13100. ResolveExceptionSpec(CurrentLocation,
  13101. CopyConstructor->getType()->castAs<FunctionProtoType>());
  13102. MarkVTableUsed(CurrentLocation, ClassDecl);
  13103. // Add a context note for diagnostics produced after this point.
  13104. Scope.addContextNote(CurrentLocation);
  13105. // C++11 [class.copy]p7:
  13106. // The [definition of an implicitly declared copy constructor] is
  13107. // deprecated if the class has a user-declared copy assignment operator
  13108. // or a user-declared destructor.
  13109. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  13110. diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
  13111. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
  13112. CopyConstructor->setInvalidDecl();
  13113. } else {
  13114. SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
  13115. ? CopyConstructor->getEndLoc()
  13116. : CopyConstructor->getLocation();
  13117. Sema::CompoundScopeRAII CompoundScope(*this);
  13118. CopyConstructor->setBody(
  13119. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  13120. CopyConstructor->markUsed(Context);
  13121. }
  13122. if (ASTMutationListener *L = getASTMutationListener()) {
  13123. L->CompletedImplicitDefinition(CopyConstructor);
  13124. }
  13125. }
  13126. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  13127. CXXRecordDecl *ClassDecl) {
  13128. assert(ClassDecl->needsImplicitMoveConstructor());
  13129. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  13130. if (DSM.isAlreadyBeingDeclared())
  13131. return nullptr;
  13132. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  13133. QualType ArgType = ClassType;
  13134. LangAS AS = getDefaultCXXMethodAddrSpace();
  13135. if (AS != LangAS::Default)
  13136. ArgType = Context.getAddrSpaceQualType(ClassType, AS);
  13137. ArgType = Context.getRValueReferenceType(ArgType);
  13138. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  13139. CXXMoveConstructor,
  13140. false);
  13141. DeclarationName Name
  13142. = Context.DeclarationNames.getCXXConstructorName(
  13143. Context.getCanonicalType(ClassType));
  13144. SourceLocation ClassLoc = ClassDecl->getLocation();
  13145. DeclarationNameInfo NameInfo(Name, ClassLoc);
  13146. // C++11 [class.copy]p11:
  13147. // An implicitly-declared copy/move constructor is an inline public
  13148. // member of its class.
  13149. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  13150. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  13151. ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
  13152. /*isInline=*/true,
  13153. /*isImplicitlyDeclared=*/true,
  13154. Constexpr ? ConstexprSpecKind::Constexpr
  13155. : ConstexprSpecKind::Unspecified);
  13156. MoveConstructor->setAccess(AS_public);
  13157. MoveConstructor->setDefaulted();
  13158. if (getLangOpts().CUDA) {
  13159. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  13160. MoveConstructor,
  13161. /* ConstRHS */ false,
  13162. /* Diagnose */ false);
  13163. }
  13164. setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
  13165. // Add the parameter to the constructor.
  13166. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  13167. ClassLoc, ClassLoc,
  13168. /*IdentifierInfo=*/nullptr,
  13169. ArgType, /*TInfo=*/nullptr,
  13170. SC_None, nullptr);
  13171. MoveConstructor->setParams(FromParam);
  13172. MoveConstructor->setTrivial(
  13173. ClassDecl->needsOverloadResolutionForMoveConstructor()
  13174. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  13175. : ClassDecl->hasTrivialMoveConstructor());
  13176. MoveConstructor->setTrivialForCall(
  13177. ClassDecl->hasAttr<TrivialABIAttr>() ||
  13178. (ClassDecl->needsOverloadResolutionForMoveConstructor()
  13179. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
  13180. TAH_ConsiderTrivialABI)
  13181. : ClassDecl->hasTrivialMoveConstructorForCall()));
  13182. // Note that we have declared this constructor.
  13183. ++getASTContext().NumImplicitMoveConstructorsDeclared;
  13184. Scope *S = getScopeForContext(ClassDecl);
  13185. CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
  13186. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  13187. ClassDecl->setImplicitMoveConstructorIsDeleted();
  13188. SetDeclDeleted(MoveConstructor, ClassLoc);
  13189. }
  13190. if (S)
  13191. PushOnScopeChains(MoveConstructor, S, false);
  13192. ClassDecl->addDecl(MoveConstructor);
  13193. return MoveConstructor;
  13194. }
  13195. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  13196. CXXConstructorDecl *MoveConstructor) {
  13197. assert((MoveConstructor->isDefaulted() &&
  13198. MoveConstructor->isMoveConstructor() &&
  13199. !MoveConstructor->doesThisDeclarationHaveABody() &&
  13200. !MoveConstructor->isDeleted()) &&
  13201. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  13202. if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
  13203. return;
  13204. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  13205. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  13206. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  13207. // The exception specification is needed because we are defining the
  13208. // function.
  13209. ResolveExceptionSpec(CurrentLocation,
  13210. MoveConstructor->getType()->castAs<FunctionProtoType>());
  13211. MarkVTableUsed(CurrentLocation, ClassDecl);
  13212. // Add a context note for diagnostics produced after this point.
  13213. Scope.addContextNote(CurrentLocation);
  13214. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
  13215. MoveConstructor->setInvalidDecl();
  13216. } else {
  13217. SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
  13218. ? MoveConstructor->getEndLoc()
  13219. : MoveConstructor->getLocation();
  13220. Sema::CompoundScopeRAII CompoundScope(*this);
  13221. MoveConstructor->setBody(ActOnCompoundStmt(
  13222. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  13223. MoveConstructor->markUsed(Context);
  13224. }
  13225. if (ASTMutationListener *L = getASTMutationListener()) {
  13226. L->CompletedImplicitDefinition(MoveConstructor);
  13227. }
  13228. }
  13229. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  13230. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  13231. }
  13232. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  13233. SourceLocation CurrentLocation,
  13234. CXXConversionDecl *Conv) {
  13235. SynthesizedFunctionScope Scope(*this, Conv);
  13236. assert(!Conv->getReturnType()->isUndeducedType());
  13237. QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
  13238. CallingConv CC =
  13239. ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
  13240. CXXRecordDecl *Lambda = Conv->getParent();
  13241. FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
  13242. FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
  13243. if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
  13244. CallOp = InstantiateFunctionDeclaration(
  13245. CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  13246. if (!CallOp)
  13247. return;
  13248. Invoker = InstantiateFunctionDeclaration(
  13249. Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
  13250. if (!Invoker)
  13251. return;
  13252. }
  13253. if (CallOp->isInvalidDecl())
  13254. return;
  13255. // Mark the call operator referenced (and add to pending instantiations
  13256. // if necessary).
  13257. // For both the conversion and static-invoker template specializations
  13258. // we construct their body's in this function, so no need to add them
  13259. // to the PendingInstantiations.
  13260. MarkFunctionReferenced(CurrentLocation, CallOp);
  13261. // Fill in the __invoke function with a dummy implementation. IR generation
  13262. // will fill in the actual details. Update its type in case it contained
  13263. // an 'auto'.
  13264. Invoker->markUsed(Context);
  13265. Invoker->setReferenced();
  13266. Invoker->setType(Conv->getReturnType()->getPointeeType());
  13267. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  13268. // Construct the body of the conversion function { return __invoke; }.
  13269. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  13270. VK_LValue, Conv->getLocation());
  13271. assert(FunctionRef && "Can't refer to __invoke function?");
  13272. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  13273. Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
  13274. Conv->getLocation()));
  13275. Conv->markUsed(Context);
  13276. Conv->setReferenced();
  13277. if (ASTMutationListener *L = getASTMutationListener()) {
  13278. L->CompletedImplicitDefinition(Conv);
  13279. L->CompletedImplicitDefinition(Invoker);
  13280. }
  13281. }
  13282. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  13283. SourceLocation CurrentLocation,
  13284. CXXConversionDecl *Conv)
  13285. {
  13286. assert(!Conv->getParent()->isGenericLambda());
  13287. SynthesizedFunctionScope Scope(*this, Conv);
  13288. // Copy-initialize the lambda object as needed to capture it.
  13289. Expr *This = ActOnCXXThis(CurrentLocation).get();
  13290. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  13291. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  13292. Conv->getLocation(),
  13293. Conv, DerefThis);
  13294. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  13295. // behavior. Note that only the general conversion function does this
  13296. // (since it's unusable otherwise); in the case where we inline the
  13297. // block literal, it has block literal lifetime semantics.
  13298. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  13299. BuildBlock = ImplicitCastExpr::Create(
  13300. Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
  13301. BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
  13302. if (BuildBlock.isInvalid()) {
  13303. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  13304. Conv->setInvalidDecl();
  13305. return;
  13306. }
  13307. // Create the return statement that returns the block from the conversion
  13308. // function.
  13309. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  13310. if (Return.isInvalid()) {
  13311. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  13312. Conv->setInvalidDecl();
  13313. return;
  13314. }
  13315. // Set the body of the conversion function.
  13316. Stmt *ReturnS = Return.get();
  13317. Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
  13318. Conv->getLocation()));
  13319. Conv->markUsed(Context);
  13320. // We're done; notify the mutation listener, if any.
  13321. if (ASTMutationListener *L = getASTMutationListener()) {
  13322. L->CompletedImplicitDefinition(Conv);
  13323. }
  13324. }
  13325. /// Determine whether the given list arguments contains exactly one
  13326. /// "real" (non-default) argument.
  13327. static bool hasOneRealArgument(MultiExprArg Args) {
  13328. switch (Args.size()) {
  13329. case 0:
  13330. return false;
  13331. default:
  13332. if (!Args[1]->isDefaultArgument())
  13333. return false;
  13334. LLVM_FALLTHROUGH;
  13335. case 1:
  13336. return !Args[0]->isDefaultArgument();
  13337. }
  13338. return false;
  13339. }
  13340. ExprResult
  13341. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  13342. NamedDecl *FoundDecl,
  13343. CXXConstructorDecl *Constructor,
  13344. MultiExprArg ExprArgs,
  13345. bool HadMultipleCandidates,
  13346. bool IsListInitialization,
  13347. bool IsStdInitListInitialization,
  13348. bool RequiresZeroInit,
  13349. unsigned ConstructKind,
  13350. SourceRange ParenRange) {
  13351. bool Elidable = false;
  13352. // C++0x [class.copy]p34:
  13353. // When certain criteria are met, an implementation is allowed to
  13354. // omit the copy/move construction of a class object, even if the
  13355. // copy/move constructor and/or destructor for the object have
  13356. // side effects. [...]
  13357. // - when a temporary class object that has not been bound to a
  13358. // reference (12.2) would be copied/moved to a class object
  13359. // with the same cv-unqualified type, the copy/move operation
  13360. // can be omitted by constructing the temporary object
  13361. // directly into the target of the omitted copy/move
  13362. if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
  13363. // FIXME: Converting constructors should also be accepted.
  13364. // But to fix this, the logic that digs down into a CXXConstructExpr
  13365. // to find the source object needs to handle it.
  13366. // Right now it assumes the source object is passed directly as the
  13367. // first argument.
  13368. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  13369. Expr *SubExpr = ExprArgs[0];
  13370. // FIXME: Per above, this is also incorrect if we want to accept
  13371. // converting constructors, as isTemporaryObject will
  13372. // reject temporaries with different type from the
  13373. // CXXRecord itself.
  13374. Elidable = SubExpr->isTemporaryObject(
  13375. Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  13376. }
  13377. return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
  13378. FoundDecl, Constructor,
  13379. Elidable, ExprArgs, HadMultipleCandidates,
  13380. IsListInitialization,
  13381. IsStdInitListInitialization, RequiresZeroInit,
  13382. ConstructKind, ParenRange);
  13383. }
  13384. ExprResult
  13385. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  13386. NamedDecl *FoundDecl,
  13387. CXXConstructorDecl *Constructor,
  13388. bool Elidable,
  13389. MultiExprArg ExprArgs,
  13390. bool HadMultipleCandidates,
  13391. bool IsListInitialization,
  13392. bool IsStdInitListInitialization,
  13393. bool RequiresZeroInit,
  13394. unsigned ConstructKind,
  13395. SourceRange ParenRange) {
  13396. if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
  13397. Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
  13398. if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
  13399. return ExprError();
  13400. }
  13401. return BuildCXXConstructExpr(
  13402. ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
  13403. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  13404. RequiresZeroInit, ConstructKind, ParenRange);
  13405. }
  13406. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  13407. /// including handling of its default argument expressions.
  13408. ExprResult
  13409. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  13410. CXXConstructorDecl *Constructor,
  13411. bool Elidable,
  13412. MultiExprArg ExprArgs,
  13413. bool HadMultipleCandidates,
  13414. bool IsListInitialization,
  13415. bool IsStdInitListInitialization,
  13416. bool RequiresZeroInit,
  13417. unsigned ConstructKind,
  13418. SourceRange ParenRange) {
  13419. assert(declaresSameEntity(
  13420. Constructor->getParent(),
  13421. DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
  13422. "given constructor for wrong type");
  13423. MarkFunctionReferenced(ConstructLoc, Constructor);
  13424. if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
  13425. return ExprError();
  13426. if (getLangOpts().SYCLIsDevice &&
  13427. !checkSYCLDeviceFunction(ConstructLoc, Constructor))
  13428. return ExprError();
  13429. return CheckForImmediateInvocation(
  13430. CXXConstructExpr::Create(
  13431. Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
  13432. HadMultipleCandidates, IsListInitialization,
  13433. IsStdInitListInitialization, RequiresZeroInit,
  13434. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  13435. ParenRange),
  13436. Constructor);
  13437. }
  13438. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  13439. assert(Field->hasInClassInitializer());
  13440. // If we already have the in-class initializer nothing needs to be done.
  13441. if (Field->getInClassInitializer())
  13442. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  13443. // If we might have already tried and failed to instantiate, don't try again.
  13444. if (Field->isInvalidDecl())
  13445. return ExprError();
  13446. // Maybe we haven't instantiated the in-class initializer. Go check the
  13447. // pattern FieldDecl to see if it has one.
  13448. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  13449. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  13450. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  13451. DeclContext::lookup_result Lookup =
  13452. ClassPattern->lookup(Field->getDeclName());
  13453. FieldDecl *Pattern = nullptr;
  13454. for (auto L : Lookup) {
  13455. if (isa<FieldDecl>(L)) {
  13456. Pattern = cast<FieldDecl>(L);
  13457. break;
  13458. }
  13459. }
  13460. assert(Pattern && "We must have set the Pattern!");
  13461. if (!Pattern->hasInClassInitializer() ||
  13462. InstantiateInClassInitializer(Loc, Field, Pattern,
  13463. getTemplateInstantiationArgs(Field))) {
  13464. // Don't diagnose this again.
  13465. Field->setInvalidDecl();
  13466. return ExprError();
  13467. }
  13468. return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
  13469. }
  13470. // DR1351:
  13471. // If the brace-or-equal-initializer of a non-static data member
  13472. // invokes a defaulted default constructor of its class or of an
  13473. // enclosing class in a potentially evaluated subexpression, the
  13474. // program is ill-formed.
  13475. //
  13476. // This resolution is unworkable: the exception specification of the
  13477. // default constructor can be needed in an unevaluated context, in
  13478. // particular, in the operand of a noexcept-expression, and we can be
  13479. // unable to compute an exception specification for an enclosed class.
  13480. //
  13481. // Any attempt to resolve the exception specification of a defaulted default
  13482. // constructor before the initializer is lexically complete will ultimately
  13483. // come here at which point we can diagnose it.
  13484. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  13485. Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
  13486. << OutermostClass << Field;
  13487. Diag(Field->getEndLoc(),
  13488. diag::note_default_member_initializer_not_yet_parsed);
  13489. // Recover by marking the field invalid, unless we're in a SFINAE context.
  13490. if (!isSFINAEContext())
  13491. Field->setInvalidDecl();
  13492. return ExprError();
  13493. }
  13494. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  13495. if (VD->isInvalidDecl()) return;
  13496. // If initializing the variable failed, don't also diagnose problems with
  13497. // the destructor, they're likely related.
  13498. if (VD->getInit() && VD->getInit()->containsErrors())
  13499. return;
  13500. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  13501. if (ClassDecl->isInvalidDecl()) return;
  13502. if (ClassDecl->hasIrrelevantDestructor()) return;
  13503. if (ClassDecl->isDependentContext()) return;
  13504. if (VD->isNoDestroy(getASTContext()))
  13505. return;
  13506. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  13507. // If this is an array, we'll require the destructor during initialization, so
  13508. // we can skip over this. We still want to emit exit-time destructor warnings
  13509. // though.
  13510. if (!VD->getType()->isArrayType()) {
  13511. MarkFunctionReferenced(VD->getLocation(), Destructor);
  13512. CheckDestructorAccess(VD->getLocation(), Destructor,
  13513. PDiag(diag::err_access_dtor_var)
  13514. << VD->getDeclName() << VD->getType());
  13515. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  13516. }
  13517. if (Destructor->isTrivial()) return;
  13518. // If the destructor is constexpr, check whether the variable has constant
  13519. // destruction now.
  13520. if (Destructor->isConstexpr()) {
  13521. bool HasConstantInit = false;
  13522. if (VD->getInit() && !VD->getInit()->isValueDependent())
  13523. HasConstantInit = VD->evaluateValue();
  13524. SmallVector<PartialDiagnosticAt, 8> Notes;
  13525. if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
  13526. HasConstantInit) {
  13527. Diag(VD->getLocation(),
  13528. diag::err_constexpr_var_requires_const_destruction) << VD;
  13529. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  13530. Diag(Notes[I].first, Notes[I].second);
  13531. }
  13532. }
  13533. if (!VD->hasGlobalStorage()) return;
  13534. // Emit warning for non-trivial dtor in global scope (a real global,
  13535. // class-static, function-static).
  13536. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  13537. // TODO: this should be re-enabled for static locals by !CXAAtExit
  13538. if (!VD->isStaticLocal())
  13539. Diag(VD->getLocation(), diag::warn_global_destructor);
  13540. }
  13541. /// Given a constructor and the set of arguments provided for the
  13542. /// constructor, convert the arguments and add any required default arguments
  13543. /// to form a proper call to this constructor.
  13544. ///
  13545. /// \returns true if an error occurred, false otherwise.
  13546. bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  13547. QualType DeclInitType, MultiExprArg ArgsPtr,
  13548. SourceLocation Loc,
  13549. SmallVectorImpl<Expr *> &ConvertedArgs,
  13550. bool AllowExplicit,
  13551. bool IsListInitialization) {
  13552. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  13553. unsigned NumArgs = ArgsPtr.size();
  13554. Expr **Args = ArgsPtr.data();
  13555. const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
  13556. unsigned NumParams = Proto->getNumParams();
  13557. // If too few arguments are available, we'll fill in the rest with defaults.
  13558. if (NumArgs < NumParams)
  13559. ConvertedArgs.reserve(NumParams);
  13560. else
  13561. ConvertedArgs.reserve(NumArgs);
  13562. VariadicCallType CallType =
  13563. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  13564. SmallVector<Expr *, 8> AllArgs;
  13565. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  13566. Proto, 0,
  13567. llvm::makeArrayRef(Args, NumArgs),
  13568. AllArgs,
  13569. CallType, AllowExplicit,
  13570. IsListInitialization);
  13571. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  13572. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  13573. CheckConstructorCall(Constructor, DeclInitType,
  13574. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  13575. Proto, Loc);
  13576. return Invalid;
  13577. }
  13578. static inline bool
  13579. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  13580. const FunctionDecl *FnDecl) {
  13581. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  13582. if (isa<NamespaceDecl>(DC)) {
  13583. return SemaRef.Diag(FnDecl->getLocation(),
  13584. diag::err_operator_new_delete_declared_in_namespace)
  13585. << FnDecl->getDeclName();
  13586. }
  13587. if (isa<TranslationUnitDecl>(DC) &&
  13588. FnDecl->getStorageClass() == SC_Static) {
  13589. return SemaRef.Diag(FnDecl->getLocation(),
  13590. diag::err_operator_new_delete_declared_static)
  13591. << FnDecl->getDeclName();
  13592. }
  13593. return false;
  13594. }
  13595. static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
  13596. const PointerType *PtrTy) {
  13597. auto &Ctx = SemaRef.Context;
  13598. Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
  13599. PtrQuals.removeAddressSpace();
  13600. return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
  13601. PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
  13602. }
  13603. static inline bool
  13604. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  13605. CanQualType ExpectedResultType,
  13606. CanQualType ExpectedFirstParamType,
  13607. unsigned DependentParamTypeDiag,
  13608. unsigned InvalidParamTypeDiag) {
  13609. QualType ResultType =
  13610. FnDecl->getType()->castAs<FunctionType>()->getReturnType();
  13611. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  13612. // The operator is valid on any address space for OpenCL.
  13613. // Drop address space from actual and expected result types.
  13614. if (const auto *PtrTy = ResultType->getAs<PointerType>())
  13615. ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  13616. if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
  13617. ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
  13618. }
  13619. // Check that the result type is what we expect.
  13620. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
  13621. // Reject even if the type is dependent; an operator delete function is
  13622. // required to have a non-dependent result type.
  13623. return SemaRef.Diag(
  13624. FnDecl->getLocation(),
  13625. ResultType->isDependentType()
  13626. ? diag::err_operator_new_delete_dependent_result_type
  13627. : diag::err_operator_new_delete_invalid_result_type)
  13628. << FnDecl->getDeclName() << ExpectedResultType;
  13629. }
  13630. // A function template must have at least 2 parameters.
  13631. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  13632. return SemaRef.Diag(FnDecl->getLocation(),
  13633. diag::err_operator_new_delete_template_too_few_parameters)
  13634. << FnDecl->getDeclName();
  13635. // The function decl must have at least 1 parameter.
  13636. if (FnDecl->getNumParams() == 0)
  13637. return SemaRef.Diag(FnDecl->getLocation(),
  13638. diag::err_operator_new_delete_too_few_parameters)
  13639. << FnDecl->getDeclName();
  13640. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  13641. if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
  13642. // The operator is valid on any address space for OpenCL.
  13643. // Drop address space from actual and expected first parameter types.
  13644. if (const auto *PtrTy =
  13645. FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
  13646. FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
  13647. if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
  13648. ExpectedFirstParamType =
  13649. RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
  13650. }
  13651. // Check that the first parameter type is what we expect.
  13652. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  13653. ExpectedFirstParamType) {
  13654. // The first parameter type is not allowed to be dependent. As a tentative
  13655. // DR resolution, we allow a dependent parameter type if it is the right
  13656. // type anyway, to allow destroying operator delete in class templates.
  13657. return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
  13658. ? DependentParamTypeDiag
  13659. : InvalidParamTypeDiag)
  13660. << FnDecl->getDeclName() << ExpectedFirstParamType;
  13661. }
  13662. return false;
  13663. }
  13664. static bool
  13665. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  13666. // C++ [basic.stc.dynamic.allocation]p1:
  13667. // A program is ill-formed if an allocation function is declared in a
  13668. // namespace scope other than global scope or declared static in global
  13669. // scope.
  13670. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  13671. return true;
  13672. CanQualType SizeTy =
  13673. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  13674. // C++ [basic.stc.dynamic.allocation]p1:
  13675. // The return type shall be void*. The first parameter shall have type
  13676. // std::size_t.
  13677. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  13678. SizeTy,
  13679. diag::err_operator_new_dependent_param_type,
  13680. diag::err_operator_new_param_type))
  13681. return true;
  13682. // C++ [basic.stc.dynamic.allocation]p1:
  13683. // The first parameter shall not have an associated default argument.
  13684. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  13685. return SemaRef.Diag(FnDecl->getLocation(),
  13686. diag::err_operator_new_default_arg)
  13687. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  13688. return false;
  13689. }
  13690. static bool
  13691. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  13692. // C++ [basic.stc.dynamic.deallocation]p1:
  13693. // A program is ill-formed if deallocation functions are declared in a
  13694. // namespace scope other than global scope or declared static in global
  13695. // scope.
  13696. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  13697. return true;
  13698. auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
  13699. // C++ P0722:
  13700. // Within a class C, the first parameter of a destroying operator delete
  13701. // shall be of type C *. The first parameter of any other deallocation
  13702. // function shall be of type void *.
  13703. CanQualType ExpectedFirstParamType =
  13704. MD && MD->isDestroyingOperatorDelete()
  13705. ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
  13706. SemaRef.Context.getRecordType(MD->getParent())))
  13707. : SemaRef.Context.VoidPtrTy;
  13708. // C++ [basic.stc.dynamic.deallocation]p2:
  13709. // Each deallocation function shall return void
  13710. if (CheckOperatorNewDeleteTypes(
  13711. SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
  13712. diag::err_operator_delete_dependent_param_type,
  13713. diag::err_operator_delete_param_type))
  13714. return true;
  13715. // C++ P0722:
  13716. // A destroying operator delete shall be a usual deallocation function.
  13717. if (MD && !MD->getParent()->isDependentContext() &&
  13718. MD->isDestroyingOperatorDelete() &&
  13719. !SemaRef.isUsualDeallocationFunction(MD)) {
  13720. SemaRef.Diag(MD->getLocation(),
  13721. diag::err_destroying_operator_delete_not_usual);
  13722. return true;
  13723. }
  13724. return false;
  13725. }
  13726. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  13727. /// of this overloaded operator is well-formed. If so, returns false;
  13728. /// otherwise, emits appropriate diagnostics and returns true.
  13729. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  13730. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  13731. "Expected an overloaded operator declaration");
  13732. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  13733. // C++ [over.oper]p5:
  13734. // The allocation and deallocation functions, operator new,
  13735. // operator new[], operator delete and operator delete[], are
  13736. // described completely in 3.7.3. The attributes and restrictions
  13737. // found in the rest of this subclause do not apply to them unless
  13738. // explicitly stated in 3.7.3.
  13739. if (Op == OO_Delete || Op == OO_Array_Delete)
  13740. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  13741. if (Op == OO_New || Op == OO_Array_New)
  13742. return CheckOperatorNewDeclaration(*this, FnDecl);
  13743. // C++ [over.oper]p6:
  13744. // An operator function shall either be a non-static member
  13745. // function or be a non-member function and have at least one
  13746. // parameter whose type is a class, a reference to a class, an
  13747. // enumeration, or a reference to an enumeration.
  13748. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  13749. if (MethodDecl->isStatic())
  13750. return Diag(FnDecl->getLocation(),
  13751. diag::err_operator_overload_static) << FnDecl->getDeclName();
  13752. } else {
  13753. bool ClassOrEnumParam = false;
  13754. for (auto Param : FnDecl->parameters()) {
  13755. QualType ParamType = Param->getType().getNonReferenceType();
  13756. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  13757. ParamType->isEnumeralType()) {
  13758. ClassOrEnumParam = true;
  13759. break;
  13760. }
  13761. }
  13762. if (!ClassOrEnumParam)
  13763. return Diag(FnDecl->getLocation(),
  13764. diag::err_operator_overload_needs_class_or_enum)
  13765. << FnDecl->getDeclName();
  13766. }
  13767. // C++ [over.oper]p8:
  13768. // An operator function cannot have default arguments (8.3.6),
  13769. // except where explicitly stated below.
  13770. //
  13771. // Only the function-call operator allows default arguments
  13772. // (C++ [over.call]p1).
  13773. if (Op != OO_Call) {
  13774. for (auto Param : FnDecl->parameters()) {
  13775. if (Param->hasDefaultArg())
  13776. return Diag(Param->getLocation(),
  13777. diag::err_operator_overload_default_arg)
  13778. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  13779. }
  13780. }
  13781. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  13782. { false, false, false }
  13783. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  13784. , { Unary, Binary, MemberOnly }
  13785. #include "clang/Basic/OperatorKinds.def"
  13786. };
  13787. bool CanBeUnaryOperator = OperatorUses[Op][0];
  13788. bool CanBeBinaryOperator = OperatorUses[Op][1];
  13789. bool MustBeMemberOperator = OperatorUses[Op][2];
  13790. // C++ [over.oper]p8:
  13791. // [...] Operator functions cannot have more or fewer parameters
  13792. // than the number required for the corresponding operator, as
  13793. // described in the rest of this subclause.
  13794. unsigned NumParams = FnDecl->getNumParams()
  13795. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  13796. if (Op != OO_Call &&
  13797. ((NumParams == 1 && !CanBeUnaryOperator) ||
  13798. (NumParams == 2 && !CanBeBinaryOperator) ||
  13799. (NumParams < 1) || (NumParams > 2))) {
  13800. // We have the wrong number of parameters.
  13801. unsigned ErrorKind;
  13802. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  13803. ErrorKind = 2; // 2 -> unary or binary.
  13804. } else if (CanBeUnaryOperator) {
  13805. ErrorKind = 0; // 0 -> unary
  13806. } else {
  13807. assert(CanBeBinaryOperator &&
  13808. "All non-call overloaded operators are unary or binary!");
  13809. ErrorKind = 1; // 1 -> binary
  13810. }
  13811. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  13812. << FnDecl->getDeclName() << NumParams << ErrorKind;
  13813. }
  13814. // Overloaded operators other than operator() cannot be variadic.
  13815. if (Op != OO_Call &&
  13816. FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
  13817. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  13818. << FnDecl->getDeclName();
  13819. }
  13820. // Some operators must be non-static member functions.
  13821. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  13822. return Diag(FnDecl->getLocation(),
  13823. diag::err_operator_overload_must_be_member)
  13824. << FnDecl->getDeclName();
  13825. }
  13826. // C++ [over.inc]p1:
  13827. // The user-defined function called operator++ implements the
  13828. // prefix and postfix ++ operator. If this function is a member
  13829. // function with no parameters, or a non-member function with one
  13830. // parameter of class or enumeration type, it defines the prefix
  13831. // increment operator ++ for objects of that type. If the function
  13832. // is a member function with one parameter (which shall be of type
  13833. // int) or a non-member function with two parameters (the second
  13834. // of which shall be of type int), it defines the postfix
  13835. // increment operator ++ for objects of that type.
  13836. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  13837. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  13838. QualType ParamType = LastParam->getType();
  13839. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  13840. !ParamType->isDependentType())
  13841. return Diag(LastParam->getLocation(),
  13842. diag::err_operator_overload_post_incdec_must_be_int)
  13843. << LastParam->getType() << (Op == OO_MinusMinus);
  13844. }
  13845. return false;
  13846. }
  13847. static bool
  13848. checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
  13849. FunctionTemplateDecl *TpDecl) {
  13850. TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
  13851. // Must have one or two template parameters.
  13852. if (TemplateParams->size() == 1) {
  13853. NonTypeTemplateParmDecl *PmDecl =
  13854. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
  13855. // The template parameter must be a char parameter pack.
  13856. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  13857. SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
  13858. return false;
  13859. // C++20 [over.literal]p5:
  13860. // A string literal operator template is a literal operator template
  13861. // whose template-parameter-list comprises a single non-type
  13862. // template-parameter of class type.
  13863. //
  13864. // As a DR resolution, we also allow placeholders for deduced class
  13865. // template specializations.
  13866. if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
  13867. !PmDecl->isTemplateParameterPack() &&
  13868. (PmDecl->getType()->isRecordType() ||
  13869. PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
  13870. return false;
  13871. } else if (TemplateParams->size() == 2) {
  13872. TemplateTypeParmDecl *PmType =
  13873. dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
  13874. NonTypeTemplateParmDecl *PmArgs =
  13875. dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
  13876. // The second template parameter must be a parameter pack with the
  13877. // first template parameter as its type.
  13878. if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
  13879. PmArgs->isTemplateParameterPack()) {
  13880. const TemplateTypeParmType *TArgs =
  13881. PmArgs->getType()->getAs<TemplateTypeParmType>();
  13882. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  13883. TArgs->getIndex() == PmType->getIndex()) {
  13884. if (!SemaRef.inTemplateInstantiation())
  13885. SemaRef.Diag(TpDecl->getLocation(),
  13886. diag::ext_string_literal_operator_template);
  13887. return false;
  13888. }
  13889. }
  13890. }
  13891. SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
  13892. diag::err_literal_operator_template)
  13893. << TpDecl->getTemplateParameters()->getSourceRange();
  13894. return true;
  13895. }
  13896. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  13897. /// of this literal operator function is well-formed. If so, returns
  13898. /// false; otherwise, emits appropriate diagnostics and returns true.
  13899. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  13900. if (isa<CXXMethodDecl>(FnDecl)) {
  13901. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  13902. << FnDecl->getDeclName();
  13903. return true;
  13904. }
  13905. if (FnDecl->isExternC()) {
  13906. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  13907. if (const LinkageSpecDecl *LSD =
  13908. FnDecl->getDeclContext()->getExternCContext())
  13909. Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
  13910. return true;
  13911. }
  13912. // This might be the definition of a literal operator template.
  13913. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  13914. // This might be a specialization of a literal operator template.
  13915. if (!TpDecl)
  13916. TpDecl = FnDecl->getPrimaryTemplate();
  13917. // template <char...> type operator "" name() and
  13918. // template <class T, T...> type operator "" name() are the only valid
  13919. // template signatures, and the only valid signatures with no parameters.
  13920. //
  13921. // C++20 also allows template <SomeClass T> type operator "" name().
  13922. if (TpDecl) {
  13923. if (FnDecl->param_size() != 0) {
  13924. Diag(FnDecl->getLocation(),
  13925. diag::err_literal_operator_template_with_params);
  13926. return true;
  13927. }
  13928. if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
  13929. return true;
  13930. } else if (FnDecl->param_size() == 1) {
  13931. const ParmVarDecl *Param = FnDecl->getParamDecl(0);
  13932. QualType ParamType = Param->getType().getUnqualifiedType();
  13933. // Only unsigned long long int, long double, any character type, and const
  13934. // char * are allowed as the only parameters.
  13935. if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  13936. ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
  13937. Context.hasSameType(ParamType, Context.CharTy) ||
  13938. Context.hasSameType(ParamType, Context.WideCharTy) ||
  13939. Context.hasSameType(ParamType, Context.Char8Ty) ||
  13940. Context.hasSameType(ParamType, Context.Char16Ty) ||
  13941. Context.hasSameType(ParamType, Context.Char32Ty)) {
  13942. } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
  13943. QualType InnerType = Ptr->getPointeeType();
  13944. // Pointer parameter must be a const char *.
  13945. if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
  13946. Context.CharTy) &&
  13947. InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
  13948. Diag(Param->getSourceRange().getBegin(),
  13949. diag::err_literal_operator_param)
  13950. << ParamType << "'const char *'" << Param->getSourceRange();
  13951. return true;
  13952. }
  13953. } else if (ParamType->isRealFloatingType()) {
  13954. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  13955. << ParamType << Context.LongDoubleTy << Param->getSourceRange();
  13956. return true;
  13957. } else if (ParamType->isIntegerType()) {
  13958. Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
  13959. << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
  13960. return true;
  13961. } else {
  13962. Diag(Param->getSourceRange().getBegin(),
  13963. diag::err_literal_operator_invalid_param)
  13964. << ParamType << Param->getSourceRange();
  13965. return true;
  13966. }
  13967. } else if (FnDecl->param_size() == 2) {
  13968. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  13969. // First, verify that the first parameter is correct.
  13970. QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
  13971. // Two parameter function must have a pointer to const as a
  13972. // first parameter; let's strip those qualifiers.
  13973. const PointerType *PT = FirstParamType->getAs<PointerType>();
  13974. if (!PT) {
  13975. Diag((*Param)->getSourceRange().getBegin(),
  13976. diag::err_literal_operator_param)
  13977. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  13978. return true;
  13979. }
  13980. QualType PointeeType = PT->getPointeeType();
  13981. // First parameter must be const
  13982. if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
  13983. Diag((*Param)->getSourceRange().getBegin(),
  13984. diag::err_literal_operator_param)
  13985. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  13986. return true;
  13987. }
  13988. QualType InnerType = PointeeType.getUnqualifiedType();
  13989. // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
  13990. // const char32_t* are allowed as the first parameter to a two-parameter
  13991. // function
  13992. if (!(Context.hasSameType(InnerType, Context.CharTy) ||
  13993. Context.hasSameType(InnerType, Context.WideCharTy) ||
  13994. Context.hasSameType(InnerType, Context.Char8Ty) ||
  13995. Context.hasSameType(InnerType, Context.Char16Ty) ||
  13996. Context.hasSameType(InnerType, Context.Char32Ty))) {
  13997. Diag((*Param)->getSourceRange().getBegin(),
  13998. diag::err_literal_operator_param)
  13999. << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
  14000. return true;
  14001. }
  14002. // Move on to the second and final parameter.
  14003. ++Param;
  14004. // The second parameter must be a std::size_t.
  14005. QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
  14006. if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
  14007. Diag((*Param)->getSourceRange().getBegin(),
  14008. diag::err_literal_operator_param)
  14009. << SecondParamType << Context.getSizeType()
  14010. << (*Param)->getSourceRange();
  14011. return true;
  14012. }
  14013. } else {
  14014. Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
  14015. return true;
  14016. }
  14017. // Parameters are good.
  14018. // A parameter-declaration-clause containing a default argument is not
  14019. // equivalent to any of the permitted forms.
  14020. for (auto Param : FnDecl->parameters()) {
  14021. if (Param->hasDefaultArg()) {
  14022. Diag(Param->getDefaultArgRange().getBegin(),
  14023. diag::err_literal_operator_default_argument)
  14024. << Param->getDefaultArgRange();
  14025. break;
  14026. }
  14027. }
  14028. StringRef LiteralName
  14029. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  14030. if (LiteralName[0] != '_' &&
  14031. !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
  14032. // C++11 [usrlit.suffix]p1:
  14033. // Literal suffix identifiers that do not start with an underscore
  14034. // are reserved for future standardization.
  14035. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  14036. << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  14037. }
  14038. return false;
  14039. }
  14040. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  14041. /// linkage specification, including the language and (if present)
  14042. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  14043. /// language string literal. LBraceLoc, if valid, provides the location of
  14044. /// the '{' brace. Otherwise, this linkage specification does not
  14045. /// have any braces.
  14046. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  14047. Expr *LangStr,
  14048. SourceLocation LBraceLoc) {
  14049. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  14050. if (!Lit->isAscii()) {
  14051. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  14052. << LangStr->getSourceRange();
  14053. return nullptr;
  14054. }
  14055. StringRef Lang = Lit->getString();
  14056. LinkageSpecDecl::LanguageIDs Language;
  14057. if (Lang == "C")
  14058. Language = LinkageSpecDecl::lang_c;
  14059. else if (Lang == "C++")
  14060. Language = LinkageSpecDecl::lang_cxx;
  14061. else {
  14062. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  14063. << LangStr->getSourceRange();
  14064. return nullptr;
  14065. }
  14066. // FIXME: Add all the various semantics of linkage specifications
  14067. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  14068. LangStr->getExprLoc(), Language,
  14069. LBraceLoc.isValid());
  14070. /// C++ [module.unit]p7.2.3
  14071. /// - Otherwise, if the declaration
  14072. /// - ...
  14073. /// - ...
  14074. /// - appears within a linkage-specification,
  14075. /// it is attached to the global module.
  14076. ///
  14077. /// If the declaration is already in global module fragment, we don't
  14078. /// need to attach it again.
  14079. if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
  14080. Module *GlobalModule =
  14081. PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
  14082. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  14083. D->setLocalOwningModule(GlobalModule);
  14084. }
  14085. CurContext->addDecl(D);
  14086. PushDeclContext(S, D);
  14087. return D;
  14088. }
  14089. /// ActOnFinishLinkageSpecification - Complete the definition of
  14090. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  14091. /// valid, it's the position of the closing '}' brace in a linkage
  14092. /// specification that uses braces.
  14093. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  14094. Decl *LinkageSpec,
  14095. SourceLocation RBraceLoc) {
  14096. if (RBraceLoc.isValid()) {
  14097. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  14098. LSDecl->setRBraceLoc(RBraceLoc);
  14099. }
  14100. // If the current module doesn't has Parent, it implies that the
  14101. // LinkageSpec isn't in the module created by itself. So we don't
  14102. // need to pop it.
  14103. if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
  14104. getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
  14105. PopGlobalModuleFragment();
  14106. PopDeclContext();
  14107. return LinkageSpec;
  14108. }
  14109. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  14110. const ParsedAttributesView &AttrList,
  14111. SourceLocation SemiLoc) {
  14112. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  14113. // Attribute declarations appertain to empty declaration so we handle
  14114. // them here.
  14115. ProcessDeclAttributeList(S, ED, AttrList);
  14116. CurContext->addDecl(ED);
  14117. return ED;
  14118. }
  14119. /// Perform semantic analysis for the variable declaration that
  14120. /// occurs within a C++ catch clause, returning the newly-created
  14121. /// variable.
  14122. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  14123. TypeSourceInfo *TInfo,
  14124. SourceLocation StartLoc,
  14125. SourceLocation Loc,
  14126. IdentifierInfo *Name) {
  14127. bool Invalid = false;
  14128. QualType ExDeclType = TInfo->getType();
  14129. // Arrays and functions decay.
  14130. if (ExDeclType->isArrayType())
  14131. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  14132. else if (ExDeclType->isFunctionType())
  14133. ExDeclType = Context.getPointerType(ExDeclType);
  14134. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  14135. // The exception-declaration shall not denote a pointer or reference to an
  14136. // incomplete type, other than [cv] void*.
  14137. // N2844 forbids rvalue references.
  14138. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  14139. Diag(Loc, diag::err_catch_rvalue_ref);
  14140. Invalid = true;
  14141. }
  14142. if (ExDeclType->isVariablyModifiedType()) {
  14143. Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
  14144. Invalid = true;
  14145. }
  14146. QualType BaseType = ExDeclType;
  14147. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  14148. unsigned DK = diag::err_catch_incomplete;
  14149. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  14150. BaseType = Ptr->getPointeeType();
  14151. Mode = 1;
  14152. DK = diag::err_catch_incomplete_ptr;
  14153. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  14154. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  14155. BaseType = Ref->getPointeeType();
  14156. Mode = 2;
  14157. DK = diag::err_catch_incomplete_ref;
  14158. }
  14159. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  14160. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  14161. Invalid = true;
  14162. if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
  14163. Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
  14164. Invalid = true;
  14165. }
  14166. if (!Invalid && !ExDeclType->isDependentType() &&
  14167. RequireNonAbstractType(Loc, ExDeclType,
  14168. diag::err_abstract_type_in_decl,
  14169. AbstractVariableType))
  14170. Invalid = true;
  14171. // Only the non-fragile NeXT runtime currently supports C++ catches
  14172. // of ObjC types, and no runtime supports catching ObjC types by value.
  14173. if (!Invalid && getLangOpts().ObjC) {
  14174. QualType T = ExDeclType;
  14175. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  14176. T = RT->getPointeeType();
  14177. if (T->isObjCObjectType()) {
  14178. Diag(Loc, diag::err_objc_object_catch);
  14179. Invalid = true;
  14180. } else if (T->isObjCObjectPointerType()) {
  14181. // FIXME: should this be a test for macosx-fragile specifically?
  14182. if (getLangOpts().ObjCRuntime.isFragile())
  14183. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  14184. }
  14185. }
  14186. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  14187. ExDeclType, TInfo, SC_None);
  14188. ExDecl->setExceptionVariable(true);
  14189. // In ARC, infer 'retaining' for variables of retainable type.
  14190. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  14191. Invalid = true;
  14192. if (!Invalid && !ExDeclType->isDependentType()) {
  14193. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  14194. // Insulate this from anything else we might currently be parsing.
  14195. EnterExpressionEvaluationContext scope(
  14196. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  14197. // C++ [except.handle]p16:
  14198. // The object declared in an exception-declaration or, if the
  14199. // exception-declaration does not specify a name, a temporary (12.2) is
  14200. // copy-initialized (8.5) from the exception object. [...]
  14201. // The object is destroyed when the handler exits, after the destruction
  14202. // of any automatic objects initialized within the handler.
  14203. //
  14204. // We just pretend to initialize the object with itself, then make sure
  14205. // it can be destroyed later.
  14206. QualType initType = Context.getExceptionObjectType(ExDeclType);
  14207. InitializedEntity entity =
  14208. InitializedEntity::InitializeVariable(ExDecl);
  14209. InitializationKind initKind =
  14210. InitializationKind::CreateCopy(Loc, SourceLocation());
  14211. Expr *opaqueValue =
  14212. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  14213. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  14214. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  14215. if (result.isInvalid())
  14216. Invalid = true;
  14217. else {
  14218. // If the constructor used was non-trivial, set this as the
  14219. // "initializer".
  14220. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  14221. if (!construct->getConstructor()->isTrivial()) {
  14222. Expr *init = MaybeCreateExprWithCleanups(construct);
  14223. ExDecl->setInit(init);
  14224. }
  14225. // And make sure it's destructable.
  14226. FinalizeVarWithDestructor(ExDecl, recordType);
  14227. }
  14228. }
  14229. }
  14230. if (Invalid)
  14231. ExDecl->setInvalidDecl();
  14232. return ExDecl;
  14233. }
  14234. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  14235. /// handler.
  14236. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  14237. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14238. bool Invalid = D.isInvalidType();
  14239. // Check for unexpanded parameter packs.
  14240. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  14241. UPPC_ExceptionType)) {
  14242. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  14243. D.getIdentifierLoc());
  14244. Invalid = true;
  14245. }
  14246. IdentifierInfo *II = D.getIdentifier();
  14247. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  14248. LookupOrdinaryName,
  14249. ForVisibleRedeclaration)) {
  14250. // The scope should be freshly made just for us. There is just no way
  14251. // it contains any previous declaration, except for function parameters in
  14252. // a function-try-block's catch statement.
  14253. assert(!S->isDeclScope(PrevDecl));
  14254. if (isDeclInScope(PrevDecl, CurContext, S)) {
  14255. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  14256. << D.getIdentifier();
  14257. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  14258. Invalid = true;
  14259. } else if (PrevDecl->isTemplateParameter())
  14260. // Maybe we will complain about the shadowed template parameter.
  14261. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  14262. }
  14263. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  14264. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  14265. << D.getCXXScopeSpec().getRange();
  14266. Invalid = true;
  14267. }
  14268. VarDecl *ExDecl = BuildExceptionDeclaration(
  14269. S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
  14270. if (Invalid)
  14271. ExDecl->setInvalidDecl();
  14272. // Add the exception declaration into this scope.
  14273. if (II)
  14274. PushOnScopeChains(ExDecl, S);
  14275. else
  14276. CurContext->addDecl(ExDecl);
  14277. ProcessDeclAttributes(S, ExDecl, D);
  14278. return ExDecl;
  14279. }
  14280. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  14281. Expr *AssertExpr,
  14282. Expr *AssertMessageExpr,
  14283. SourceLocation RParenLoc) {
  14284. StringLiteral *AssertMessage =
  14285. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  14286. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  14287. return nullptr;
  14288. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  14289. AssertMessage, RParenLoc, false);
  14290. }
  14291. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  14292. Expr *AssertExpr,
  14293. StringLiteral *AssertMessage,
  14294. SourceLocation RParenLoc,
  14295. bool Failed) {
  14296. assert(AssertExpr != nullptr && "Expected non-null condition");
  14297. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  14298. !Failed) {
  14299. // In a static_assert-declaration, the constant-expression shall be a
  14300. // constant expression that can be contextually converted to bool.
  14301. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  14302. if (Converted.isInvalid())
  14303. Failed = true;
  14304. ExprResult FullAssertExpr =
  14305. ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
  14306. /*DiscardedValue*/ false,
  14307. /*IsConstexpr*/ true);
  14308. if (FullAssertExpr.isInvalid())
  14309. Failed = true;
  14310. else
  14311. AssertExpr = FullAssertExpr.get();
  14312. llvm::APSInt Cond;
  14313. if (!Failed && VerifyIntegerConstantExpression(
  14314. AssertExpr, &Cond,
  14315. diag::err_static_assert_expression_is_not_constant)
  14316. .isInvalid())
  14317. Failed = true;
  14318. if (!Failed && !Cond) {
  14319. SmallString<256> MsgBuffer;
  14320. llvm::raw_svector_ostream Msg(MsgBuffer);
  14321. if (AssertMessage)
  14322. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  14323. Expr *InnerCond = nullptr;
  14324. std::string InnerCondDescription;
  14325. std::tie(InnerCond, InnerCondDescription) =
  14326. findFailedBooleanCondition(Converted.get());
  14327. if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
  14328. // Drill down into concept specialization expressions to see why they
  14329. // weren't satisfied.
  14330. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  14331. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  14332. ConstraintSatisfaction Satisfaction;
  14333. if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
  14334. DiagnoseUnsatisfiedConstraint(Satisfaction);
  14335. } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
  14336. && !isa<IntegerLiteral>(InnerCond)) {
  14337. Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
  14338. << InnerCondDescription << !AssertMessage
  14339. << Msg.str() << InnerCond->getSourceRange();
  14340. } else {
  14341. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  14342. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  14343. }
  14344. Failed = true;
  14345. }
  14346. } else {
  14347. ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
  14348. /*DiscardedValue*/false,
  14349. /*IsConstexpr*/true);
  14350. if (FullAssertExpr.isInvalid())
  14351. Failed = true;
  14352. else
  14353. AssertExpr = FullAssertExpr.get();
  14354. }
  14355. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  14356. AssertExpr, AssertMessage, RParenLoc,
  14357. Failed);
  14358. CurContext->addDecl(Decl);
  14359. return Decl;
  14360. }
  14361. /// Perform semantic analysis of the given friend type declaration.
  14362. ///
  14363. /// \returns A friend declaration that.
  14364. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  14365. SourceLocation FriendLoc,
  14366. TypeSourceInfo *TSInfo) {
  14367. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  14368. QualType T = TSInfo->getType();
  14369. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  14370. // C++03 [class.friend]p2:
  14371. // An elaborated-type-specifier shall be used in a friend declaration
  14372. // for a class.*
  14373. //
  14374. // * The class-key of the elaborated-type-specifier is required.
  14375. if (!CodeSynthesisContexts.empty()) {
  14376. // Do not complain about the form of friend template types during any kind
  14377. // of code synthesis. For template instantiation, we will have complained
  14378. // when the template was defined.
  14379. } else {
  14380. if (!T->isElaboratedTypeSpecifier()) {
  14381. // If we evaluated the type to a record type, suggest putting
  14382. // a tag in front.
  14383. if (const RecordType *RT = T->getAs<RecordType>()) {
  14384. RecordDecl *RD = RT->getDecl();
  14385. SmallString<16> InsertionText(" ");
  14386. InsertionText += RD->getKindName();
  14387. Diag(TypeRange.getBegin(),
  14388. getLangOpts().CPlusPlus11 ?
  14389. diag::warn_cxx98_compat_unelaborated_friend_type :
  14390. diag::ext_unelaborated_friend_type)
  14391. << (unsigned) RD->getTagKind()
  14392. << T
  14393. << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
  14394. InsertionText);
  14395. } else {
  14396. Diag(FriendLoc,
  14397. getLangOpts().CPlusPlus11 ?
  14398. diag::warn_cxx98_compat_nonclass_type_friend :
  14399. diag::ext_nonclass_type_friend)
  14400. << T
  14401. << TypeRange;
  14402. }
  14403. } else if (T->getAs<EnumType>()) {
  14404. Diag(FriendLoc,
  14405. getLangOpts().CPlusPlus11 ?
  14406. diag::warn_cxx98_compat_enum_friend :
  14407. diag::ext_enum_friend)
  14408. << T
  14409. << TypeRange;
  14410. }
  14411. // C++11 [class.friend]p3:
  14412. // A friend declaration that does not declare a function shall have one
  14413. // of the following forms:
  14414. // friend elaborated-type-specifier ;
  14415. // friend simple-type-specifier ;
  14416. // friend typename-specifier ;
  14417. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  14418. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  14419. }
  14420. // If the type specifier in a friend declaration designates a (possibly
  14421. // cv-qualified) class type, that class is declared as a friend; otherwise,
  14422. // the friend declaration is ignored.
  14423. return FriendDecl::Create(Context, CurContext,
  14424. TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
  14425. FriendLoc);
  14426. }
  14427. /// Handle a friend tag declaration where the scope specifier was
  14428. /// templated.
  14429. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  14430. unsigned TagSpec, SourceLocation TagLoc,
  14431. CXXScopeSpec &SS, IdentifierInfo *Name,
  14432. SourceLocation NameLoc,
  14433. const ParsedAttributesView &Attr,
  14434. MultiTemplateParamsArg TempParamLists) {
  14435. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  14436. bool IsMemberSpecialization = false;
  14437. bool Invalid = false;
  14438. if (TemplateParameterList *TemplateParams =
  14439. MatchTemplateParametersToScopeSpecifier(
  14440. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  14441. IsMemberSpecialization, Invalid)) {
  14442. if (TemplateParams->size() > 0) {
  14443. // This is a declaration of a class template.
  14444. if (Invalid)
  14445. return nullptr;
  14446. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  14447. NameLoc, Attr, TemplateParams, AS_public,
  14448. /*ModulePrivateLoc=*/SourceLocation(),
  14449. FriendLoc, TempParamLists.size() - 1,
  14450. TempParamLists.data()).get();
  14451. } else {
  14452. // The "template<>" header is extraneous.
  14453. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  14454. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  14455. IsMemberSpecialization = true;
  14456. }
  14457. }
  14458. if (Invalid) return nullptr;
  14459. bool isAllExplicitSpecializations = true;
  14460. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  14461. if (TempParamLists[I]->size()) {
  14462. isAllExplicitSpecializations = false;
  14463. break;
  14464. }
  14465. }
  14466. // FIXME: don't ignore attributes.
  14467. // If it's explicit specializations all the way down, just forget
  14468. // about the template header and build an appropriate non-templated
  14469. // friend. TODO: for source fidelity, remember the headers.
  14470. if (isAllExplicitSpecializations) {
  14471. if (SS.isEmpty()) {
  14472. bool Owned = false;
  14473. bool IsDependent = false;
  14474. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  14475. Attr, AS_public,
  14476. /*ModulePrivateLoc=*/SourceLocation(),
  14477. MultiTemplateParamsArg(), Owned, IsDependent,
  14478. /*ScopedEnumKWLoc=*/SourceLocation(),
  14479. /*ScopedEnumUsesClassTag=*/false,
  14480. /*UnderlyingType=*/TypeResult(),
  14481. /*IsTypeSpecifier=*/false,
  14482. /*IsTemplateParamOrArg=*/false);
  14483. }
  14484. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  14485. ElaboratedTypeKeyword Keyword
  14486. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  14487. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  14488. *Name, NameLoc);
  14489. if (T.isNull())
  14490. return nullptr;
  14491. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  14492. if (isa<DependentNameType>(T)) {
  14493. DependentNameTypeLoc TL =
  14494. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  14495. TL.setElaboratedKeywordLoc(TagLoc);
  14496. TL.setQualifierLoc(QualifierLoc);
  14497. TL.setNameLoc(NameLoc);
  14498. } else {
  14499. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  14500. TL.setElaboratedKeywordLoc(TagLoc);
  14501. TL.setQualifierLoc(QualifierLoc);
  14502. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  14503. }
  14504. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  14505. TSI, FriendLoc, TempParamLists);
  14506. Friend->setAccess(AS_public);
  14507. CurContext->addDecl(Friend);
  14508. return Friend;
  14509. }
  14510. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  14511. // Handle the case of a templated-scope friend class. e.g.
  14512. // template <class T> class A<T>::B;
  14513. // FIXME: we don't support these right now.
  14514. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  14515. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  14516. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  14517. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  14518. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  14519. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  14520. TL.setElaboratedKeywordLoc(TagLoc);
  14521. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  14522. TL.setNameLoc(NameLoc);
  14523. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  14524. TSI, FriendLoc, TempParamLists);
  14525. Friend->setAccess(AS_public);
  14526. Friend->setUnsupportedFriend(true);
  14527. CurContext->addDecl(Friend);
  14528. return Friend;
  14529. }
  14530. /// Handle a friend type declaration. This works in tandem with
  14531. /// ActOnTag.
  14532. ///
  14533. /// Notes on friend class templates:
  14534. ///
  14535. /// We generally treat friend class declarations as if they were
  14536. /// declaring a class. So, for example, the elaborated type specifier
  14537. /// in a friend declaration is required to obey the restrictions of a
  14538. /// class-head (i.e. no typedefs in the scope chain), template
  14539. /// parameters are required to match up with simple template-ids, &c.
  14540. /// However, unlike when declaring a template specialization, it's
  14541. /// okay to refer to a template specialization without an empty
  14542. /// template parameter declaration, e.g.
  14543. /// friend class A<T>::B<unsigned>;
  14544. /// We permit this as a special case; if there are any template
  14545. /// parameters present at all, require proper matching, i.e.
  14546. /// template <> template \<class T> friend class A<int>::B;
  14547. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  14548. MultiTemplateParamsArg TempParams) {
  14549. SourceLocation Loc = DS.getBeginLoc();
  14550. assert(DS.isFriendSpecified());
  14551. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  14552. // C++ [class.friend]p3:
  14553. // A friend declaration that does not declare a function shall have one of
  14554. // the following forms:
  14555. // friend elaborated-type-specifier ;
  14556. // friend simple-type-specifier ;
  14557. // friend typename-specifier ;
  14558. //
  14559. // Any declaration with a type qualifier does not have that form. (It's
  14560. // legal to specify a qualified type as a friend, you just can't write the
  14561. // keywords.)
  14562. if (DS.getTypeQualifiers()) {
  14563. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  14564. Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
  14565. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  14566. Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
  14567. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  14568. Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
  14569. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  14570. Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
  14571. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  14572. Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
  14573. }
  14574. // Try to convert the decl specifier to a type. This works for
  14575. // friend templates because ActOnTag never produces a ClassTemplateDecl
  14576. // for a TUK_Friend.
  14577. Declarator TheDeclarator(DS, DeclaratorContext::Member);
  14578. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  14579. QualType T = TSI->getType();
  14580. if (TheDeclarator.isInvalidType())
  14581. return nullptr;
  14582. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  14583. return nullptr;
  14584. // This is definitely an error in C++98. It's probably meant to
  14585. // be forbidden in C++0x, too, but the specification is just
  14586. // poorly written.
  14587. //
  14588. // The problem is with declarations like the following:
  14589. // template <T> friend A<T>::foo;
  14590. // where deciding whether a class C is a friend or not now hinges
  14591. // on whether there exists an instantiation of A that causes
  14592. // 'foo' to equal C. There are restrictions on class-heads
  14593. // (which we declare (by fiat) elaborated friend declarations to
  14594. // be) that makes this tractable.
  14595. //
  14596. // FIXME: handle "template <> friend class A<T>;", which
  14597. // is possibly well-formed? Who even knows?
  14598. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  14599. Diag(Loc, diag::err_tagless_friend_type_template)
  14600. << DS.getSourceRange();
  14601. return nullptr;
  14602. }
  14603. // C++98 [class.friend]p1: A friend of a class is a function
  14604. // or class that is not a member of the class . . .
  14605. // This is fixed in DR77, which just barely didn't make the C++03
  14606. // deadline. It's also a very silly restriction that seriously
  14607. // affects inner classes and which nobody else seems to implement;
  14608. // thus we never diagnose it, not even in -pedantic.
  14609. //
  14610. // But note that we could warn about it: it's always useless to
  14611. // friend one of your own members (it's not, however, worthless to
  14612. // friend a member of an arbitrary specialization of your template).
  14613. Decl *D;
  14614. if (!TempParams.empty())
  14615. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  14616. TempParams,
  14617. TSI,
  14618. DS.getFriendSpecLoc());
  14619. else
  14620. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  14621. if (!D)
  14622. return nullptr;
  14623. D->setAccess(AS_public);
  14624. CurContext->addDecl(D);
  14625. return D;
  14626. }
  14627. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  14628. MultiTemplateParamsArg TemplateParams) {
  14629. const DeclSpec &DS = D.getDeclSpec();
  14630. assert(DS.isFriendSpecified());
  14631. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  14632. SourceLocation Loc = D.getIdentifierLoc();
  14633. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14634. // C++ [class.friend]p1
  14635. // A friend of a class is a function or class....
  14636. // Note that this sees through typedefs, which is intended.
  14637. // It *doesn't* see through dependent types, which is correct
  14638. // according to [temp.arg.type]p3:
  14639. // If a declaration acquires a function type through a
  14640. // type dependent on a template-parameter and this causes
  14641. // a declaration that does not use the syntactic form of a
  14642. // function declarator to have a function type, the program
  14643. // is ill-formed.
  14644. if (!TInfo->getType()->isFunctionType()) {
  14645. Diag(Loc, diag::err_unexpected_friend);
  14646. // It might be worthwhile to try to recover by creating an
  14647. // appropriate declaration.
  14648. return nullptr;
  14649. }
  14650. // C++ [namespace.memdef]p3
  14651. // - If a friend declaration in a non-local class first declares a
  14652. // class or function, the friend class or function is a member
  14653. // of the innermost enclosing namespace.
  14654. // - The name of the friend is not found by simple name lookup
  14655. // until a matching declaration is provided in that namespace
  14656. // scope (either before or after the class declaration granting
  14657. // friendship).
  14658. // - If a friend function is called, its name may be found by the
  14659. // name lookup that considers functions from namespaces and
  14660. // classes associated with the types of the function arguments.
  14661. // - When looking for a prior declaration of a class or a function
  14662. // declared as a friend, scopes outside the innermost enclosing
  14663. // namespace scope are not considered.
  14664. CXXScopeSpec &SS = D.getCXXScopeSpec();
  14665. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  14666. assert(NameInfo.getName());
  14667. // Check for unexpanded parameter packs.
  14668. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  14669. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  14670. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  14671. return nullptr;
  14672. // The context we found the declaration in, or in which we should
  14673. // create the declaration.
  14674. DeclContext *DC;
  14675. Scope *DCScope = S;
  14676. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  14677. ForExternalRedeclaration);
  14678. // There are five cases here.
  14679. // - There's no scope specifier and we're in a local class. Only look
  14680. // for functions declared in the immediately-enclosing block scope.
  14681. // We recover from invalid scope qualifiers as if they just weren't there.
  14682. FunctionDecl *FunctionContainingLocalClass = nullptr;
  14683. if ((SS.isInvalid() || !SS.isSet()) &&
  14684. (FunctionContainingLocalClass =
  14685. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  14686. // C++11 [class.friend]p11:
  14687. // If a friend declaration appears in a local class and the name
  14688. // specified is an unqualified name, a prior declaration is
  14689. // looked up without considering scopes that are outside the
  14690. // innermost enclosing non-class scope. For a friend function
  14691. // declaration, if there is no prior declaration, the program is
  14692. // ill-formed.
  14693. // Find the innermost enclosing non-class scope. This is the block
  14694. // scope containing the local class definition (or for a nested class,
  14695. // the outer local class).
  14696. DCScope = S->getFnParent();
  14697. // Look up the function name in the scope.
  14698. Previous.clear(LookupLocalFriendName);
  14699. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  14700. if (!Previous.empty()) {
  14701. // All possible previous declarations must have the same context:
  14702. // either they were declared at block scope or they are members of
  14703. // one of the enclosing local classes.
  14704. DC = Previous.getRepresentativeDecl()->getDeclContext();
  14705. } else {
  14706. // This is ill-formed, but provide the context that we would have
  14707. // declared the function in, if we were permitted to, for error recovery.
  14708. DC = FunctionContainingLocalClass;
  14709. }
  14710. adjustContextForLocalExternDecl(DC);
  14711. // C++ [class.friend]p6:
  14712. // A function can be defined in a friend declaration of a class if and
  14713. // only if the class is a non-local class (9.8), the function name is
  14714. // unqualified, and the function has namespace scope.
  14715. if (D.isFunctionDefinition()) {
  14716. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  14717. }
  14718. // - There's no scope specifier, in which case we just go to the
  14719. // appropriate scope and look for a function or function template
  14720. // there as appropriate.
  14721. } else if (SS.isInvalid() || !SS.isSet()) {
  14722. // C++11 [namespace.memdef]p3:
  14723. // If the name in a friend declaration is neither qualified nor
  14724. // a template-id and the declaration is a function or an
  14725. // elaborated-type-specifier, the lookup to determine whether
  14726. // the entity has been previously declared shall not consider
  14727. // any scopes outside the innermost enclosing namespace.
  14728. bool isTemplateId =
  14729. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
  14730. // Find the appropriate context according to the above.
  14731. DC = CurContext;
  14732. // Skip class contexts. If someone can cite chapter and verse
  14733. // for this behavior, that would be nice --- it's what GCC and
  14734. // EDG do, and it seems like a reasonable intent, but the spec
  14735. // really only says that checks for unqualified existing
  14736. // declarations should stop at the nearest enclosing namespace,
  14737. // not that they should only consider the nearest enclosing
  14738. // namespace.
  14739. while (DC->isRecord())
  14740. DC = DC->getParent();
  14741. DeclContext *LookupDC = DC->getNonTransparentContext();
  14742. while (true) {
  14743. LookupQualifiedName(Previous, LookupDC);
  14744. if (!Previous.empty()) {
  14745. DC = LookupDC;
  14746. break;
  14747. }
  14748. if (isTemplateId) {
  14749. if (isa<TranslationUnitDecl>(LookupDC)) break;
  14750. } else {
  14751. if (LookupDC->isFileContext()) break;
  14752. }
  14753. LookupDC = LookupDC->getParent();
  14754. }
  14755. DCScope = getScopeForDeclContext(S, DC);
  14756. // - There's a non-dependent scope specifier, in which case we
  14757. // compute it and do a previous lookup there for a function
  14758. // or function template.
  14759. } else if (!SS.getScopeRep()->isDependent()) {
  14760. DC = computeDeclContext(SS);
  14761. if (!DC) return nullptr;
  14762. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  14763. LookupQualifiedName(Previous, DC);
  14764. // C++ [class.friend]p1: A friend of a class is a function or
  14765. // class that is not a member of the class . . .
  14766. if (DC->Equals(CurContext))
  14767. Diag(DS.getFriendSpecLoc(),
  14768. getLangOpts().CPlusPlus11 ?
  14769. diag::warn_cxx98_compat_friend_is_member :
  14770. diag::err_friend_is_member);
  14771. if (D.isFunctionDefinition()) {
  14772. // C++ [class.friend]p6:
  14773. // A function can be defined in a friend declaration of a class if and
  14774. // only if the class is a non-local class (9.8), the function name is
  14775. // unqualified, and the function has namespace scope.
  14776. //
  14777. // FIXME: We should only do this if the scope specifier names the
  14778. // innermost enclosing namespace; otherwise the fixit changes the
  14779. // meaning of the code.
  14780. SemaDiagnosticBuilder DB
  14781. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  14782. DB << SS.getScopeRep();
  14783. if (DC->isFileContext())
  14784. DB << FixItHint::CreateRemoval(SS.getRange());
  14785. SS.clear();
  14786. }
  14787. // - There's a scope specifier that does not match any template
  14788. // parameter lists, in which case we use some arbitrary context,
  14789. // create a method or method template, and wait for instantiation.
  14790. // - There's a scope specifier that does match some template
  14791. // parameter lists, which we don't handle right now.
  14792. } else {
  14793. if (D.isFunctionDefinition()) {
  14794. // C++ [class.friend]p6:
  14795. // A function can be defined in a friend declaration of a class if and
  14796. // only if the class is a non-local class (9.8), the function name is
  14797. // unqualified, and the function has namespace scope.
  14798. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  14799. << SS.getScopeRep();
  14800. }
  14801. DC = CurContext;
  14802. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  14803. }
  14804. if (!DC->isRecord()) {
  14805. int DiagArg = -1;
  14806. switch (D.getName().getKind()) {
  14807. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  14808. case UnqualifiedIdKind::IK_ConstructorName:
  14809. DiagArg = 0;
  14810. break;
  14811. case UnqualifiedIdKind::IK_DestructorName:
  14812. DiagArg = 1;
  14813. break;
  14814. case UnqualifiedIdKind::IK_ConversionFunctionId:
  14815. DiagArg = 2;
  14816. break;
  14817. case UnqualifiedIdKind::IK_DeductionGuideName:
  14818. DiagArg = 3;
  14819. break;
  14820. case UnqualifiedIdKind::IK_Identifier:
  14821. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  14822. case UnqualifiedIdKind::IK_LiteralOperatorId:
  14823. case UnqualifiedIdKind::IK_OperatorFunctionId:
  14824. case UnqualifiedIdKind::IK_TemplateId:
  14825. break;
  14826. }
  14827. // This implies that it has to be an operator or function.
  14828. if (DiagArg >= 0) {
  14829. Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
  14830. return nullptr;
  14831. }
  14832. }
  14833. // FIXME: This is an egregious hack to cope with cases where the scope stack
  14834. // does not contain the declaration context, i.e., in an out-of-line
  14835. // definition of a class.
  14836. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  14837. if (!DCScope) {
  14838. FakeDCScope.setEntity(DC);
  14839. DCScope = &FakeDCScope;
  14840. }
  14841. bool AddToScope = true;
  14842. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  14843. TemplateParams, AddToScope);
  14844. if (!ND) return nullptr;
  14845. assert(ND->getLexicalDeclContext() == CurContext);
  14846. // If we performed typo correction, we might have added a scope specifier
  14847. // and changed the decl context.
  14848. DC = ND->getDeclContext();
  14849. // Add the function declaration to the appropriate lookup tables,
  14850. // adjusting the redeclarations list as necessary. We don't
  14851. // want to do this yet if the friending class is dependent.
  14852. //
  14853. // Also update the scope-based lookup if the target context's
  14854. // lookup context is in lexical scope.
  14855. if (!CurContext->isDependentContext()) {
  14856. DC = DC->getRedeclContext();
  14857. DC->makeDeclVisibleInContext(ND);
  14858. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  14859. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  14860. }
  14861. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  14862. D.getIdentifierLoc(), ND,
  14863. DS.getFriendSpecLoc());
  14864. FrD->setAccess(AS_public);
  14865. CurContext->addDecl(FrD);
  14866. if (ND->isInvalidDecl()) {
  14867. FrD->setInvalidDecl();
  14868. } else {
  14869. if (DC->isRecord()) CheckFriendAccess(ND);
  14870. FunctionDecl *FD;
  14871. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  14872. FD = FTD->getTemplatedDecl();
  14873. else
  14874. FD = cast<FunctionDecl>(ND);
  14875. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  14876. // default argument expression, that declaration shall be a definition
  14877. // and shall be the only declaration of the function or function
  14878. // template in the translation unit.
  14879. if (functionDeclHasDefaultArgument(FD)) {
  14880. // We can't look at FD->getPreviousDecl() because it may not have been set
  14881. // if we're in a dependent context. If the function is known to be a
  14882. // redeclaration, we will have narrowed Previous down to the right decl.
  14883. if (D.isRedeclaration()) {
  14884. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  14885. Diag(Previous.getRepresentativeDecl()->getLocation(),
  14886. diag::note_previous_declaration);
  14887. } else if (!D.isFunctionDefinition())
  14888. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  14889. }
  14890. // Mark templated-scope function declarations as unsupported.
  14891. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  14892. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  14893. << SS.getScopeRep() << SS.getRange()
  14894. << cast<CXXRecordDecl>(CurContext);
  14895. FrD->setUnsupportedFriend(true);
  14896. }
  14897. }
  14898. warnOnReservedIdentifier(ND);
  14899. return ND;
  14900. }
  14901. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  14902. AdjustDeclIfTemplate(Dcl);
  14903. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  14904. if (!Fn) {
  14905. Diag(DelLoc, diag::err_deleted_non_function);
  14906. return;
  14907. }
  14908. // Deleted function does not have a body.
  14909. Fn->setWillHaveBody(false);
  14910. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  14911. // Don't consider the implicit declaration we generate for explicit
  14912. // specializations. FIXME: Do not generate these implicit declarations.
  14913. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  14914. Prev->getPreviousDecl()) &&
  14915. !Prev->isDefined()) {
  14916. Diag(DelLoc, diag::err_deleted_decl_not_first);
  14917. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  14918. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  14919. : diag::note_previous_declaration);
  14920. // We can't recover from this; the declaration might have already
  14921. // been used.
  14922. Fn->setInvalidDecl();
  14923. return;
  14924. }
  14925. // To maintain the invariant that functions are only deleted on their first
  14926. // declaration, mark the implicitly-instantiated declaration of the
  14927. // explicitly-specialized function as deleted instead of marking the
  14928. // instantiated redeclaration.
  14929. Fn = Fn->getCanonicalDecl();
  14930. }
  14931. // dllimport/dllexport cannot be deleted.
  14932. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  14933. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  14934. Fn->setInvalidDecl();
  14935. }
  14936. // C++11 [basic.start.main]p3:
  14937. // A program that defines main as deleted [...] is ill-formed.
  14938. if (Fn->isMain())
  14939. Diag(DelLoc, diag::err_deleted_main);
  14940. // C++11 [dcl.fct.def.delete]p4:
  14941. // A deleted function is implicitly inline.
  14942. Fn->setImplicitlyInline();
  14943. Fn->setDeletedAsWritten();
  14944. }
  14945. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  14946. if (!Dcl || Dcl->isInvalidDecl())
  14947. return;
  14948. auto *FD = dyn_cast<FunctionDecl>(Dcl);
  14949. if (!FD) {
  14950. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
  14951. if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
  14952. Diag(DefaultLoc, diag::err_defaulted_comparison_template);
  14953. return;
  14954. }
  14955. }
  14956. Diag(DefaultLoc, diag::err_default_special_members)
  14957. << getLangOpts().CPlusPlus20;
  14958. return;
  14959. }
  14960. // Reject if this can't possibly be a defaultable function.
  14961. DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
  14962. if (!DefKind &&
  14963. // A dependent function that doesn't locally look defaultable can
  14964. // still instantiate to a defaultable function if it's a constructor
  14965. // or assignment operator.
  14966. (!FD->isDependentContext() ||
  14967. (!isa<CXXConstructorDecl>(FD) &&
  14968. FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
  14969. Diag(DefaultLoc, diag::err_default_special_members)
  14970. << getLangOpts().CPlusPlus20;
  14971. return;
  14972. }
  14973. // Issue compatibility warning. We already warned if the operator is
  14974. // 'operator<=>' when parsing the '<=>' token.
  14975. if (DefKind.isComparison() &&
  14976. DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
  14977. Diag(DefaultLoc, getLangOpts().CPlusPlus20
  14978. ? diag::warn_cxx17_compat_defaulted_comparison
  14979. : diag::ext_defaulted_comparison);
  14980. }
  14981. FD->setDefaulted();
  14982. FD->setExplicitlyDefaulted();
  14983. // Defer checking functions that are defaulted in a dependent context.
  14984. if (FD->isDependentContext())
  14985. return;
  14986. // Unset that we will have a body for this function. We might not,
  14987. // if it turns out to be trivial, and we don't need this marking now
  14988. // that we've marked it as defaulted.
  14989. FD->setWillHaveBody(false);
  14990. if (DefKind.isComparison()) {
  14991. // If this comparison's defaulting occurs within the definition of its
  14992. // lexical class context, we have to do the checking when complete.
  14993. if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
  14994. if (!RD->isCompleteDefinition())
  14995. return;
  14996. }
  14997. // If this member fn was defaulted on its first declaration, we will have
  14998. // already performed the checking in CheckCompletedCXXClass. Such a
  14999. // declaration doesn't trigger an implicit definition.
  15000. if (isa<CXXMethodDecl>(FD)) {
  15001. const FunctionDecl *Primary = FD;
  15002. if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
  15003. // Ask the template instantiation pattern that actually had the
  15004. // '= default' on it.
  15005. Primary = Pattern;
  15006. if (Primary->getCanonicalDecl()->isDefaulted())
  15007. return;
  15008. }
  15009. if (DefKind.isComparison()) {
  15010. if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
  15011. FD->setInvalidDecl();
  15012. else
  15013. DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
  15014. } else {
  15015. auto *MD = cast<CXXMethodDecl>(FD);
  15016. if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
  15017. MD->setInvalidDecl();
  15018. else
  15019. DefineDefaultedFunction(*this, MD, DefaultLoc);
  15020. }
  15021. }
  15022. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  15023. for (Stmt *SubStmt : S->children()) {
  15024. if (!SubStmt)
  15025. continue;
  15026. if (isa<ReturnStmt>(SubStmt))
  15027. Self.Diag(SubStmt->getBeginLoc(),
  15028. diag::err_return_in_constructor_handler);
  15029. if (!isa<Expr>(SubStmt))
  15030. SearchForReturnInStmt(Self, SubStmt);
  15031. }
  15032. }
  15033. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  15034. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  15035. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  15036. SearchForReturnInStmt(*this, Handler);
  15037. }
  15038. }
  15039. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  15040. const CXXMethodDecl *Old) {
  15041. const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
  15042. const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
  15043. if (OldFT->hasExtParameterInfos()) {
  15044. for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
  15045. // A parameter of the overriding method should be annotated with noescape
  15046. // if the corresponding parameter of the overridden method is annotated.
  15047. if (OldFT->getExtParameterInfo(I).isNoEscape() &&
  15048. !NewFT->getExtParameterInfo(I).isNoEscape()) {
  15049. Diag(New->getParamDecl(I)->getLocation(),
  15050. diag::warn_overriding_method_missing_noescape);
  15051. Diag(Old->getParamDecl(I)->getLocation(),
  15052. diag::note_overridden_marked_noescape);
  15053. }
  15054. }
  15055. // Virtual overrides must have the same code_seg.
  15056. const auto *OldCSA = Old->getAttr<CodeSegAttr>();
  15057. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  15058. if ((NewCSA || OldCSA) &&
  15059. (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
  15060. Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
  15061. Diag(Old->getLocation(), diag::note_previous_declaration);
  15062. return true;
  15063. }
  15064. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  15065. // If the calling conventions match, everything is fine
  15066. if (NewCC == OldCC)
  15067. return false;
  15068. // If the calling conventions mismatch because the new function is static,
  15069. // suppress the calling convention mismatch error; the error about static
  15070. // function override (err_static_overrides_virtual from
  15071. // Sema::CheckFunctionDeclaration) is more clear.
  15072. if (New->getStorageClass() == SC_Static)
  15073. return false;
  15074. Diag(New->getLocation(),
  15075. diag::err_conflicting_overriding_cc_attributes)
  15076. << New->getDeclName() << New->getType() << Old->getType();
  15077. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  15078. return true;
  15079. }
  15080. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  15081. const CXXMethodDecl *Old) {
  15082. QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
  15083. QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
  15084. if (Context.hasSameType(NewTy, OldTy) ||
  15085. NewTy->isDependentType() || OldTy->isDependentType())
  15086. return false;
  15087. // Check if the return types are covariant
  15088. QualType NewClassTy, OldClassTy;
  15089. /// Both types must be pointers or references to classes.
  15090. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  15091. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  15092. NewClassTy = NewPT->getPointeeType();
  15093. OldClassTy = OldPT->getPointeeType();
  15094. }
  15095. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  15096. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  15097. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  15098. NewClassTy = NewRT->getPointeeType();
  15099. OldClassTy = OldRT->getPointeeType();
  15100. }
  15101. }
  15102. }
  15103. // The return types aren't either both pointers or references to a class type.
  15104. if (NewClassTy.isNull()) {
  15105. Diag(New->getLocation(),
  15106. diag::err_different_return_type_for_overriding_virtual_function)
  15107. << New->getDeclName() << NewTy << OldTy
  15108. << New->getReturnTypeSourceRange();
  15109. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15110. << Old->getReturnTypeSourceRange();
  15111. return true;
  15112. }
  15113. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  15114. // C++14 [class.virtual]p8:
  15115. // If the class type in the covariant return type of D::f differs from
  15116. // that of B::f, the class type in the return type of D::f shall be
  15117. // complete at the point of declaration of D::f or shall be the class
  15118. // type D.
  15119. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  15120. if (!RT->isBeingDefined() &&
  15121. RequireCompleteType(New->getLocation(), NewClassTy,
  15122. diag::err_covariant_return_incomplete,
  15123. New->getDeclName()))
  15124. return true;
  15125. }
  15126. // Check if the new class derives from the old class.
  15127. if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
  15128. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  15129. << New->getDeclName() << NewTy << OldTy
  15130. << New->getReturnTypeSourceRange();
  15131. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15132. << Old->getReturnTypeSourceRange();
  15133. return true;
  15134. }
  15135. // Check if we the conversion from derived to base is valid.
  15136. if (CheckDerivedToBaseConversion(
  15137. NewClassTy, OldClassTy,
  15138. diag::err_covariant_return_inaccessible_base,
  15139. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  15140. New->getLocation(), New->getReturnTypeSourceRange(),
  15141. New->getDeclName(), nullptr)) {
  15142. // FIXME: this note won't trigger for delayed access control
  15143. // diagnostics, and it's impossible to get an undelayed error
  15144. // here from access control during the original parse because
  15145. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  15146. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15147. << Old->getReturnTypeSourceRange();
  15148. return true;
  15149. }
  15150. }
  15151. // The qualifiers of the return types must be the same.
  15152. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  15153. Diag(New->getLocation(),
  15154. diag::err_covariant_return_type_different_qualifications)
  15155. << New->getDeclName() << NewTy << OldTy
  15156. << New->getReturnTypeSourceRange();
  15157. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15158. << Old->getReturnTypeSourceRange();
  15159. return true;
  15160. }
  15161. // The new class type must have the same or less qualifiers as the old type.
  15162. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  15163. Diag(New->getLocation(),
  15164. diag::err_covariant_return_type_class_type_more_qualified)
  15165. << New->getDeclName() << NewTy << OldTy
  15166. << New->getReturnTypeSourceRange();
  15167. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  15168. << Old->getReturnTypeSourceRange();
  15169. return true;
  15170. }
  15171. return false;
  15172. }
  15173. /// Mark the given method pure.
  15174. ///
  15175. /// \param Method the method to be marked pure.
  15176. ///
  15177. /// \param InitRange the source range that covers the "0" initializer.
  15178. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  15179. SourceLocation EndLoc = InitRange.getEnd();
  15180. if (EndLoc.isValid())
  15181. Method->setRangeEnd(EndLoc);
  15182. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  15183. Method->setPure();
  15184. return false;
  15185. }
  15186. if (!Method->isInvalidDecl())
  15187. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  15188. << Method->getDeclName() << InitRange;
  15189. return true;
  15190. }
  15191. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  15192. if (D->getFriendObjectKind())
  15193. Diag(D->getLocation(), diag::err_pure_friend);
  15194. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  15195. CheckPureMethod(M, ZeroLoc);
  15196. else
  15197. Diag(D->getLocation(), diag::err_illegal_initializer);
  15198. }
  15199. /// Determine whether the given declaration is a global variable or
  15200. /// static data member.
  15201. static bool isNonlocalVariable(const Decl *D) {
  15202. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  15203. return Var->hasGlobalStorage();
  15204. return false;
  15205. }
  15206. /// Invoked when we are about to parse an initializer for the declaration
  15207. /// 'Dcl'.
  15208. ///
  15209. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  15210. /// static data member of class X, names should be looked up in the scope of
  15211. /// class X. If the declaration had a scope specifier, a scope will have
  15212. /// been created and passed in for this purpose. Otherwise, S will be null.
  15213. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  15214. // If there is no declaration, there was an error parsing it.
  15215. if (!D || D->isInvalidDecl())
  15216. return;
  15217. // We will always have a nested name specifier here, but this declaration
  15218. // might not be out of line if the specifier names the current namespace:
  15219. // extern int n;
  15220. // int ::n = 0;
  15221. if (S && D->isOutOfLine())
  15222. EnterDeclaratorContext(S, D->getDeclContext());
  15223. // If we are parsing the initializer for a static data member, push a
  15224. // new expression evaluation context that is associated with this static
  15225. // data member.
  15226. if (isNonlocalVariable(D))
  15227. PushExpressionEvaluationContext(
  15228. ExpressionEvaluationContext::PotentiallyEvaluated, D);
  15229. }
  15230. /// Invoked after we are finished parsing an initializer for the declaration D.
  15231. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  15232. // If there is no declaration, there was an error parsing it.
  15233. if (!D || D->isInvalidDecl())
  15234. return;
  15235. if (isNonlocalVariable(D))
  15236. PopExpressionEvaluationContext();
  15237. if (S && D->isOutOfLine())
  15238. ExitDeclaratorContext(S);
  15239. }
  15240. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  15241. /// C++ if/switch/while/for statement.
  15242. /// e.g: "if (int x = f()) {...}"
  15243. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  15244. // C++ 6.4p2:
  15245. // The declarator shall not specify a function or an array.
  15246. // The type-specifier-seq shall not contain typedef and shall not declare a
  15247. // new class or enumeration.
  15248. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  15249. "Parser allowed 'typedef' as storage class of condition decl.");
  15250. Decl *Dcl = ActOnDeclarator(S, D);
  15251. if (!Dcl)
  15252. return true;
  15253. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  15254. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  15255. << D.getSourceRange();
  15256. return true;
  15257. }
  15258. return Dcl;
  15259. }
  15260. void Sema::LoadExternalVTableUses() {
  15261. if (!ExternalSource)
  15262. return;
  15263. SmallVector<ExternalVTableUse, 4> VTables;
  15264. ExternalSource->ReadUsedVTables(VTables);
  15265. SmallVector<VTableUse, 4> NewUses;
  15266. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  15267. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  15268. = VTablesUsed.find(VTables[I].Record);
  15269. // Even if a definition wasn't required before, it may be required now.
  15270. if (Pos != VTablesUsed.end()) {
  15271. if (!Pos->second && VTables[I].DefinitionRequired)
  15272. Pos->second = true;
  15273. continue;
  15274. }
  15275. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  15276. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  15277. }
  15278. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  15279. }
  15280. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  15281. bool DefinitionRequired) {
  15282. // Ignore any vtable uses in unevaluated operands or for classes that do
  15283. // not have a vtable.
  15284. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  15285. CurContext->isDependentContext() || isUnevaluatedContext())
  15286. return;
  15287. // Do not mark as used if compiling for the device outside of the target
  15288. // region.
  15289. if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  15290. !isInOpenMPDeclareTargetContext() &&
  15291. !isInOpenMPTargetExecutionDirective()) {
  15292. if (!DefinitionRequired)
  15293. MarkVirtualMembersReferenced(Loc, Class);
  15294. return;
  15295. }
  15296. // Try to insert this class into the map.
  15297. LoadExternalVTableUses();
  15298. Class = Class->getCanonicalDecl();
  15299. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  15300. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  15301. if (!Pos.second) {
  15302. // If we already had an entry, check to see if we are promoting this vtable
  15303. // to require a definition. If so, we need to reappend to the VTableUses
  15304. // list, since we may have already processed the first entry.
  15305. if (DefinitionRequired && !Pos.first->second) {
  15306. Pos.first->second = true;
  15307. } else {
  15308. // Otherwise, we can early exit.
  15309. return;
  15310. }
  15311. } else {
  15312. // The Microsoft ABI requires that we perform the destructor body
  15313. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  15314. // the deleting destructor is emitted with the vtable, not with the
  15315. // destructor definition as in the Itanium ABI.
  15316. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  15317. CXXDestructorDecl *DD = Class->getDestructor();
  15318. if (DD && DD->isVirtual() && !DD->isDeleted()) {
  15319. if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
  15320. // If this is an out-of-line declaration, marking it referenced will
  15321. // not do anything. Manually call CheckDestructor to look up operator
  15322. // delete().
  15323. ContextRAII SavedContext(*this, DD);
  15324. CheckDestructor(DD);
  15325. } else {
  15326. MarkFunctionReferenced(Loc, Class->getDestructor());
  15327. }
  15328. }
  15329. }
  15330. }
  15331. // Local classes need to have their virtual members marked
  15332. // immediately. For all other classes, we mark their virtual members
  15333. // at the end of the translation unit.
  15334. if (Class->isLocalClass())
  15335. MarkVirtualMembersReferenced(Loc, Class);
  15336. else
  15337. VTableUses.push_back(std::make_pair(Class, Loc));
  15338. }
  15339. bool Sema::DefineUsedVTables() {
  15340. LoadExternalVTableUses();
  15341. if (VTableUses.empty())
  15342. return false;
  15343. // Note: The VTableUses vector could grow as a result of marking
  15344. // the members of a class as "used", so we check the size each
  15345. // time through the loop and prefer indices (which are stable) to
  15346. // iterators (which are not).
  15347. bool DefinedAnything = false;
  15348. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  15349. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  15350. if (!Class)
  15351. continue;
  15352. TemplateSpecializationKind ClassTSK =
  15353. Class->getTemplateSpecializationKind();
  15354. SourceLocation Loc = VTableUses[I].second;
  15355. bool DefineVTable = true;
  15356. // If this class has a key function, but that key function is
  15357. // defined in another translation unit, we don't need to emit the
  15358. // vtable even though we're using it.
  15359. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  15360. if (KeyFunction && !KeyFunction->hasBody()) {
  15361. // The key function is in another translation unit.
  15362. DefineVTable = false;
  15363. TemplateSpecializationKind TSK =
  15364. KeyFunction->getTemplateSpecializationKind();
  15365. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  15366. TSK != TSK_ImplicitInstantiation &&
  15367. "Instantiations don't have key functions");
  15368. (void)TSK;
  15369. } else if (!KeyFunction) {
  15370. // If we have a class with no key function that is the subject
  15371. // of an explicit instantiation declaration, suppress the
  15372. // vtable; it will live with the explicit instantiation
  15373. // definition.
  15374. bool IsExplicitInstantiationDeclaration =
  15375. ClassTSK == TSK_ExplicitInstantiationDeclaration;
  15376. for (auto R : Class->redecls()) {
  15377. TemplateSpecializationKind TSK
  15378. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  15379. if (TSK == TSK_ExplicitInstantiationDeclaration)
  15380. IsExplicitInstantiationDeclaration = true;
  15381. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  15382. IsExplicitInstantiationDeclaration = false;
  15383. break;
  15384. }
  15385. }
  15386. if (IsExplicitInstantiationDeclaration)
  15387. DefineVTable = false;
  15388. }
  15389. // The exception specifications for all virtual members may be needed even
  15390. // if we are not providing an authoritative form of the vtable in this TU.
  15391. // We may choose to emit it available_externally anyway.
  15392. if (!DefineVTable) {
  15393. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  15394. continue;
  15395. }
  15396. // Mark all of the virtual members of this class as referenced, so
  15397. // that we can build a vtable. Then, tell the AST consumer that a
  15398. // vtable for this class is required.
  15399. DefinedAnything = true;
  15400. MarkVirtualMembersReferenced(Loc, Class);
  15401. CXXRecordDecl *Canonical = Class->getCanonicalDecl();
  15402. if (VTablesUsed[Canonical])
  15403. Consumer.HandleVTable(Class);
  15404. // Warn if we're emitting a weak vtable. The vtable will be weak if there is
  15405. // no key function or the key function is inlined. Don't warn in C++ ABIs
  15406. // that lack key functions, since the user won't be able to make one.
  15407. if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
  15408. Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
  15409. ClassTSK != TSK_ExplicitInstantiationDefinition) {
  15410. const FunctionDecl *KeyFunctionDef = nullptr;
  15411. if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
  15412. KeyFunctionDef->isInlined()))
  15413. Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
  15414. }
  15415. }
  15416. VTableUses.clear();
  15417. return DefinedAnything;
  15418. }
  15419. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  15420. const CXXRecordDecl *RD) {
  15421. for (const auto *I : RD->methods())
  15422. if (I->isVirtual() && !I->isPure())
  15423. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  15424. }
  15425. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  15426. const CXXRecordDecl *RD,
  15427. bool ConstexprOnly) {
  15428. // Mark all functions which will appear in RD's vtable as used.
  15429. CXXFinalOverriderMap FinalOverriders;
  15430. RD->getFinalOverriders(FinalOverriders);
  15431. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  15432. E = FinalOverriders.end();
  15433. I != E; ++I) {
  15434. for (OverridingMethods::const_iterator OI = I->second.begin(),
  15435. OE = I->second.end();
  15436. OI != OE; ++OI) {
  15437. assert(OI->second.size() > 0 && "no final overrider");
  15438. CXXMethodDecl *Overrider = OI->second.front().Method;
  15439. // C++ [basic.def.odr]p2:
  15440. // [...] A virtual member function is used if it is not pure. [...]
  15441. if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
  15442. MarkFunctionReferenced(Loc, Overrider);
  15443. }
  15444. }
  15445. // Only classes that have virtual bases need a VTT.
  15446. if (RD->getNumVBases() == 0)
  15447. return;
  15448. for (const auto &I : RD->bases()) {
  15449. const auto *Base =
  15450. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  15451. if (Base->getNumVBases() == 0)
  15452. continue;
  15453. MarkVirtualMembersReferenced(Loc, Base);
  15454. }
  15455. }
  15456. /// SetIvarInitializers - This routine builds initialization ASTs for the
  15457. /// Objective-C implementation whose ivars need be initialized.
  15458. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  15459. if (!getLangOpts().CPlusPlus)
  15460. return;
  15461. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  15462. SmallVector<ObjCIvarDecl*, 8> ivars;
  15463. CollectIvarsToConstructOrDestruct(OID, ivars);
  15464. if (ivars.empty())
  15465. return;
  15466. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  15467. for (unsigned i = 0; i < ivars.size(); i++) {
  15468. FieldDecl *Field = ivars[i];
  15469. if (Field->isInvalidDecl())
  15470. continue;
  15471. CXXCtorInitializer *Member;
  15472. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  15473. InitializationKind InitKind =
  15474. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  15475. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  15476. ExprResult MemberInit =
  15477. InitSeq.Perform(*this, InitEntity, InitKind, None);
  15478. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  15479. // Note, MemberInit could actually come back empty if no initialization
  15480. // is required (e.g., because it would call a trivial default constructor)
  15481. if (!MemberInit.get() || MemberInit.isInvalid())
  15482. continue;
  15483. Member =
  15484. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  15485. SourceLocation(),
  15486. MemberInit.getAs<Expr>(),
  15487. SourceLocation());
  15488. AllToInit.push_back(Member);
  15489. // Be sure that the destructor is accessible and is marked as referenced.
  15490. if (const RecordType *RecordTy =
  15491. Context.getBaseElementType(Field->getType())
  15492. ->getAs<RecordType>()) {
  15493. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  15494. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  15495. MarkFunctionReferenced(Field->getLocation(), Destructor);
  15496. CheckDestructorAccess(Field->getLocation(), Destructor,
  15497. PDiag(diag::err_access_dtor_ivar)
  15498. << Context.getBaseElementType(Field->getType()));
  15499. }
  15500. }
  15501. }
  15502. ObjCImplementation->setIvarInitializers(Context,
  15503. AllToInit.data(), AllToInit.size());
  15504. }
  15505. }
  15506. static
  15507. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  15508. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
  15509. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
  15510. llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
  15511. Sema &S) {
  15512. if (Ctor->isInvalidDecl())
  15513. return;
  15514. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  15515. // Target may not be determinable yet, for instance if this is a dependent
  15516. // call in an uninstantiated template.
  15517. if (Target) {
  15518. const FunctionDecl *FNTarget = nullptr;
  15519. (void)Target->hasBody(FNTarget);
  15520. Target = const_cast<CXXConstructorDecl*>(
  15521. cast_or_null<CXXConstructorDecl>(FNTarget));
  15522. }
  15523. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  15524. // Avoid dereferencing a null pointer here.
  15525. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  15526. if (!Current.insert(Canonical).second)
  15527. return;
  15528. // We know that beyond here, we aren't chaining into a cycle.
  15529. if (!Target || !Target->isDelegatingConstructor() ||
  15530. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  15531. Valid.insert(Current.begin(), Current.end());
  15532. Current.clear();
  15533. // We've hit a cycle.
  15534. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  15535. Current.count(TCanonical)) {
  15536. // If we haven't diagnosed this cycle yet, do so now.
  15537. if (!Invalid.count(TCanonical)) {
  15538. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  15539. diag::warn_delegating_ctor_cycle)
  15540. << Ctor;
  15541. // Don't add a note for a function delegating directly to itself.
  15542. if (TCanonical != Canonical)
  15543. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  15544. CXXConstructorDecl *C = Target;
  15545. while (C->getCanonicalDecl() != Canonical) {
  15546. const FunctionDecl *FNTarget = nullptr;
  15547. (void)C->getTargetConstructor()->hasBody(FNTarget);
  15548. assert(FNTarget && "Ctor cycle through bodiless function");
  15549. C = const_cast<CXXConstructorDecl*>(
  15550. cast<CXXConstructorDecl>(FNTarget));
  15551. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  15552. }
  15553. }
  15554. Invalid.insert(Current.begin(), Current.end());
  15555. Current.clear();
  15556. } else {
  15557. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  15558. }
  15559. }
  15560. void Sema::CheckDelegatingCtorCycles() {
  15561. llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  15562. for (DelegatingCtorDeclsType::iterator
  15563. I = DelegatingCtorDecls.begin(ExternalSource),
  15564. E = DelegatingCtorDecls.end();
  15565. I != E; ++I)
  15566. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  15567. for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  15568. (*CI)->setInvalidDecl();
  15569. }
  15570. namespace {
  15571. /// AST visitor that finds references to the 'this' expression.
  15572. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  15573. Sema &S;
  15574. public:
  15575. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  15576. bool VisitCXXThisExpr(CXXThisExpr *E) {
  15577. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  15578. << E->isImplicit();
  15579. return false;
  15580. }
  15581. };
  15582. }
  15583. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  15584. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  15585. if (!TSInfo)
  15586. return false;
  15587. TypeLoc TL = TSInfo->getTypeLoc();
  15588. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  15589. if (!ProtoTL)
  15590. return false;
  15591. // C++11 [expr.prim.general]p3:
  15592. // [The expression this] shall not appear before the optional
  15593. // cv-qualifier-seq and it shall not appear within the declaration of a
  15594. // static member function (although its type and value category are defined
  15595. // within a static member function as they are within a non-static member
  15596. // function). [ Note: this is because declaration matching does not occur
  15597. // until the complete declarator is known. - end note ]
  15598. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  15599. FindCXXThisExpr Finder(*this);
  15600. // If the return type came after the cv-qualifier-seq, check it now.
  15601. if (Proto->hasTrailingReturn() &&
  15602. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  15603. return true;
  15604. // Check the exception specification.
  15605. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  15606. return true;
  15607. // Check the trailing requires clause
  15608. if (Expr *E = Method->getTrailingRequiresClause())
  15609. if (!Finder.TraverseStmt(E))
  15610. return true;
  15611. return checkThisInStaticMemberFunctionAttributes(Method);
  15612. }
  15613. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  15614. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  15615. if (!TSInfo)
  15616. return false;
  15617. TypeLoc TL = TSInfo->getTypeLoc();
  15618. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  15619. if (!ProtoTL)
  15620. return false;
  15621. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  15622. FindCXXThisExpr Finder(*this);
  15623. switch (Proto->getExceptionSpecType()) {
  15624. case EST_Unparsed:
  15625. case EST_Uninstantiated:
  15626. case EST_Unevaluated:
  15627. case EST_BasicNoexcept:
  15628. case EST_NoThrow:
  15629. case EST_DynamicNone:
  15630. case EST_MSAny:
  15631. case EST_None:
  15632. break;
  15633. case EST_DependentNoexcept:
  15634. case EST_NoexceptFalse:
  15635. case EST_NoexceptTrue:
  15636. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  15637. return true;
  15638. LLVM_FALLTHROUGH;
  15639. case EST_Dynamic:
  15640. for (const auto &E : Proto->exceptions()) {
  15641. if (!Finder.TraverseType(E))
  15642. return true;
  15643. }
  15644. break;
  15645. }
  15646. return false;
  15647. }
  15648. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  15649. FindCXXThisExpr Finder(*this);
  15650. // Check attributes.
  15651. for (const auto *A : Method->attrs()) {
  15652. // FIXME: This should be emitted by tblgen.
  15653. Expr *Arg = nullptr;
  15654. ArrayRef<Expr *> Args;
  15655. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  15656. Arg = G->getArg();
  15657. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  15658. Arg = G->getArg();
  15659. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  15660. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  15661. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  15662. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  15663. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  15664. Arg = ETLF->getSuccessValue();
  15665. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  15666. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  15667. Arg = STLF->getSuccessValue();
  15668. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  15669. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  15670. Arg = LR->getArg();
  15671. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  15672. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  15673. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  15674. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  15675. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  15676. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  15677. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  15678. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  15679. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  15680. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  15681. if (Arg && !Finder.TraverseStmt(Arg))
  15682. return true;
  15683. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  15684. if (!Finder.TraverseStmt(Args[I]))
  15685. return true;
  15686. }
  15687. }
  15688. return false;
  15689. }
  15690. void Sema::checkExceptionSpecification(
  15691. bool IsTopLevel, ExceptionSpecificationType EST,
  15692. ArrayRef<ParsedType> DynamicExceptions,
  15693. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  15694. SmallVectorImpl<QualType> &Exceptions,
  15695. FunctionProtoType::ExceptionSpecInfo &ESI) {
  15696. Exceptions.clear();
  15697. ESI.Type = EST;
  15698. if (EST == EST_Dynamic) {
  15699. Exceptions.reserve(DynamicExceptions.size());
  15700. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  15701. // FIXME: Preserve type source info.
  15702. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  15703. if (IsTopLevel) {
  15704. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  15705. collectUnexpandedParameterPacks(ET, Unexpanded);
  15706. if (!Unexpanded.empty()) {
  15707. DiagnoseUnexpandedParameterPacks(
  15708. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  15709. Unexpanded);
  15710. continue;
  15711. }
  15712. }
  15713. // Check that the type is valid for an exception spec, and
  15714. // drop it if not.
  15715. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  15716. Exceptions.push_back(ET);
  15717. }
  15718. ESI.Exceptions = Exceptions;
  15719. return;
  15720. }
  15721. if (isComputedNoexcept(EST)) {
  15722. assert((NoexceptExpr->isTypeDependent() ||
  15723. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  15724. Context.BoolTy) &&
  15725. "Parser should have made sure that the expression is boolean");
  15726. if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  15727. ESI.Type = EST_BasicNoexcept;
  15728. return;
  15729. }
  15730. ESI.NoexceptExpr = NoexceptExpr;
  15731. return;
  15732. }
  15733. }
  15734. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  15735. ExceptionSpecificationType EST,
  15736. SourceRange SpecificationRange,
  15737. ArrayRef<ParsedType> DynamicExceptions,
  15738. ArrayRef<SourceRange> DynamicExceptionRanges,
  15739. Expr *NoexceptExpr) {
  15740. if (!MethodD)
  15741. return;
  15742. // Dig out the method we're referring to.
  15743. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  15744. MethodD = FunTmpl->getTemplatedDecl();
  15745. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  15746. if (!Method)
  15747. return;
  15748. // Check the exception specification.
  15749. llvm::SmallVector<QualType, 4> Exceptions;
  15750. FunctionProtoType::ExceptionSpecInfo ESI;
  15751. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  15752. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  15753. ESI);
  15754. // Update the exception specification on the function type.
  15755. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  15756. if (Method->isStatic())
  15757. checkThisInStaticMemberFunctionExceptionSpec(Method);
  15758. if (Method->isVirtual()) {
  15759. // Check overrides, which we previously had to delay.
  15760. for (const CXXMethodDecl *O : Method->overridden_methods())
  15761. CheckOverridingFunctionExceptionSpec(Method, O);
  15762. }
  15763. }
  15764. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  15765. ///
  15766. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  15767. SourceLocation DeclStart, Declarator &D,
  15768. Expr *BitWidth,
  15769. InClassInitStyle InitStyle,
  15770. AccessSpecifier AS,
  15771. const ParsedAttr &MSPropertyAttr) {
  15772. IdentifierInfo *II = D.getIdentifier();
  15773. if (!II) {
  15774. Diag(DeclStart, diag::err_anonymous_property);
  15775. return nullptr;
  15776. }
  15777. SourceLocation Loc = D.getIdentifierLoc();
  15778. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  15779. QualType T = TInfo->getType();
  15780. if (getLangOpts().CPlusPlus) {
  15781. CheckExtraCXXDefaultArguments(D);
  15782. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  15783. UPPC_DataMemberType)) {
  15784. D.setInvalidType();
  15785. T = Context.IntTy;
  15786. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  15787. }
  15788. }
  15789. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  15790. if (D.getDeclSpec().isInlineSpecified())
  15791. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  15792. << getLangOpts().CPlusPlus17;
  15793. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  15794. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  15795. diag::err_invalid_thread)
  15796. << DeclSpec::getSpecifierName(TSCS);
  15797. // Check to see if this name was declared as a member previously
  15798. NamedDecl *PrevDecl = nullptr;
  15799. LookupResult Previous(*this, II, Loc, LookupMemberName,
  15800. ForVisibleRedeclaration);
  15801. LookupName(Previous, S);
  15802. switch (Previous.getResultKind()) {
  15803. case LookupResult::Found:
  15804. case LookupResult::FoundUnresolvedValue:
  15805. PrevDecl = Previous.getAsSingle<NamedDecl>();
  15806. break;
  15807. case LookupResult::FoundOverloaded:
  15808. PrevDecl = Previous.getRepresentativeDecl();
  15809. break;
  15810. case LookupResult::NotFound:
  15811. case LookupResult::NotFoundInCurrentInstantiation:
  15812. case LookupResult::Ambiguous:
  15813. break;
  15814. }
  15815. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  15816. // Maybe we will complain about the shadowed template parameter.
  15817. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  15818. // Just pretend that we didn't see the previous declaration.
  15819. PrevDecl = nullptr;
  15820. }
  15821. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  15822. PrevDecl = nullptr;
  15823. SourceLocation TSSL = D.getBeginLoc();
  15824. MSPropertyDecl *NewPD =
  15825. MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
  15826. MSPropertyAttr.getPropertyDataGetter(),
  15827. MSPropertyAttr.getPropertyDataSetter());
  15828. ProcessDeclAttributes(TUScope, NewPD, D);
  15829. NewPD->setAccess(AS);
  15830. if (NewPD->isInvalidDecl())
  15831. Record->setInvalidDecl();
  15832. if (D.getDeclSpec().isModulePrivateSpecified())
  15833. NewPD->setModulePrivate();
  15834. if (NewPD->isInvalidDecl() && PrevDecl) {
  15835. // Don't introduce NewFD into scope; there's already something
  15836. // with the same name in the same scope.
  15837. } else if (II) {
  15838. PushOnScopeChains(NewPD, S);
  15839. } else
  15840. Record->addDecl(NewPD);
  15841. return NewPD;
  15842. }
  15843. void Sema::ActOnStartFunctionDeclarationDeclarator(
  15844. Declarator &Declarator, unsigned TemplateParameterDepth) {
  15845. auto &Info = InventedParameterInfos.emplace_back();
  15846. TemplateParameterList *ExplicitParams = nullptr;
  15847. ArrayRef<TemplateParameterList *> ExplicitLists =
  15848. Declarator.getTemplateParameterLists();
  15849. if (!ExplicitLists.empty()) {
  15850. bool IsMemberSpecialization, IsInvalid;
  15851. ExplicitParams = MatchTemplateParametersToScopeSpecifier(
  15852. Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
  15853. Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
  15854. ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
  15855. /*SuppressDiagnostic=*/true);
  15856. }
  15857. if (ExplicitParams) {
  15858. Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
  15859. for (NamedDecl *Param : *ExplicitParams)
  15860. Info.TemplateParams.push_back(Param);
  15861. Info.NumExplicitTemplateParams = ExplicitParams->size();
  15862. } else {
  15863. Info.AutoTemplateParameterDepth = TemplateParameterDepth;
  15864. Info.NumExplicitTemplateParams = 0;
  15865. }
  15866. }
  15867. void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
  15868. auto &FSI = InventedParameterInfos.back();
  15869. if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
  15870. if (FSI.NumExplicitTemplateParams != 0) {
  15871. TemplateParameterList *ExplicitParams =
  15872. Declarator.getTemplateParameterLists().back();
  15873. Declarator.setInventedTemplateParameterList(
  15874. TemplateParameterList::Create(
  15875. Context, ExplicitParams->getTemplateLoc(),
  15876. ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
  15877. ExplicitParams->getRAngleLoc(),
  15878. ExplicitParams->getRequiresClause()));
  15879. } else {
  15880. Declarator.setInventedTemplateParameterList(
  15881. TemplateParameterList::Create(
  15882. Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
  15883. SourceLocation(), /*RequiresClause=*/nullptr));
  15884. }
  15885. }
  15886. InventedParameterInfos.pop_back();
  15887. }