SemaDeclCXX.cpp 427 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121
  1. //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for C++ declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/Sema/CXXFieldCollector.h"
  15. #include "clang/Sema/Scope.h"
  16. #include "clang/Sema/Initialization.h"
  17. #include "clang/Sema/Lookup.h"
  18. #include "clang/AST/ASTConsumer.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/ASTMutationListener.h"
  21. #include "clang/AST/CharUnits.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/DeclVisitor.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/RecordLayout.h"
  26. #include "clang/AST/StmtVisitor.h"
  27. #include "clang/AST/TypeLoc.h"
  28. #include "clang/AST/TypeOrdering.h"
  29. #include "clang/Sema/DeclSpec.h"
  30. #include "clang/Sema/ParsedTemplate.h"
  31. #include "clang/Basic/PartialDiagnostic.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "llvm/ADT/DenseSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include <map>
  37. #include <set>
  38. using namespace clang;
  39. //===----------------------------------------------------------------------===//
  40. // CheckDefaultArgumentVisitor
  41. //===----------------------------------------------------------------------===//
  42. namespace {
  43. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  44. /// the default argument of a parameter to determine whether it
  45. /// contains any ill-formed subexpressions. For example, this will
  46. /// diagnose the use of local variables or parameters within the
  47. /// default argument expression.
  48. class CheckDefaultArgumentVisitor
  49. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  50. Expr *DefaultArg;
  51. Sema *S;
  52. public:
  53. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  54. : DefaultArg(defarg), S(s) {}
  55. bool VisitExpr(Expr *Node);
  56. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  57. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  58. };
  59. /// VisitExpr - Visit all of the children of this expression.
  60. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  61. bool IsInvalid = false;
  62. for (Stmt::child_range I = Node->children(); I; ++I)
  63. IsInvalid |= Visit(*I);
  64. return IsInvalid;
  65. }
  66. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  67. /// determine whether this declaration can be used in the default
  68. /// argument expression.
  69. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  70. NamedDecl *Decl = DRE->getDecl();
  71. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  72. // C++ [dcl.fct.default]p9
  73. // Default arguments are evaluated each time the function is
  74. // called. The order of evaluation of function arguments is
  75. // unspecified. Consequently, parameters of a function shall not
  76. // be used in default argument expressions, even if they are not
  77. // evaluated. Parameters of a function declared before a default
  78. // argument expression are in scope and can hide namespace and
  79. // class member names.
  80. return S->Diag(DRE->getSourceRange().getBegin(),
  81. diag::err_param_default_argument_references_param)
  82. << Param->getDeclName() << DefaultArg->getSourceRange();
  83. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  84. // C++ [dcl.fct.default]p7
  85. // Local variables shall not be used in default argument
  86. // expressions.
  87. if (VDecl->isLocalVarDecl())
  88. return S->Diag(DRE->getSourceRange().getBegin(),
  89. diag::err_param_default_argument_references_local)
  90. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  91. }
  92. return false;
  93. }
  94. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  95. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  96. // C++ [dcl.fct.default]p8:
  97. // The keyword this shall not be used in a default argument of a
  98. // member function.
  99. return S->Diag(ThisE->getSourceRange().getBegin(),
  100. diag::err_param_default_argument_references_this)
  101. << ThisE->getSourceRange();
  102. }
  103. }
  104. void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
  105. assert(Context && "ImplicitExceptionSpecification without an ASTContext");
  106. // If we have an MSAny or unknown spec already, don't bother.
  107. if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
  108. return;
  109. const FunctionProtoType *Proto
  110. = Method->getType()->getAs<FunctionProtoType>();
  111. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  112. // If this function can throw any exceptions, make a note of that.
  113. if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
  114. ClearExceptions();
  115. ComputedEST = EST;
  116. return;
  117. }
  118. // FIXME: If the call to this decl is using any of its default arguments, we
  119. // need to search them for potentially-throwing calls.
  120. // If this function has a basic noexcept, it doesn't affect the outcome.
  121. if (EST == EST_BasicNoexcept)
  122. return;
  123. // If we have a throw-all spec at this point, ignore the function.
  124. if (ComputedEST == EST_None)
  125. return;
  126. // If we're still at noexcept(true) and there's a nothrow() callee,
  127. // change to that specification.
  128. if (EST == EST_DynamicNone) {
  129. if (ComputedEST == EST_BasicNoexcept)
  130. ComputedEST = EST_DynamicNone;
  131. return;
  132. }
  133. // Check out noexcept specs.
  134. if (EST == EST_ComputedNoexcept) {
  135. FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
  136. assert(NR != FunctionProtoType::NR_NoNoexcept &&
  137. "Must have noexcept result for EST_ComputedNoexcept.");
  138. assert(NR != FunctionProtoType::NR_Dependent &&
  139. "Should not generate implicit declarations for dependent cases, "
  140. "and don't know how to handle them anyway.");
  141. // noexcept(false) -> no spec on the new function
  142. if (NR == FunctionProtoType::NR_Throw) {
  143. ClearExceptions();
  144. ComputedEST = EST_None;
  145. }
  146. // noexcept(true) won't change anything either.
  147. return;
  148. }
  149. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  150. assert(ComputedEST != EST_None &&
  151. "Shouldn't collect exceptions when throw-all is guaranteed.");
  152. ComputedEST = EST_Dynamic;
  153. // Record the exceptions in this function's exception specification.
  154. for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
  155. EEnd = Proto->exception_end();
  156. E != EEnd; ++E)
  157. if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
  158. Exceptions.push_back(*E);
  159. }
  160. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  161. if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
  162. return;
  163. // FIXME:
  164. //
  165. // C++0x [except.spec]p14:
  166. // [An] implicit exception-specification specifies the type-id T if and
  167. // only if T is allowed by the exception-specification of a function directly
  168. // invoked by f's implicit definition; f shall allow all exceptions if any
  169. // function it directly invokes allows all exceptions, and f shall allow no
  170. // exceptions if every function it directly invokes allows no exceptions.
  171. //
  172. // Note in particular that if an implicit exception-specification is generated
  173. // for a function containing a throw-expression, that specification can still
  174. // be noexcept(true).
  175. //
  176. // Note also that 'directly invoked' is not defined in the standard, and there
  177. // is no indication that we should only consider potentially-evaluated calls.
  178. //
  179. // Ultimately we should implement the intent of the standard: the exception
  180. // specification should be the set of exceptions which can be thrown by the
  181. // implicit definition. For now, we assume that any non-nothrow expression can
  182. // throw any exception.
  183. if (E->CanThrow(*Context))
  184. ComputedEST = EST_None;
  185. }
  186. bool
  187. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  188. SourceLocation EqualLoc) {
  189. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  190. diag::err_typecheck_decl_incomplete_type)) {
  191. Param->setInvalidDecl();
  192. return true;
  193. }
  194. // C++ [dcl.fct.default]p5
  195. // A default argument expression is implicitly converted (clause
  196. // 4) to the parameter type. The default argument expression has
  197. // the same semantic constraints as the initializer expression in
  198. // a declaration of a variable of the parameter type, using the
  199. // copy-initialization semantics (8.5).
  200. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  201. Param);
  202. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  203. EqualLoc);
  204. InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
  205. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  206. MultiExprArg(*this, &Arg, 1));
  207. if (Result.isInvalid())
  208. return true;
  209. Arg = Result.takeAs<Expr>();
  210. CheckImplicitConversions(Arg, EqualLoc);
  211. Arg = MaybeCreateExprWithCleanups(Arg);
  212. // Okay: add the default argument to the parameter
  213. Param->setDefaultArg(Arg);
  214. // We have already instantiated this parameter; provide each of the
  215. // instantiations with the uninstantiated default argument.
  216. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  217. = UnparsedDefaultArgInstantiations.find(Param);
  218. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  219. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  220. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  221. // We're done tracking this parameter's instantiations.
  222. UnparsedDefaultArgInstantiations.erase(InstPos);
  223. }
  224. return false;
  225. }
  226. /// ActOnParamDefaultArgument - Check whether the default argument
  227. /// provided for a function parameter is well-formed. If so, attach it
  228. /// to the parameter declaration.
  229. void
  230. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  231. Expr *DefaultArg) {
  232. if (!param || !DefaultArg)
  233. return;
  234. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  235. UnparsedDefaultArgLocs.erase(Param);
  236. // Default arguments are only permitted in C++
  237. if (!getLangOptions().CPlusPlus) {
  238. Diag(EqualLoc, diag::err_param_default_argument)
  239. << DefaultArg->getSourceRange();
  240. Param->setInvalidDecl();
  241. return;
  242. }
  243. // Check for unexpanded parameter packs.
  244. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  245. Param->setInvalidDecl();
  246. return;
  247. }
  248. // Check that the default argument is well-formed
  249. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  250. if (DefaultArgChecker.Visit(DefaultArg)) {
  251. Param->setInvalidDecl();
  252. return;
  253. }
  254. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  255. }
  256. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  257. /// argument for a function parameter, but we can't parse it yet
  258. /// because we're inside a class definition. Note that this default
  259. /// argument will be parsed later.
  260. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  261. SourceLocation EqualLoc,
  262. SourceLocation ArgLoc) {
  263. if (!param)
  264. return;
  265. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  266. if (Param)
  267. Param->setUnparsedDefaultArg();
  268. UnparsedDefaultArgLocs[Param] = ArgLoc;
  269. }
  270. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  271. /// the default argument for the parameter param failed.
  272. void Sema::ActOnParamDefaultArgumentError(Decl *param) {
  273. if (!param)
  274. return;
  275. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  276. Param->setInvalidDecl();
  277. UnparsedDefaultArgLocs.erase(Param);
  278. }
  279. /// CheckExtraCXXDefaultArguments - Check for any extra default
  280. /// arguments in the declarator, which is not a function declaration
  281. /// or definition and therefore is not permitted to have default
  282. /// arguments. This routine should be invoked for every declarator
  283. /// that is not a function declaration or definition.
  284. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  285. // C++ [dcl.fct.default]p3
  286. // A default argument expression shall be specified only in the
  287. // parameter-declaration-clause of a function declaration or in a
  288. // template-parameter (14.1). It shall not be specified for a
  289. // parameter pack. If it is specified in a
  290. // parameter-declaration-clause, it shall not occur within a
  291. // declarator or abstract-declarator of a parameter-declaration.
  292. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  293. DeclaratorChunk &chunk = D.getTypeObject(i);
  294. if (chunk.Kind == DeclaratorChunk::Function) {
  295. for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
  296. ParmVarDecl *Param =
  297. cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
  298. if (Param->hasUnparsedDefaultArg()) {
  299. CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
  300. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  301. << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
  302. delete Toks;
  303. chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
  304. } else if (Param->getDefaultArg()) {
  305. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  306. << Param->getDefaultArg()->getSourceRange();
  307. Param->setDefaultArg(0);
  308. }
  309. }
  310. }
  311. }
  312. }
  313. // MergeCXXFunctionDecl - Merge two declarations of the same C++
  314. // function, once we already know that they have the same
  315. // type. Subroutine of MergeFunctionDecl. Returns true if there was an
  316. // error, false otherwise.
  317. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
  318. bool Invalid = false;
  319. // C++ [dcl.fct.default]p4:
  320. // For non-template functions, default arguments can be added in
  321. // later declarations of a function in the same
  322. // scope. Declarations in different scopes have completely
  323. // distinct sets of default arguments. That is, declarations in
  324. // inner scopes do not acquire default arguments from
  325. // declarations in outer scopes, and vice versa. In a given
  326. // function declaration, all parameters subsequent to a
  327. // parameter with a default argument shall have default
  328. // arguments supplied in this or previous declarations. A
  329. // default argument shall not be redefined by a later
  330. // declaration (not even to the same value).
  331. //
  332. // C++ [dcl.fct.default]p6:
  333. // Except for member functions of class templates, the default arguments
  334. // in a member function definition that appears outside of the class
  335. // definition are added to the set of default arguments provided by the
  336. // member function declaration in the class definition.
  337. for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
  338. ParmVarDecl *OldParam = Old->getParamDecl(p);
  339. ParmVarDecl *NewParam = New->getParamDecl(p);
  340. if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
  341. unsigned DiagDefaultParamID =
  342. diag::err_param_default_argument_redefinition;
  343. // MSVC accepts that default parameters be redefined for member functions
  344. // of template class. The new default parameter's value is ignored.
  345. Invalid = true;
  346. if (getLangOptions().MicrosoftExt) {
  347. CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
  348. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  349. // Merge the old default argument into the new parameter.
  350. NewParam->setHasInheritedDefaultArg();
  351. if (OldParam->hasUninstantiatedDefaultArg())
  352. NewParam->setUninstantiatedDefaultArg(
  353. OldParam->getUninstantiatedDefaultArg());
  354. else
  355. NewParam->setDefaultArg(OldParam->getInit());
  356. DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
  357. Invalid = false;
  358. }
  359. }
  360. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  361. // hint here. Alternatively, we could walk the type-source information
  362. // for NewParam to find the last source location in the type... but it
  363. // isn't worth the effort right now. This is the kind of test case that
  364. // is hard to get right:
  365. // int f(int);
  366. // void g(int (*fp)(int) = f);
  367. // void g(int (*fp)(int) = &f);
  368. Diag(NewParam->getLocation(), DiagDefaultParamID)
  369. << NewParam->getDefaultArgRange();
  370. // Look for the function declaration where the default argument was
  371. // actually written, which may be a declaration prior to Old.
  372. for (FunctionDecl *Older = Old->getPreviousDecl();
  373. Older; Older = Older->getPreviousDecl()) {
  374. if (!Older->getParamDecl(p)->hasDefaultArg())
  375. break;
  376. OldParam = Older->getParamDecl(p);
  377. }
  378. Diag(OldParam->getLocation(), diag::note_previous_definition)
  379. << OldParam->getDefaultArgRange();
  380. } else if (OldParam->hasDefaultArg()) {
  381. // Merge the old default argument into the new parameter.
  382. // It's important to use getInit() here; getDefaultArg()
  383. // strips off any top-level ExprWithCleanups.
  384. NewParam->setHasInheritedDefaultArg();
  385. if (OldParam->hasUninstantiatedDefaultArg())
  386. NewParam->setUninstantiatedDefaultArg(
  387. OldParam->getUninstantiatedDefaultArg());
  388. else
  389. NewParam->setDefaultArg(OldParam->getInit());
  390. } else if (NewParam->hasDefaultArg()) {
  391. if (New->getDescribedFunctionTemplate()) {
  392. // Paragraph 4, quoted above, only applies to non-template functions.
  393. Diag(NewParam->getLocation(),
  394. diag::err_param_default_argument_template_redecl)
  395. << NewParam->getDefaultArgRange();
  396. Diag(Old->getLocation(), diag::note_template_prev_declaration)
  397. << false;
  398. } else if (New->getTemplateSpecializationKind()
  399. != TSK_ImplicitInstantiation &&
  400. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  401. // C++ [temp.expr.spec]p21:
  402. // Default function arguments shall not be specified in a declaration
  403. // or a definition for one of the following explicit specializations:
  404. // - the explicit specialization of a function template;
  405. // - the explicit specialization of a member function template;
  406. // - the explicit specialization of a member function of a class
  407. // template where the class template specialization to which the
  408. // member function specialization belongs is implicitly
  409. // instantiated.
  410. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  411. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  412. << New->getDeclName()
  413. << NewParam->getDefaultArgRange();
  414. } else if (New->getDeclContext()->isDependentContext()) {
  415. // C++ [dcl.fct.default]p6 (DR217):
  416. // Default arguments for a member function of a class template shall
  417. // be specified on the initial declaration of the member function
  418. // within the class template.
  419. //
  420. // Reading the tea leaves a bit in DR217 and its reference to DR205
  421. // leads me to the conclusion that one cannot add default function
  422. // arguments for an out-of-line definition of a member function of a
  423. // dependent type.
  424. int WhichKind = 2;
  425. if (CXXRecordDecl *Record
  426. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  427. if (Record->getDescribedClassTemplate())
  428. WhichKind = 0;
  429. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  430. WhichKind = 1;
  431. else
  432. WhichKind = 2;
  433. }
  434. Diag(NewParam->getLocation(),
  435. diag::err_param_default_argument_member_template_redecl)
  436. << WhichKind
  437. << NewParam->getDefaultArgRange();
  438. } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
  439. CXXSpecialMember NewSM = getSpecialMember(Ctor),
  440. OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
  441. if (NewSM != OldSM) {
  442. Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
  443. << NewParam->getDefaultArgRange() << NewSM;
  444. Diag(Old->getLocation(), diag::note_previous_declaration_special)
  445. << OldSM;
  446. }
  447. }
  448. }
  449. }
  450. // C++0x [dcl.constexpr]p1: If any declaration of a function or function
  451. // template has a constexpr specifier then all its declarations shall
  452. // contain the constexpr specifier. [Note: An explicit specialization can
  453. // differ from the template declaration with respect to the constexpr
  454. // specifier. -- end note]
  455. //
  456. // FIXME: Don't reject changes in constexpr in explicit specializations.
  457. if (New->isConstexpr() != Old->isConstexpr()) {
  458. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  459. << New << New->isConstexpr();
  460. Diag(Old->getLocation(), diag::note_previous_declaration);
  461. Invalid = true;
  462. }
  463. if (CheckEquivalentExceptionSpec(Old, New))
  464. Invalid = true;
  465. return Invalid;
  466. }
  467. /// \brief Merge the exception specifications of two variable declarations.
  468. ///
  469. /// This is called when there's a redeclaration of a VarDecl. The function
  470. /// checks if the redeclaration might have an exception specification and
  471. /// validates compatibility and merges the specs if necessary.
  472. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  473. // Shortcut if exceptions are disabled.
  474. if (!getLangOptions().CXXExceptions)
  475. return;
  476. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  477. "Should only be called if types are otherwise the same.");
  478. QualType NewType = New->getType();
  479. QualType OldType = Old->getType();
  480. // We're only interested in pointers and references to functions, as well
  481. // as pointers to member functions.
  482. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  483. NewType = R->getPointeeType();
  484. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  485. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  486. NewType = P->getPointeeType();
  487. OldType = OldType->getAs<PointerType>()->getPointeeType();
  488. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  489. NewType = M->getPointeeType();
  490. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  491. }
  492. if (!NewType->isFunctionProtoType())
  493. return;
  494. // There's lots of special cases for functions. For function pointers, system
  495. // libraries are hopefully not as broken so that we don't need these
  496. // workarounds.
  497. if (CheckEquivalentExceptionSpec(
  498. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  499. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  500. New->setInvalidDecl();
  501. }
  502. }
  503. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  504. /// function declaration are well-formed according to C++
  505. /// [dcl.fct.default].
  506. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  507. unsigned NumParams = FD->getNumParams();
  508. unsigned p;
  509. // Find first parameter with a default argument
  510. for (p = 0; p < NumParams; ++p) {
  511. ParmVarDecl *Param = FD->getParamDecl(p);
  512. if (Param->hasDefaultArg())
  513. break;
  514. }
  515. // C++ [dcl.fct.default]p4:
  516. // In a given function declaration, all parameters
  517. // subsequent to a parameter with a default argument shall
  518. // have default arguments supplied in this or previous
  519. // declarations. A default argument shall not be redefined
  520. // by a later declaration (not even to the same value).
  521. unsigned LastMissingDefaultArg = 0;
  522. for (; p < NumParams; ++p) {
  523. ParmVarDecl *Param = FD->getParamDecl(p);
  524. if (!Param->hasDefaultArg()) {
  525. if (Param->isInvalidDecl())
  526. /* We already complained about this parameter. */;
  527. else if (Param->getIdentifier())
  528. Diag(Param->getLocation(),
  529. diag::err_param_default_argument_missing_name)
  530. << Param->getIdentifier();
  531. else
  532. Diag(Param->getLocation(),
  533. diag::err_param_default_argument_missing);
  534. LastMissingDefaultArg = p;
  535. }
  536. }
  537. if (LastMissingDefaultArg > 0) {
  538. // Some default arguments were missing. Clear out all of the
  539. // default arguments up to (and including) the last missing
  540. // default argument, so that we leave the function parameters
  541. // in a semantically valid state.
  542. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  543. ParmVarDecl *Param = FD->getParamDecl(p);
  544. if (Param->hasDefaultArg()) {
  545. Param->setDefaultArg(0);
  546. }
  547. }
  548. }
  549. }
  550. // CheckConstexprParameterTypes - Check whether a function's parameter types
  551. // are all literal types. If so, return true. If not, produce a suitable
  552. // diagnostic depending on @p CCK and return false.
  553. static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
  554. Sema::CheckConstexprKind CCK) {
  555. unsigned ArgIndex = 0;
  556. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  557. for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
  558. e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
  559. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  560. SourceLocation ParamLoc = PD->getLocation();
  561. if (!(*i)->isDependentType() &&
  562. SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
  563. SemaRef.PDiag(diag::err_constexpr_non_literal_param)
  564. << ArgIndex+1 << PD->getSourceRange()
  565. << isa<CXXConstructorDecl>(FD) :
  566. SemaRef.PDiag(),
  567. /*AllowIncompleteType*/ true)) {
  568. if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
  569. SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
  570. << ArgIndex+1 << PD->getSourceRange()
  571. << isa<CXXConstructorDecl>(FD) << *i;
  572. return false;
  573. }
  574. }
  575. return true;
  576. }
  577. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  578. // the requirements of a constexpr function declaration or a constexpr
  579. // constructor declaration. Return true if it does, false if not.
  580. //
  581. // This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
  582. //
  583. // \param CCK Specifies whether to produce diagnostics if the function does not
  584. // satisfy the requirements.
  585. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
  586. CheckConstexprKind CCK) {
  587. assert((CCK != CCK_NoteNonConstexprInstantiation ||
  588. (NewFD->getTemplateInstantiationPattern() &&
  589. NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
  590. "only constexpr templates can be instantiated non-constexpr");
  591. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  592. if (MD && MD->isInstance()) {
  593. // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
  594. // In addition, either its function-body shall be = delete or = default or
  595. // it shall satisfy the following constraints:
  596. // - the class shall not have any virtual base classes;
  597. //
  598. // We apply this to constexpr member functions too: the class cannot be a
  599. // literal type, so the members are not permitted to be constexpr.
  600. const CXXRecordDecl *RD = MD->getParent();
  601. if (RD->getNumVBases()) {
  602. // Note, this is still illegal if the body is = default, since the
  603. // implicit body does not satisfy the requirements of a constexpr
  604. // constructor. We also reject cases where the body is = delete, as
  605. // required by N3308.
  606. if (CCK != CCK_Instantiation) {
  607. Diag(NewFD->getLocation(),
  608. CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
  609. : diag::note_constexpr_tmpl_virtual_base)
  610. << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
  611. << RD->getNumVBases();
  612. for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
  613. E = RD->vbases_end(); I != E; ++I)
  614. Diag(I->getSourceRange().getBegin(),
  615. diag::note_constexpr_virtual_base_here) << I->getSourceRange();
  616. }
  617. return false;
  618. }
  619. }
  620. if (!isa<CXXConstructorDecl>(NewFD)) {
  621. // C++11 [dcl.constexpr]p3:
  622. // The definition of a constexpr function shall satisfy the following
  623. // constraints:
  624. // - it shall not be virtual;
  625. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  626. if (Method && Method->isVirtual()) {
  627. if (CCK != CCK_Instantiation) {
  628. Diag(NewFD->getLocation(),
  629. CCK == CCK_Declaration ? diag::err_constexpr_virtual
  630. : diag::note_constexpr_tmpl_virtual);
  631. // If it's not obvious why this function is virtual, find an overridden
  632. // function which uses the 'virtual' keyword.
  633. const CXXMethodDecl *WrittenVirtual = Method;
  634. while (!WrittenVirtual->isVirtualAsWritten())
  635. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  636. if (WrittenVirtual != Method)
  637. Diag(WrittenVirtual->getLocation(),
  638. diag::note_overridden_virtual_function);
  639. }
  640. return false;
  641. }
  642. // - its return type shall be a literal type;
  643. QualType RT = NewFD->getResultType();
  644. if (!RT->isDependentType() &&
  645. RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
  646. PDiag(diag::err_constexpr_non_literal_return) :
  647. PDiag(),
  648. /*AllowIncompleteType*/ true)) {
  649. if (CCK == CCK_NoteNonConstexprInstantiation)
  650. Diag(NewFD->getLocation(),
  651. diag::note_constexpr_tmpl_non_literal_return) << RT;
  652. return false;
  653. }
  654. }
  655. // - each of its parameter types shall be a literal type;
  656. if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
  657. return false;
  658. return true;
  659. }
  660. /// Check the given declaration statement is legal within a constexpr function
  661. /// body. C++0x [dcl.constexpr]p3,p4.
  662. ///
  663. /// \return true if the body is OK, false if we have diagnosed a problem.
  664. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  665. DeclStmt *DS) {
  666. // C++0x [dcl.constexpr]p3 and p4:
  667. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  668. // contain only
  669. for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
  670. DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
  671. switch ((*DclIt)->getKind()) {
  672. case Decl::StaticAssert:
  673. case Decl::Using:
  674. case Decl::UsingShadow:
  675. case Decl::UsingDirective:
  676. case Decl::UnresolvedUsingTypename:
  677. // - static_assert-declarations
  678. // - using-declarations,
  679. // - using-directives,
  680. continue;
  681. case Decl::Typedef:
  682. case Decl::TypeAlias: {
  683. // - typedef declarations and alias-declarations that do not define
  684. // classes or enumerations,
  685. TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
  686. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  687. // Don't allow variably-modified types in constexpr functions.
  688. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  689. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  690. << TL.getSourceRange() << TL.getType()
  691. << isa<CXXConstructorDecl>(Dcl);
  692. return false;
  693. }
  694. continue;
  695. }
  696. case Decl::Enum:
  697. case Decl::CXXRecord:
  698. // As an extension, we allow the declaration (but not the definition) of
  699. // classes and enumerations in all declarations, not just in typedef and
  700. // alias declarations.
  701. if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
  702. SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
  703. << isa<CXXConstructorDecl>(Dcl);
  704. return false;
  705. }
  706. continue;
  707. case Decl::Var:
  708. SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
  709. << isa<CXXConstructorDecl>(Dcl);
  710. return false;
  711. default:
  712. SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  713. << isa<CXXConstructorDecl>(Dcl);
  714. return false;
  715. }
  716. }
  717. return true;
  718. }
  719. /// Check that the given field is initialized within a constexpr constructor.
  720. ///
  721. /// \param Dcl The constexpr constructor being checked.
  722. /// \param Field The field being checked. This may be a member of an anonymous
  723. /// struct or union nested within the class being checked.
  724. /// \param Inits All declarations, including anonymous struct/union members and
  725. /// indirect members, for which any initialization was provided.
  726. /// \param Diagnosed Set to true if an error is produced.
  727. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  728. const FunctionDecl *Dcl,
  729. FieldDecl *Field,
  730. llvm::SmallSet<Decl*, 16> &Inits,
  731. bool &Diagnosed) {
  732. if (Field->isUnnamedBitfield())
  733. return;
  734. if (!Inits.count(Field)) {
  735. if (!Diagnosed) {
  736. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  737. Diagnosed = true;
  738. }
  739. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  740. } else if (Field->isAnonymousStructOrUnion()) {
  741. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  742. for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  743. I != E; ++I)
  744. // If an anonymous union contains an anonymous struct of which any member
  745. // is initialized, all members must be initialized.
  746. if (!RD->isUnion() || Inits.count(*I))
  747. CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
  748. }
  749. }
  750. /// Check the body for the given constexpr function declaration only contains
  751. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  752. ///
  753. /// \return true if the body is OK, false if we have diagnosed a problem.
  754. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  755. if (isa<CXXTryStmt>(Body)) {
  756. // C++11 [dcl.constexpr]p3:
  757. // The definition of a constexpr function shall satisfy the following
  758. // constraints: [...]
  759. // - its function-body shall be = delete, = default, or a
  760. // compound-statement
  761. //
  762. // C++11 [dcl.constexpr]p4:
  763. // In the definition of a constexpr constructor, [...]
  764. // - its function-body shall not be a function-try-block;
  765. Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
  766. << isa<CXXConstructorDecl>(Dcl);
  767. return false;
  768. }
  769. // - its function-body shall be [...] a compound-statement that contains only
  770. CompoundStmt *CompBody = cast<CompoundStmt>(Body);
  771. llvm::SmallVector<SourceLocation, 4> ReturnStmts;
  772. for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
  773. BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
  774. switch ((*BodyIt)->getStmtClass()) {
  775. case Stmt::NullStmtClass:
  776. // - null statements,
  777. continue;
  778. case Stmt::DeclStmtClass:
  779. // - static_assert-declarations
  780. // - using-declarations,
  781. // - using-directives,
  782. // - typedef declarations and alias-declarations that do not define
  783. // classes or enumerations,
  784. if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
  785. return false;
  786. continue;
  787. case Stmt::ReturnStmtClass:
  788. // - and exactly one return statement;
  789. if (isa<CXXConstructorDecl>(Dcl))
  790. break;
  791. ReturnStmts.push_back((*BodyIt)->getLocStart());
  792. // FIXME
  793. // - every constructor call and implicit conversion used in initializing
  794. // the return value shall be one of those allowed in a constant
  795. // expression.
  796. // Deal with this as part of a general check that the function can produce
  797. // a constant expression (for [dcl.constexpr]p5).
  798. continue;
  799. default:
  800. break;
  801. }
  802. Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  803. << isa<CXXConstructorDecl>(Dcl);
  804. return false;
  805. }
  806. if (const CXXConstructorDecl *Constructor
  807. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  808. const CXXRecordDecl *RD = Constructor->getParent();
  809. // - every non-static data member and base class sub-object shall be
  810. // initialized;
  811. if (RD->isUnion()) {
  812. // DR1359: Exactly one member of a union shall be initialized.
  813. if (Constructor->getNumCtorInitializers() == 0) {
  814. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  815. return false;
  816. }
  817. } else if (!Constructor->isDependentContext() &&
  818. !Constructor->isDelegatingConstructor()) {
  819. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  820. // Skip detailed checking if we have enough initializers, and we would
  821. // allow at most one initializer per member.
  822. bool AnyAnonStructUnionMembers = false;
  823. unsigned Fields = 0;
  824. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  825. E = RD->field_end(); I != E; ++I, ++Fields) {
  826. if ((*I)->isAnonymousStructOrUnion()) {
  827. AnyAnonStructUnionMembers = true;
  828. break;
  829. }
  830. }
  831. if (AnyAnonStructUnionMembers ||
  832. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  833. // Check initialization of non-static data members. Base classes are
  834. // always initialized so do not need to be checked. Dependent bases
  835. // might not have initializers in the member initializer list.
  836. llvm::SmallSet<Decl*, 16> Inits;
  837. for (CXXConstructorDecl::init_const_iterator
  838. I = Constructor->init_begin(), E = Constructor->init_end();
  839. I != E; ++I) {
  840. if (FieldDecl *FD = (*I)->getMember())
  841. Inits.insert(FD);
  842. else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
  843. Inits.insert(ID->chain_begin(), ID->chain_end());
  844. }
  845. bool Diagnosed = false;
  846. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  847. E = RD->field_end(); I != E; ++I)
  848. CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
  849. if (Diagnosed)
  850. return false;
  851. }
  852. }
  853. // FIXME
  854. // - every constructor involved in initializing non-static data members
  855. // and base class sub-objects shall be a constexpr constructor;
  856. // - every assignment-expression that is an initializer-clause appearing
  857. // directly or indirectly within a brace-or-equal-initializer for
  858. // a non-static data member that is not named by a mem-initializer-id
  859. // shall be a constant expression; and
  860. // - every implicit conversion used in converting a constructor argument
  861. // to the corresponding parameter type and converting
  862. // a full-expression to the corresponding member type shall be one of
  863. // those allowed in a constant expression.
  864. // Deal with these as part of a general check that the function can produce
  865. // a constant expression (for [dcl.constexpr]p5).
  866. } else {
  867. if (ReturnStmts.empty()) {
  868. Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
  869. return false;
  870. }
  871. if (ReturnStmts.size() > 1) {
  872. Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
  873. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  874. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  875. return false;
  876. }
  877. }
  878. // C++11 [dcl.constexpr]p5:
  879. // if no function argument values exist such that the function invocation
  880. // substitution would produce a constant expression, the program is
  881. // ill-formed; no diagnostic required.
  882. // C++11 [dcl.constexpr]p3:
  883. // - every constructor call and implicit conversion used in initializing the
  884. // return value shall be one of those allowed in a constant expression.
  885. // C++11 [dcl.constexpr]p4:
  886. // - every constructor involved in initializing non-static data members and
  887. // base class sub-objects shall be a constexpr constructor.
  888. //
  889. // FIXME: We currently disable this check inside system headers, to work
  890. // around early STL implementations which contain constexpr functions which
  891. // can't produce constant expressions.
  892. llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
  893. if (!Context.getSourceManager().isInSystemHeader(Dcl->getLocation()) &&
  894. !Expr::isPotentialConstantExpr(Dcl, Diags)) {
  895. Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
  896. << isa<CXXConstructorDecl>(Dcl);
  897. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  898. Diag(Diags[I].first, Diags[I].second);
  899. return false;
  900. }
  901. return true;
  902. }
  903. /// isCurrentClassName - Determine whether the identifier II is the
  904. /// name of the class type currently being defined. In the case of
  905. /// nested classes, this will only return true if II is the name of
  906. /// the innermost class.
  907. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
  908. const CXXScopeSpec *SS) {
  909. assert(getLangOptions().CPlusPlus && "No class names in C!");
  910. CXXRecordDecl *CurDecl;
  911. if (SS && SS->isSet() && !SS->isInvalid()) {
  912. DeclContext *DC = computeDeclContext(*SS, true);
  913. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  914. } else
  915. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  916. if (CurDecl && CurDecl->getIdentifier())
  917. return &II == CurDecl->getIdentifier();
  918. else
  919. return false;
  920. }
  921. /// \brief Check the validity of a C++ base class specifier.
  922. ///
  923. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  924. /// and returns NULL otherwise.
  925. CXXBaseSpecifier *
  926. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  927. SourceRange SpecifierRange,
  928. bool Virtual, AccessSpecifier Access,
  929. TypeSourceInfo *TInfo,
  930. SourceLocation EllipsisLoc) {
  931. QualType BaseType = TInfo->getType();
  932. // C++ [class.union]p1:
  933. // A union shall not have base classes.
  934. if (Class->isUnion()) {
  935. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  936. << SpecifierRange;
  937. return 0;
  938. }
  939. if (EllipsisLoc.isValid() &&
  940. !TInfo->getType()->containsUnexpandedParameterPack()) {
  941. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  942. << TInfo->getTypeLoc().getSourceRange();
  943. EllipsisLoc = SourceLocation();
  944. }
  945. if (BaseType->isDependentType())
  946. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  947. Class->getTagKind() == TTK_Class,
  948. Access, TInfo, EllipsisLoc);
  949. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  950. // Base specifiers must be record types.
  951. if (!BaseType->isRecordType()) {
  952. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  953. return 0;
  954. }
  955. // C++ [class.union]p1:
  956. // A union shall not be used as a base class.
  957. if (BaseType->isUnionType()) {
  958. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  959. return 0;
  960. }
  961. // C++ [class.derived]p2:
  962. // The class-name in a base-specifier shall not be an incompletely
  963. // defined class.
  964. if (RequireCompleteType(BaseLoc, BaseType,
  965. PDiag(diag::err_incomplete_base_class)
  966. << SpecifierRange)) {
  967. Class->setInvalidDecl();
  968. return 0;
  969. }
  970. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  971. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  972. assert(BaseDecl && "Record type has no declaration");
  973. BaseDecl = BaseDecl->getDefinition();
  974. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  975. CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  976. assert(CXXBaseDecl && "Base type is not a C++ type");
  977. // C++ [class]p3:
  978. // If a class is marked final and it appears as a base-type-specifier in
  979. // base-clause, the program is ill-formed.
  980. if (CXXBaseDecl->hasAttr<FinalAttr>()) {
  981. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  982. << CXXBaseDecl->getDeclName();
  983. Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
  984. << CXXBaseDecl->getDeclName();
  985. return 0;
  986. }
  987. if (BaseDecl->isInvalidDecl())
  988. Class->setInvalidDecl();
  989. // Create the base specifier.
  990. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  991. Class->getTagKind() == TTK_Class,
  992. Access, TInfo, EllipsisLoc);
  993. }
  994. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  995. /// one entry in the base class list of a class specifier, for
  996. /// example:
  997. /// class foo : public bar, virtual private baz {
  998. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  999. BaseResult
  1000. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  1001. bool Virtual, AccessSpecifier Access,
  1002. ParsedType basetype, SourceLocation BaseLoc,
  1003. SourceLocation EllipsisLoc) {
  1004. if (!classdecl)
  1005. return true;
  1006. AdjustDeclIfTemplate(classdecl);
  1007. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  1008. if (!Class)
  1009. return true;
  1010. TypeSourceInfo *TInfo = 0;
  1011. GetTypeFromParser(basetype, &TInfo);
  1012. if (EllipsisLoc.isInvalid() &&
  1013. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  1014. UPPC_BaseType))
  1015. return true;
  1016. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  1017. Virtual, Access, TInfo,
  1018. EllipsisLoc))
  1019. return BaseSpec;
  1020. return true;
  1021. }
  1022. /// \brief Performs the actual work of attaching the given base class
  1023. /// specifiers to a C++ class.
  1024. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
  1025. unsigned NumBases) {
  1026. if (NumBases == 0)
  1027. return false;
  1028. // Used to keep track of which base types we have already seen, so
  1029. // that we can properly diagnose redundant direct base types. Note
  1030. // that the key is always the unqualified canonical type of the base
  1031. // class.
  1032. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  1033. // Copy non-redundant base specifiers into permanent storage.
  1034. unsigned NumGoodBases = 0;
  1035. bool Invalid = false;
  1036. for (unsigned idx = 0; idx < NumBases; ++idx) {
  1037. QualType NewBaseType
  1038. = Context.getCanonicalType(Bases[idx]->getType());
  1039. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  1040. if (KnownBaseTypes[NewBaseType]) {
  1041. // C++ [class.mi]p3:
  1042. // A class shall not be specified as a direct base class of a
  1043. // derived class more than once.
  1044. Diag(Bases[idx]->getSourceRange().getBegin(),
  1045. diag::err_duplicate_base_class)
  1046. << KnownBaseTypes[NewBaseType]->getType()
  1047. << Bases[idx]->getSourceRange();
  1048. // Delete the duplicate base class specifier; we're going to
  1049. // overwrite its pointer later.
  1050. Context.Deallocate(Bases[idx]);
  1051. Invalid = true;
  1052. } else {
  1053. // Okay, add this new base class.
  1054. KnownBaseTypes[NewBaseType] = Bases[idx];
  1055. Bases[NumGoodBases++] = Bases[idx];
  1056. if (const RecordType *Record = NewBaseType->getAs<RecordType>())
  1057. if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
  1058. if (RD->hasAttr<WeakAttr>())
  1059. Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
  1060. }
  1061. }
  1062. // Attach the remaining base class specifiers to the derived class.
  1063. Class->setBases(Bases, NumGoodBases);
  1064. // Delete the remaining (good) base class specifiers, since their
  1065. // data has been copied into the CXXRecordDecl.
  1066. for (unsigned idx = 0; idx < NumGoodBases; ++idx)
  1067. Context.Deallocate(Bases[idx]);
  1068. return Invalid;
  1069. }
  1070. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  1071. /// class, after checking whether there are any duplicate base
  1072. /// classes.
  1073. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
  1074. unsigned NumBases) {
  1075. if (!ClassDecl || !Bases || !NumBases)
  1076. return;
  1077. AdjustDeclIfTemplate(ClassDecl);
  1078. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
  1079. (CXXBaseSpecifier**)(Bases), NumBases);
  1080. }
  1081. static CXXRecordDecl *GetClassForType(QualType T) {
  1082. if (const RecordType *RT = T->getAs<RecordType>())
  1083. return cast<CXXRecordDecl>(RT->getDecl());
  1084. else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
  1085. return ICT->getDecl();
  1086. else
  1087. return 0;
  1088. }
  1089. /// \brief Determine whether the type \p Derived is a C++ class that is
  1090. /// derived from the type \p Base.
  1091. bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
  1092. if (!getLangOptions().CPlusPlus)
  1093. return false;
  1094. CXXRecordDecl *DerivedRD = GetClassForType(Derived);
  1095. if (!DerivedRD)
  1096. return false;
  1097. CXXRecordDecl *BaseRD = GetClassForType(Base);
  1098. if (!BaseRD)
  1099. return false;
  1100. // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
  1101. return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
  1102. }
  1103. /// \brief Determine whether the type \p Derived is a C++ class that is
  1104. /// derived from the type \p Base.
  1105. bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
  1106. if (!getLangOptions().CPlusPlus)
  1107. return false;
  1108. CXXRecordDecl *DerivedRD = GetClassForType(Derived);
  1109. if (!DerivedRD)
  1110. return false;
  1111. CXXRecordDecl *BaseRD = GetClassForType(Base);
  1112. if (!BaseRD)
  1113. return false;
  1114. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  1115. }
  1116. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  1117. CXXCastPath &BasePathArray) {
  1118. assert(BasePathArray.empty() && "Base path array must be empty!");
  1119. assert(Paths.isRecordingPaths() && "Must record paths!");
  1120. const CXXBasePath &Path = Paths.front();
  1121. // We first go backward and check if we have a virtual base.
  1122. // FIXME: It would be better if CXXBasePath had the base specifier for
  1123. // the nearest virtual base.
  1124. unsigned Start = 0;
  1125. for (unsigned I = Path.size(); I != 0; --I) {
  1126. if (Path[I - 1].Base->isVirtual()) {
  1127. Start = I - 1;
  1128. break;
  1129. }
  1130. }
  1131. // Now add all bases.
  1132. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  1133. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  1134. }
  1135. /// \brief Determine whether the given base path includes a virtual
  1136. /// base class.
  1137. bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
  1138. for (CXXCastPath::const_iterator B = BasePath.begin(),
  1139. BEnd = BasePath.end();
  1140. B != BEnd; ++B)
  1141. if ((*B)->isVirtual())
  1142. return true;
  1143. return false;
  1144. }
  1145. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  1146. /// conversion (where Derived and Base are class types) is
  1147. /// well-formed, meaning that the conversion is unambiguous (and
  1148. /// that all of the base classes are accessible). Returns true
  1149. /// and emits a diagnostic if the code is ill-formed, returns false
  1150. /// otherwise. Loc is the location where this routine should point to
  1151. /// if there is an error, and Range is the source range to highlight
  1152. /// if there is an error.
  1153. bool
  1154. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  1155. unsigned InaccessibleBaseID,
  1156. unsigned AmbigiousBaseConvID,
  1157. SourceLocation Loc, SourceRange Range,
  1158. DeclarationName Name,
  1159. CXXCastPath *BasePath) {
  1160. // First, determine whether the path from Derived to Base is
  1161. // ambiguous. This is slightly more expensive than checking whether
  1162. // the Derived to Base conversion exists, because here we need to
  1163. // explore multiple paths to determine if there is an ambiguity.
  1164. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1165. /*DetectVirtual=*/false);
  1166. bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
  1167. assert(DerivationOkay &&
  1168. "Can only be used with a derived-to-base conversion");
  1169. (void)DerivationOkay;
  1170. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
  1171. if (InaccessibleBaseID) {
  1172. // Check that the base class can be accessed.
  1173. switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
  1174. InaccessibleBaseID)) {
  1175. case AR_inaccessible:
  1176. return true;
  1177. case AR_accessible:
  1178. case AR_dependent:
  1179. case AR_delayed:
  1180. break;
  1181. }
  1182. }
  1183. // Build a base path if necessary.
  1184. if (BasePath)
  1185. BuildBasePathArray(Paths, *BasePath);
  1186. return false;
  1187. }
  1188. // We know that the derived-to-base conversion is ambiguous, and
  1189. // we're going to produce a diagnostic. Perform the derived-to-base
  1190. // search just one more time to compute all of the possible paths so
  1191. // that we can print them out. This is more expensive than any of
  1192. // the previous derived-to-base checks we've done, but at this point
  1193. // performance isn't as much of an issue.
  1194. Paths.clear();
  1195. Paths.setRecordingPaths(true);
  1196. bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
  1197. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  1198. (void)StillOkay;
  1199. // Build up a textual representation of the ambiguous paths, e.g.,
  1200. // D -> B -> A, that will be used to illustrate the ambiguous
  1201. // conversions in the diagnostic. We only print one of the paths
  1202. // to each base class subobject.
  1203. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  1204. Diag(Loc, AmbigiousBaseConvID)
  1205. << Derived << Base << PathDisplayStr << Range << Name;
  1206. return true;
  1207. }
  1208. bool
  1209. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  1210. SourceLocation Loc, SourceRange Range,
  1211. CXXCastPath *BasePath,
  1212. bool IgnoreAccess) {
  1213. return CheckDerivedToBaseConversion(Derived, Base,
  1214. IgnoreAccess ? 0
  1215. : diag::err_upcast_to_inaccessible_base,
  1216. diag::err_ambiguous_derived_to_base_conv,
  1217. Loc, Range, DeclarationName(),
  1218. BasePath);
  1219. }
  1220. /// @brief Builds a string representing ambiguous paths from a
  1221. /// specific derived class to different subobjects of the same base
  1222. /// class.
  1223. ///
  1224. /// This function builds a string that can be used in error messages
  1225. /// to show the different paths that one can take through the
  1226. /// inheritance hierarchy to go from the derived class to different
  1227. /// subobjects of a base class. The result looks something like this:
  1228. /// @code
  1229. /// struct D -> struct B -> struct A
  1230. /// struct D -> struct C -> struct A
  1231. /// @endcode
  1232. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  1233. std::string PathDisplayStr;
  1234. std::set<unsigned> DisplayedPaths;
  1235. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  1236. Path != Paths.end(); ++Path) {
  1237. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  1238. // We haven't displayed a path to this particular base
  1239. // class subobject yet.
  1240. PathDisplayStr += "\n ";
  1241. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  1242. for (CXXBasePath::const_iterator Element = Path->begin();
  1243. Element != Path->end(); ++Element)
  1244. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  1245. }
  1246. }
  1247. return PathDisplayStr;
  1248. }
  1249. //===----------------------------------------------------------------------===//
  1250. // C++ class member Handling
  1251. //===----------------------------------------------------------------------===//
  1252. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  1253. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
  1254. SourceLocation ASLoc,
  1255. SourceLocation ColonLoc,
  1256. AttributeList *Attrs) {
  1257. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  1258. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  1259. ASLoc, ColonLoc);
  1260. CurContext->addHiddenDecl(ASDecl);
  1261. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  1262. }
  1263. /// CheckOverrideControl - Check C++0x override control semantics.
  1264. void Sema::CheckOverrideControl(const Decl *D) {
  1265. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  1266. if (!MD || !MD->isVirtual())
  1267. return;
  1268. if (MD->isDependentContext())
  1269. return;
  1270. // C++0x [class.virtual]p3:
  1271. // If a virtual function is marked with the virt-specifier override and does
  1272. // not override a member function of a base class,
  1273. // the program is ill-formed.
  1274. bool HasOverriddenMethods =
  1275. MD->begin_overridden_methods() != MD->end_overridden_methods();
  1276. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
  1277. Diag(MD->getLocation(),
  1278. diag::err_function_marked_override_not_overriding)
  1279. << MD->getDeclName();
  1280. return;
  1281. }
  1282. }
  1283. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  1284. /// function overrides a virtual member function marked 'final', according to
  1285. /// C++0x [class.virtual]p3.
  1286. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  1287. const CXXMethodDecl *Old) {
  1288. if (!Old->hasAttr<FinalAttr>())
  1289. return false;
  1290. Diag(New->getLocation(), diag::err_final_function_overridden)
  1291. << New->getDeclName();
  1292. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  1293. return true;
  1294. }
  1295. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  1296. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  1297. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  1298. /// one has been parsed, and 'HasDeferredInit' is true if an initializer is
  1299. /// present but parsing it has been deferred.
  1300. Decl *
  1301. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  1302. MultiTemplateParamsArg TemplateParameterLists,
  1303. Expr *BW, const VirtSpecifiers &VS,
  1304. bool HasDeferredInit) {
  1305. const DeclSpec &DS = D.getDeclSpec();
  1306. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  1307. DeclarationName Name = NameInfo.getName();
  1308. SourceLocation Loc = NameInfo.getLoc();
  1309. // For anonymous bitfields, the location should point to the type.
  1310. if (Loc.isInvalid())
  1311. Loc = D.getSourceRange().getBegin();
  1312. Expr *BitWidth = static_cast<Expr*>(BW);
  1313. assert(isa<CXXRecordDecl>(CurContext));
  1314. assert(!DS.isFriendSpecified());
  1315. bool isFunc = D.isDeclarationOfFunction();
  1316. // C++ 9.2p6: A member shall not be declared to have automatic storage
  1317. // duration (auto, register) or with the extern storage-class-specifier.
  1318. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  1319. // data members and cannot be applied to names declared const or static,
  1320. // and cannot be applied to reference members.
  1321. switch (DS.getStorageClassSpec()) {
  1322. case DeclSpec::SCS_unspecified:
  1323. case DeclSpec::SCS_typedef:
  1324. case DeclSpec::SCS_static:
  1325. // FALL THROUGH.
  1326. break;
  1327. case DeclSpec::SCS_mutable:
  1328. if (isFunc) {
  1329. if (DS.getStorageClassSpecLoc().isValid())
  1330. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  1331. else
  1332. Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
  1333. // FIXME: It would be nicer if the keyword was ignored only for this
  1334. // declarator. Otherwise we could get follow-up errors.
  1335. D.getMutableDeclSpec().ClearStorageClassSpecs();
  1336. }
  1337. break;
  1338. default:
  1339. if (DS.getStorageClassSpecLoc().isValid())
  1340. Diag(DS.getStorageClassSpecLoc(),
  1341. diag::err_storageclass_invalid_for_member);
  1342. else
  1343. Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
  1344. D.getMutableDeclSpec().ClearStorageClassSpecs();
  1345. }
  1346. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  1347. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  1348. !isFunc);
  1349. Decl *Member;
  1350. if (isInstField) {
  1351. CXXScopeSpec &SS = D.getCXXScopeSpec();
  1352. // Data members must have identifiers for names.
  1353. if (Name.getNameKind() != DeclarationName::Identifier) {
  1354. Diag(Loc, diag::err_bad_variable_name)
  1355. << Name;
  1356. return 0;
  1357. }
  1358. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1359. // Member field could not be with "template" keyword.
  1360. // So TemplateParameterLists should be empty in this case.
  1361. if (TemplateParameterLists.size()) {
  1362. TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
  1363. if (TemplateParams->size()) {
  1364. // There is no such thing as a member field template.
  1365. Diag(D.getIdentifierLoc(), diag::err_template_member)
  1366. << II
  1367. << SourceRange(TemplateParams->getTemplateLoc(),
  1368. TemplateParams->getRAngleLoc());
  1369. } else {
  1370. // There is an extraneous 'template<>' for this member.
  1371. Diag(TemplateParams->getTemplateLoc(),
  1372. diag::err_template_member_noparams)
  1373. << II
  1374. << SourceRange(TemplateParams->getTemplateLoc(),
  1375. TemplateParams->getRAngleLoc());
  1376. }
  1377. return 0;
  1378. }
  1379. if (SS.isSet() && !SS.isInvalid()) {
  1380. // The user provided a superfluous scope specifier inside a class
  1381. // definition:
  1382. //
  1383. // class X {
  1384. // int X::member;
  1385. // };
  1386. DeclContext *DC = 0;
  1387. if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
  1388. Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
  1389. << Name << FixItHint::CreateRemoval(SS.getRange());
  1390. else
  1391. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  1392. << Name << SS.getRange();
  1393. SS.clear();
  1394. }
  1395. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
  1396. HasDeferredInit, AS);
  1397. assert(Member && "HandleField never returns null");
  1398. } else {
  1399. assert(!HasDeferredInit);
  1400. Member = HandleDeclarator(S, D, move(TemplateParameterLists));
  1401. if (!Member) {
  1402. return 0;
  1403. }
  1404. // Non-instance-fields can't have a bitfield.
  1405. if (BitWidth) {
  1406. if (Member->isInvalidDecl()) {
  1407. // don't emit another diagnostic.
  1408. } else if (isa<VarDecl>(Member)) {
  1409. // C++ 9.6p3: A bit-field shall not be a static member.
  1410. // "static member 'A' cannot be a bit-field"
  1411. Diag(Loc, diag::err_static_not_bitfield)
  1412. << Name << BitWidth->getSourceRange();
  1413. } else if (isa<TypedefDecl>(Member)) {
  1414. // "typedef member 'x' cannot be a bit-field"
  1415. Diag(Loc, diag::err_typedef_not_bitfield)
  1416. << Name << BitWidth->getSourceRange();
  1417. } else {
  1418. // A function typedef ("typedef int f(); f a;").
  1419. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  1420. Diag(Loc, diag::err_not_integral_type_bitfield)
  1421. << Name << cast<ValueDecl>(Member)->getType()
  1422. << BitWidth->getSourceRange();
  1423. }
  1424. BitWidth = 0;
  1425. Member->setInvalidDecl();
  1426. }
  1427. Member->setAccess(AS);
  1428. // If we have declared a member function template, set the access of the
  1429. // templated declaration as well.
  1430. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  1431. FunTmpl->getTemplatedDecl()->setAccess(AS);
  1432. }
  1433. if (VS.isOverrideSpecified()) {
  1434. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  1435. if (!MD || !MD->isVirtual()) {
  1436. Diag(Member->getLocStart(),
  1437. diag::override_keyword_only_allowed_on_virtual_member_functions)
  1438. << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
  1439. } else
  1440. MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
  1441. }
  1442. if (VS.isFinalSpecified()) {
  1443. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  1444. if (!MD || !MD->isVirtual()) {
  1445. Diag(Member->getLocStart(),
  1446. diag::override_keyword_only_allowed_on_virtual_member_functions)
  1447. << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
  1448. } else
  1449. MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
  1450. }
  1451. if (VS.getLastLocation().isValid()) {
  1452. // Update the end location of a method that has a virt-specifiers.
  1453. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  1454. MD->setRangeEnd(VS.getLastLocation());
  1455. }
  1456. CheckOverrideControl(Member);
  1457. assert((Name || isInstField) && "No identifier for non-field ?");
  1458. if (isInstField)
  1459. FieldCollector->Add(cast<FieldDecl>(Member));
  1460. return Member;
  1461. }
  1462. /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
  1463. /// in-class initializer for a non-static C++ class member, and after
  1464. /// instantiating an in-class initializer in a class template. Such actions
  1465. /// are deferred until the class is complete.
  1466. void
  1467. Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
  1468. Expr *InitExpr) {
  1469. FieldDecl *FD = cast<FieldDecl>(D);
  1470. if (!InitExpr) {
  1471. FD->setInvalidDecl();
  1472. FD->removeInClassInitializer();
  1473. return;
  1474. }
  1475. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  1476. FD->setInvalidDecl();
  1477. FD->removeInClassInitializer();
  1478. return;
  1479. }
  1480. ExprResult Init = InitExpr;
  1481. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  1482. // FIXME: if there is no EqualLoc, this is list-initialization.
  1483. Init = PerformCopyInitialization(
  1484. InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
  1485. if (Init.isInvalid()) {
  1486. FD->setInvalidDecl();
  1487. return;
  1488. }
  1489. CheckImplicitConversions(Init.get(), EqualLoc);
  1490. }
  1491. // C++0x [class.base.init]p7:
  1492. // The initialization of each base and member constitutes a
  1493. // full-expression.
  1494. Init = MaybeCreateExprWithCleanups(Init);
  1495. if (Init.isInvalid()) {
  1496. FD->setInvalidDecl();
  1497. return;
  1498. }
  1499. InitExpr = Init.release();
  1500. FD->setInClassInitializer(InitExpr);
  1501. }
  1502. /// \brief Find the direct and/or virtual base specifiers that
  1503. /// correspond to the given base type, for use in base initialization
  1504. /// within a constructor.
  1505. static bool FindBaseInitializer(Sema &SemaRef,
  1506. CXXRecordDecl *ClassDecl,
  1507. QualType BaseType,
  1508. const CXXBaseSpecifier *&DirectBaseSpec,
  1509. const CXXBaseSpecifier *&VirtualBaseSpec) {
  1510. // First, check for a direct base class.
  1511. DirectBaseSpec = 0;
  1512. for (CXXRecordDecl::base_class_const_iterator Base
  1513. = ClassDecl->bases_begin();
  1514. Base != ClassDecl->bases_end(); ++Base) {
  1515. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
  1516. // We found a direct base of this type. That's what we're
  1517. // initializing.
  1518. DirectBaseSpec = &*Base;
  1519. break;
  1520. }
  1521. }
  1522. // Check for a virtual base class.
  1523. // FIXME: We might be able to short-circuit this if we know in advance that
  1524. // there are no virtual bases.
  1525. VirtualBaseSpec = 0;
  1526. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  1527. // We haven't found a base yet; search the class hierarchy for a
  1528. // virtual base class.
  1529. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1530. /*DetectVirtual=*/false);
  1531. if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
  1532. BaseType, Paths)) {
  1533. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  1534. Path != Paths.end(); ++Path) {
  1535. if (Path->back().Base->isVirtual()) {
  1536. VirtualBaseSpec = Path->back().Base;
  1537. break;
  1538. }
  1539. }
  1540. }
  1541. }
  1542. return DirectBaseSpec || VirtualBaseSpec;
  1543. }
  1544. /// \brief Handle a C++ member initializer using braced-init-list syntax.
  1545. MemInitResult
  1546. Sema::ActOnMemInitializer(Decl *ConstructorD,
  1547. Scope *S,
  1548. CXXScopeSpec &SS,
  1549. IdentifierInfo *MemberOrBase,
  1550. ParsedType TemplateTypeTy,
  1551. const DeclSpec &DS,
  1552. SourceLocation IdLoc,
  1553. Expr *InitList,
  1554. SourceLocation EllipsisLoc) {
  1555. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  1556. DS, IdLoc, MultiInitializer(InitList),
  1557. EllipsisLoc);
  1558. }
  1559. /// \brief Handle a C++ member initializer using parentheses syntax.
  1560. MemInitResult
  1561. Sema::ActOnMemInitializer(Decl *ConstructorD,
  1562. Scope *S,
  1563. CXXScopeSpec &SS,
  1564. IdentifierInfo *MemberOrBase,
  1565. ParsedType TemplateTypeTy,
  1566. const DeclSpec &DS,
  1567. SourceLocation IdLoc,
  1568. SourceLocation LParenLoc,
  1569. Expr **Args, unsigned NumArgs,
  1570. SourceLocation RParenLoc,
  1571. SourceLocation EllipsisLoc) {
  1572. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  1573. DS, IdLoc, MultiInitializer(LParenLoc, Args,
  1574. NumArgs, RParenLoc),
  1575. EllipsisLoc);
  1576. }
  1577. namespace {
  1578. // Callback to only accept typo corrections that can be a valid C++ member
  1579. // intializer: either a non-static field member or a base class.
  1580. class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
  1581. public:
  1582. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  1583. : ClassDecl(ClassDecl) {}
  1584. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  1585. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  1586. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  1587. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  1588. else
  1589. return isa<TypeDecl>(ND);
  1590. }
  1591. return false;
  1592. }
  1593. private:
  1594. CXXRecordDecl *ClassDecl;
  1595. };
  1596. }
  1597. /// \brief Handle a C++ member initializer.
  1598. MemInitResult
  1599. Sema::BuildMemInitializer(Decl *ConstructorD,
  1600. Scope *S,
  1601. CXXScopeSpec &SS,
  1602. IdentifierInfo *MemberOrBase,
  1603. ParsedType TemplateTypeTy,
  1604. const DeclSpec &DS,
  1605. SourceLocation IdLoc,
  1606. const MultiInitializer &Args,
  1607. SourceLocation EllipsisLoc) {
  1608. if (!ConstructorD)
  1609. return true;
  1610. AdjustDeclIfTemplate(ConstructorD);
  1611. CXXConstructorDecl *Constructor
  1612. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  1613. if (!Constructor) {
  1614. // The user wrote a constructor initializer on a function that is
  1615. // not a C++ constructor. Ignore the error for now, because we may
  1616. // have more member initializers coming; we'll diagnose it just
  1617. // once in ActOnMemInitializers.
  1618. return true;
  1619. }
  1620. CXXRecordDecl *ClassDecl = Constructor->getParent();
  1621. // C++ [class.base.init]p2:
  1622. // Names in a mem-initializer-id are looked up in the scope of the
  1623. // constructor's class and, if not found in that scope, are looked
  1624. // up in the scope containing the constructor's definition.
  1625. // [Note: if the constructor's class contains a member with the
  1626. // same name as a direct or virtual base class of the class, a
  1627. // mem-initializer-id naming the member or base class and composed
  1628. // of a single identifier refers to the class member. A
  1629. // mem-initializer-id for the hidden base class may be specified
  1630. // using a qualified name. ]
  1631. if (!SS.getScopeRep() && !TemplateTypeTy) {
  1632. // Look for a member, first.
  1633. DeclContext::lookup_result Result
  1634. = ClassDecl->lookup(MemberOrBase);
  1635. if (Result.first != Result.second) {
  1636. ValueDecl *Member;
  1637. if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
  1638. (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
  1639. if (EllipsisLoc.isValid())
  1640. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  1641. << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
  1642. return BuildMemberInitializer(Member, Args, IdLoc);
  1643. }
  1644. }
  1645. }
  1646. // It didn't name a member, so see if it names a class.
  1647. QualType BaseType;
  1648. TypeSourceInfo *TInfo = 0;
  1649. if (TemplateTypeTy) {
  1650. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  1651. } else if (DS.getTypeSpecType() == TST_decltype) {
  1652. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  1653. } else {
  1654. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  1655. LookupParsedName(R, S, &SS);
  1656. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  1657. if (!TyD) {
  1658. if (R.isAmbiguous()) return true;
  1659. // We don't want access-control diagnostics here.
  1660. R.suppressDiagnostics();
  1661. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  1662. bool NotUnknownSpecialization = false;
  1663. DeclContext *DC = computeDeclContext(SS, false);
  1664. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  1665. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  1666. if (!NotUnknownSpecialization) {
  1667. // When the scope specifier can refer to a member of an unknown
  1668. // specialization, we take it as a type name.
  1669. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  1670. SS.getWithLocInContext(Context),
  1671. *MemberOrBase, IdLoc);
  1672. if (BaseType.isNull())
  1673. return true;
  1674. R.clear();
  1675. R.setLookupName(MemberOrBase);
  1676. }
  1677. }
  1678. // If no results were found, try to correct typos.
  1679. TypoCorrection Corr;
  1680. MemInitializerValidatorCCC Validator(ClassDecl);
  1681. if (R.empty() && BaseType.isNull() &&
  1682. (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  1683. Validator, ClassDecl))) {
  1684. std::string CorrectedStr(Corr.getAsString(getLangOptions()));
  1685. std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
  1686. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  1687. // We have found a non-static data member with a similar
  1688. // name to what was typed; complain and initialize that
  1689. // member.
  1690. Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
  1691. << MemberOrBase << true << CorrectedQuotedStr
  1692. << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
  1693. Diag(Member->getLocation(), diag::note_previous_decl)
  1694. << CorrectedQuotedStr;
  1695. return BuildMemberInitializer(Member, Args, IdLoc);
  1696. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  1697. const CXXBaseSpecifier *DirectBaseSpec;
  1698. const CXXBaseSpecifier *VirtualBaseSpec;
  1699. if (FindBaseInitializer(*this, ClassDecl,
  1700. Context.getTypeDeclType(Type),
  1701. DirectBaseSpec, VirtualBaseSpec)) {
  1702. // We have found a direct or virtual base class with a
  1703. // similar name to what was typed; complain and initialize
  1704. // that base class.
  1705. Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
  1706. << MemberOrBase << false << CorrectedQuotedStr
  1707. << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
  1708. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
  1709. : VirtualBaseSpec;
  1710. Diag(BaseSpec->getSourceRange().getBegin(),
  1711. diag::note_base_class_specified_here)
  1712. << BaseSpec->getType()
  1713. << BaseSpec->getSourceRange();
  1714. TyD = Type;
  1715. }
  1716. }
  1717. }
  1718. if (!TyD && BaseType.isNull()) {
  1719. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  1720. << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
  1721. return true;
  1722. }
  1723. }
  1724. if (BaseType.isNull()) {
  1725. BaseType = Context.getTypeDeclType(TyD);
  1726. if (SS.isSet()) {
  1727. NestedNameSpecifier *Qualifier =
  1728. static_cast<NestedNameSpecifier*>(SS.getScopeRep());
  1729. // FIXME: preserve source range information
  1730. BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
  1731. }
  1732. }
  1733. }
  1734. if (!TInfo)
  1735. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  1736. return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
  1737. }
  1738. /// Checks a member initializer expression for cases where reference (or
  1739. /// pointer) members are bound to by-value parameters (or their addresses).
  1740. static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
  1741. Expr *Init,
  1742. SourceLocation IdLoc) {
  1743. QualType MemberTy = Member->getType();
  1744. // We only handle pointers and references currently.
  1745. // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
  1746. if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
  1747. return;
  1748. const bool IsPointer = MemberTy->isPointerType();
  1749. if (IsPointer) {
  1750. if (const UnaryOperator *Op
  1751. = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
  1752. // The only case we're worried about with pointers requires taking the
  1753. // address.
  1754. if (Op->getOpcode() != UO_AddrOf)
  1755. return;
  1756. Init = Op->getSubExpr();
  1757. } else {
  1758. // We only handle address-of expression initializers for pointers.
  1759. return;
  1760. }
  1761. }
  1762. if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
  1763. // Taking the address of a temporary will be diagnosed as a hard error.
  1764. if (IsPointer)
  1765. return;
  1766. S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
  1767. << Member << Init->getSourceRange();
  1768. } else if (const DeclRefExpr *DRE
  1769. = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
  1770. // We only warn when referring to a non-reference parameter declaration.
  1771. const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
  1772. if (!Parameter || Parameter->getType()->isReferenceType())
  1773. return;
  1774. S.Diag(Init->getExprLoc(),
  1775. IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  1776. : diag::warn_bind_ref_member_to_parameter)
  1777. << Member << Parameter << Init->getSourceRange();
  1778. } else {
  1779. // Other initializers are fine.
  1780. return;
  1781. }
  1782. S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
  1783. << (unsigned)IsPointer;
  1784. }
  1785. /// Checks an initializer expression for use of uninitialized fields, such as
  1786. /// containing the field that is being initialized. Returns true if there is an
  1787. /// uninitialized field was used an updates the SourceLocation parameter; false
  1788. /// otherwise.
  1789. static bool InitExprContainsUninitializedFields(const Stmt *S,
  1790. const ValueDecl *LhsField,
  1791. SourceLocation *L) {
  1792. assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
  1793. if (isa<CallExpr>(S)) {
  1794. // Do not descend into function calls or constructors, as the use
  1795. // of an uninitialized field may be valid. One would have to inspect
  1796. // the contents of the function/ctor to determine if it is safe or not.
  1797. // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
  1798. // may be safe, depending on what the function/ctor does.
  1799. return false;
  1800. }
  1801. if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
  1802. const NamedDecl *RhsField = ME->getMemberDecl();
  1803. if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
  1804. // The member expression points to a static data member.
  1805. assert(VD->isStaticDataMember() &&
  1806. "Member points to non-static data member!");
  1807. (void)VD;
  1808. return false;
  1809. }
  1810. if (isa<EnumConstantDecl>(RhsField)) {
  1811. // The member expression points to an enum.
  1812. return false;
  1813. }
  1814. if (RhsField == LhsField) {
  1815. // Initializing a field with itself. Throw a warning.
  1816. // But wait; there are exceptions!
  1817. // Exception #1: The field may not belong to this record.
  1818. // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
  1819. const Expr *base = ME->getBase();
  1820. if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
  1821. // Even though the field matches, it does not belong to this record.
  1822. return false;
  1823. }
  1824. // None of the exceptions triggered; return true to indicate an
  1825. // uninitialized field was used.
  1826. *L = ME->getMemberLoc();
  1827. return true;
  1828. }
  1829. } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
  1830. // sizeof/alignof doesn't reference contents, do not warn.
  1831. return false;
  1832. } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
  1833. // address-of doesn't reference contents (the pointer may be dereferenced
  1834. // in the same expression but it would be rare; and weird).
  1835. if (UOE->getOpcode() == UO_AddrOf)
  1836. return false;
  1837. }
  1838. for (Stmt::const_child_range it = S->children(); it; ++it) {
  1839. if (!*it) {
  1840. // An expression such as 'member(arg ?: "")' may trigger this.
  1841. continue;
  1842. }
  1843. if (InitExprContainsUninitializedFields(*it, LhsField, L))
  1844. return true;
  1845. }
  1846. return false;
  1847. }
  1848. MemInitResult
  1849. Sema::BuildMemberInitializer(ValueDecl *Member,
  1850. const MultiInitializer &Args,
  1851. SourceLocation IdLoc) {
  1852. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  1853. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  1854. assert((DirectMember || IndirectMember) &&
  1855. "Member must be a FieldDecl or IndirectFieldDecl");
  1856. if (Args.DiagnoseUnexpandedParameterPack(*this))
  1857. return true;
  1858. if (Member->isInvalidDecl())
  1859. return true;
  1860. // Diagnose value-uses of fields to initialize themselves, e.g.
  1861. // foo(foo)
  1862. // where foo is not also a parameter to the constructor.
  1863. // TODO: implement -Wuninitialized and fold this into that framework.
  1864. for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
  1865. I != E; ++I) {
  1866. SourceLocation L;
  1867. Expr *Arg = *I;
  1868. if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
  1869. Arg = DIE->getInit();
  1870. if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
  1871. // FIXME: Return true in the case when other fields are used before being
  1872. // uninitialized. For example, let this field be the i'th field. When
  1873. // initializing the i'th field, throw a warning if any of the >= i'th
  1874. // fields are used, as they are not yet initialized.
  1875. // Right now we are only handling the case where the i'th field uses
  1876. // itself in its initializer.
  1877. Diag(L, diag::warn_field_is_uninit);
  1878. }
  1879. }
  1880. bool HasDependentArg = Args.isTypeDependent();
  1881. Expr *Init;
  1882. if (Member->getType()->isDependentType() || HasDependentArg) {
  1883. // Can't check initialization for a member of dependent type or when
  1884. // any of the arguments are type-dependent expressions.
  1885. Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
  1886. DiscardCleanupsInEvaluationContext();
  1887. } else {
  1888. // Initialize the member.
  1889. InitializedEntity MemberEntity =
  1890. DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
  1891. : InitializedEntity::InitializeMember(IndirectMember, 0);
  1892. InitializationKind Kind =
  1893. InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
  1894. Args.getEndLoc());
  1895. ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
  1896. if (MemberInit.isInvalid())
  1897. return true;
  1898. CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
  1899. // C++0x [class.base.init]p7:
  1900. // The initialization of each base and member constitutes a
  1901. // full-expression.
  1902. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  1903. if (MemberInit.isInvalid())
  1904. return true;
  1905. // If we are in a dependent context, template instantiation will
  1906. // perform this type-checking again. Just save the arguments that we
  1907. // received in a ParenListExpr.
  1908. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  1909. // of the information that we have about the member
  1910. // initializer. However, deconstructing the ASTs is a dicey process,
  1911. // and this approach is far more likely to get the corner cases right.
  1912. if (CurContext->isDependentContext()) {
  1913. Init = Args.CreateInitExpr(Context,
  1914. Member->getType().getNonReferenceType());
  1915. } else {
  1916. Init = MemberInit.get();
  1917. CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
  1918. }
  1919. }
  1920. if (DirectMember) {
  1921. return new (Context) CXXCtorInitializer(Context, DirectMember,
  1922. IdLoc, Args.getStartLoc(),
  1923. Init, Args.getEndLoc());
  1924. } else {
  1925. return new (Context) CXXCtorInitializer(Context, IndirectMember,
  1926. IdLoc, Args.getStartLoc(),
  1927. Init, Args.getEndLoc());
  1928. }
  1929. }
  1930. MemInitResult
  1931. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
  1932. const MultiInitializer &Args,
  1933. CXXRecordDecl *ClassDecl) {
  1934. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  1935. if (!LangOpts.CPlusPlus0x)
  1936. return Diag(NameLoc, diag::err_delegating_ctor)
  1937. << TInfo->getTypeLoc().getLocalSourceRange();
  1938. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  1939. // Initialize the object.
  1940. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  1941. QualType(ClassDecl->getTypeForDecl(), 0));
  1942. InitializationKind Kind =
  1943. InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
  1944. Args.getEndLoc());
  1945. ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
  1946. if (DelegationInit.isInvalid())
  1947. return true;
  1948. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  1949. "Delegating constructor with no target?");
  1950. CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
  1951. // C++0x [class.base.init]p7:
  1952. // The initialization of each base and member constitutes a
  1953. // full-expression.
  1954. DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
  1955. if (DelegationInit.isInvalid())
  1956. return true;
  1957. return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
  1958. DelegationInit.takeAs<Expr>(),
  1959. Args.getEndLoc());
  1960. }
  1961. MemInitResult
  1962. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  1963. const MultiInitializer &Args,
  1964. CXXRecordDecl *ClassDecl,
  1965. SourceLocation EllipsisLoc) {
  1966. bool HasDependentArg = Args.isTypeDependent();
  1967. SourceLocation BaseLoc
  1968. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  1969. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  1970. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  1971. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  1972. // C++ [class.base.init]p2:
  1973. // [...] Unless the mem-initializer-id names a nonstatic data
  1974. // member of the constructor's class or a direct or virtual base
  1975. // of that class, the mem-initializer is ill-formed. A
  1976. // mem-initializer-list can initialize a base class using any
  1977. // name that denotes that base class type.
  1978. bool Dependent = BaseType->isDependentType() || HasDependentArg;
  1979. if (EllipsisLoc.isValid()) {
  1980. // This is a pack expansion.
  1981. if (!BaseType->containsUnexpandedParameterPack()) {
  1982. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1983. << SourceRange(BaseLoc, Args.getEndLoc());
  1984. EllipsisLoc = SourceLocation();
  1985. }
  1986. } else {
  1987. // Check for any unexpanded parameter packs.
  1988. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  1989. return true;
  1990. if (Args.DiagnoseUnexpandedParameterPack(*this))
  1991. return true;
  1992. }
  1993. // Check for direct and virtual base classes.
  1994. const CXXBaseSpecifier *DirectBaseSpec = 0;
  1995. const CXXBaseSpecifier *VirtualBaseSpec = 0;
  1996. if (!Dependent) {
  1997. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  1998. BaseType))
  1999. return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
  2000. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  2001. VirtualBaseSpec);
  2002. // C++ [base.class.init]p2:
  2003. // Unless the mem-initializer-id names a nonstatic data member of the
  2004. // constructor's class or a direct or virtual base of that class, the
  2005. // mem-initializer is ill-formed.
  2006. if (!DirectBaseSpec && !VirtualBaseSpec) {
  2007. // If the class has any dependent bases, then it's possible that
  2008. // one of those types will resolve to the same type as
  2009. // BaseType. Therefore, just treat this as a dependent base
  2010. // class initialization. FIXME: Should we try to check the
  2011. // initialization anyway? It seems odd.
  2012. if (ClassDecl->hasAnyDependentBases())
  2013. Dependent = true;
  2014. else
  2015. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  2016. << BaseType << Context.getTypeDeclType(ClassDecl)
  2017. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2018. }
  2019. }
  2020. if (Dependent) {
  2021. // Can't check initialization for a base of dependent type or when
  2022. // any of the arguments are type-dependent expressions.
  2023. Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
  2024. DiscardCleanupsInEvaluationContext();
  2025. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  2026. /*IsVirtual=*/false,
  2027. Args.getStartLoc(), BaseInit,
  2028. Args.getEndLoc(), EllipsisLoc);
  2029. }
  2030. // C++ [base.class.init]p2:
  2031. // If a mem-initializer-id is ambiguous because it designates both
  2032. // a direct non-virtual base class and an inherited virtual base
  2033. // class, the mem-initializer is ill-formed.
  2034. if (DirectBaseSpec && VirtualBaseSpec)
  2035. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  2036. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2037. CXXBaseSpecifier *BaseSpec
  2038. = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
  2039. if (!BaseSpec)
  2040. BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
  2041. // Initialize the base.
  2042. InitializedEntity BaseEntity =
  2043. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  2044. InitializationKind Kind =
  2045. InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
  2046. Args.getEndLoc());
  2047. ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
  2048. if (BaseInit.isInvalid())
  2049. return true;
  2050. CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
  2051. // C++0x [class.base.init]p7:
  2052. // The initialization of each base and member constitutes a
  2053. // full-expression.
  2054. BaseInit = MaybeCreateExprWithCleanups(BaseInit);
  2055. if (BaseInit.isInvalid())
  2056. return true;
  2057. // If we are in a dependent context, template instantiation will
  2058. // perform this type-checking again. Just save the arguments that we
  2059. // received in a ParenListExpr.
  2060. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  2061. // of the information that we have about the base
  2062. // initializer. However, deconstructing the ASTs is a dicey process,
  2063. // and this approach is far more likely to get the corner cases right.
  2064. if (CurContext->isDependentContext())
  2065. BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
  2066. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  2067. BaseSpec->isVirtual(),
  2068. Args.getStartLoc(),
  2069. BaseInit.takeAs<Expr>(),
  2070. Args.getEndLoc(), EllipsisLoc);
  2071. }
  2072. // Create a static_cast\<T&&>(expr).
  2073. static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
  2074. QualType ExprType = E->getType();
  2075. QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
  2076. SourceLocation ExprLoc = E->getLocStart();
  2077. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  2078. TargetType, ExprLoc);
  2079. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  2080. SourceRange(ExprLoc, ExprLoc),
  2081. E->getSourceRange()).take();
  2082. }
  2083. /// ImplicitInitializerKind - How an implicit base or member initializer should
  2084. /// initialize its base or member.
  2085. enum ImplicitInitializerKind {
  2086. IIK_Default,
  2087. IIK_Copy,
  2088. IIK_Move
  2089. };
  2090. static bool
  2091. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  2092. ImplicitInitializerKind ImplicitInitKind,
  2093. CXXBaseSpecifier *BaseSpec,
  2094. bool IsInheritedVirtualBase,
  2095. CXXCtorInitializer *&CXXBaseInit) {
  2096. InitializedEntity InitEntity
  2097. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  2098. IsInheritedVirtualBase);
  2099. ExprResult BaseInit;
  2100. switch (ImplicitInitKind) {
  2101. case IIK_Default: {
  2102. InitializationKind InitKind
  2103. = InitializationKind::CreateDefault(Constructor->getLocation());
  2104. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
  2105. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
  2106. MultiExprArg(SemaRef, 0, 0));
  2107. break;
  2108. }
  2109. case IIK_Move:
  2110. case IIK_Copy: {
  2111. bool Moving = ImplicitInitKind == IIK_Move;
  2112. ParmVarDecl *Param = Constructor->getParamDecl(0);
  2113. QualType ParamType = Param->getType().getNonReferenceType();
  2114. Expr *CopyCtorArg =
  2115. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  2116. SourceLocation(), Param,
  2117. Constructor->getLocation(), ParamType,
  2118. VK_LValue, 0);
  2119. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  2120. // Cast to the base class to avoid ambiguities.
  2121. QualType ArgTy =
  2122. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  2123. ParamType.getQualifiers());
  2124. if (Moving) {
  2125. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  2126. }
  2127. CXXCastPath BasePath;
  2128. BasePath.push_back(BaseSpec);
  2129. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  2130. CK_UncheckedDerivedToBase,
  2131. Moving ? VK_XValue : VK_LValue,
  2132. &BasePath).take();
  2133. InitializationKind InitKind
  2134. = InitializationKind::CreateDirect(Constructor->getLocation(),
  2135. SourceLocation(), SourceLocation());
  2136. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
  2137. &CopyCtorArg, 1);
  2138. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
  2139. MultiExprArg(&CopyCtorArg, 1));
  2140. break;
  2141. }
  2142. }
  2143. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  2144. if (BaseInit.isInvalid())
  2145. return true;
  2146. CXXBaseInit =
  2147. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  2148. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  2149. SourceLocation()),
  2150. BaseSpec->isVirtual(),
  2151. SourceLocation(),
  2152. BaseInit.takeAs<Expr>(),
  2153. SourceLocation(),
  2154. SourceLocation());
  2155. return false;
  2156. }
  2157. static bool RefersToRValueRef(Expr *MemRef) {
  2158. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  2159. return Referenced->getType()->isRValueReferenceType();
  2160. }
  2161. static bool
  2162. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  2163. ImplicitInitializerKind ImplicitInitKind,
  2164. FieldDecl *Field, IndirectFieldDecl *Indirect,
  2165. CXXCtorInitializer *&CXXMemberInit) {
  2166. if (Field->isInvalidDecl())
  2167. return true;
  2168. SourceLocation Loc = Constructor->getLocation();
  2169. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  2170. bool Moving = ImplicitInitKind == IIK_Move;
  2171. ParmVarDecl *Param = Constructor->getParamDecl(0);
  2172. QualType ParamType = Param->getType().getNonReferenceType();
  2173. // Suppress copying zero-width bitfields.
  2174. if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
  2175. return false;
  2176. Expr *MemberExprBase =
  2177. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  2178. SourceLocation(), Param,
  2179. Loc, ParamType, VK_LValue, 0);
  2180. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  2181. if (Moving) {
  2182. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  2183. }
  2184. // Build a reference to this field within the parameter.
  2185. CXXScopeSpec SS;
  2186. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  2187. Sema::LookupMemberName);
  2188. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  2189. : cast<ValueDecl>(Field), AS_public);
  2190. MemberLookup.resolveKind();
  2191. ExprResult CtorArg
  2192. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  2193. ParamType, Loc,
  2194. /*IsArrow=*/false,
  2195. SS,
  2196. /*TemplateKWLoc=*/SourceLocation(),
  2197. /*FirstQualifierInScope=*/0,
  2198. MemberLookup,
  2199. /*TemplateArgs=*/0);
  2200. if (CtorArg.isInvalid())
  2201. return true;
  2202. // C++11 [class.copy]p15:
  2203. // - if a member m has rvalue reference type T&&, it is direct-initialized
  2204. // with static_cast<T&&>(x.m);
  2205. if (RefersToRValueRef(CtorArg.get())) {
  2206. CtorArg = CastForMoving(SemaRef, CtorArg.take());
  2207. }
  2208. // When the field we are copying is an array, create index variables for
  2209. // each dimension of the array. We use these index variables to subscript
  2210. // the source array, and other clients (e.g., CodeGen) will perform the
  2211. // necessary iteration with these index variables.
  2212. SmallVector<VarDecl *, 4> IndexVariables;
  2213. QualType BaseType = Field->getType();
  2214. QualType SizeType = SemaRef.Context.getSizeType();
  2215. bool InitializingArray = false;
  2216. while (const ConstantArrayType *Array
  2217. = SemaRef.Context.getAsConstantArrayType(BaseType)) {
  2218. InitializingArray = true;
  2219. // Create the iteration variable for this array index.
  2220. IdentifierInfo *IterationVarName = 0;
  2221. {
  2222. SmallString<8> Str;
  2223. llvm::raw_svector_ostream OS(Str);
  2224. OS << "__i" << IndexVariables.size();
  2225. IterationVarName = &SemaRef.Context.Idents.get(OS.str());
  2226. }
  2227. VarDecl *IterationVar
  2228. = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
  2229. IterationVarName, SizeType,
  2230. SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  2231. SC_None, SC_None);
  2232. IndexVariables.push_back(IterationVar);
  2233. // Create a reference to the iteration variable.
  2234. ExprResult IterationVarRef
  2235. = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
  2236. assert(!IterationVarRef.isInvalid() &&
  2237. "Reference to invented variable cannot fail!");
  2238. IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
  2239. assert(!IterationVarRef.isInvalid() &&
  2240. "Conversion of invented variable cannot fail!");
  2241. // Subscript the array with this iteration variable.
  2242. CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
  2243. IterationVarRef.take(),
  2244. Loc);
  2245. if (CtorArg.isInvalid())
  2246. return true;
  2247. BaseType = Array->getElementType();
  2248. }
  2249. // The array subscript expression is an lvalue, which is wrong for moving.
  2250. if (Moving && InitializingArray)
  2251. CtorArg = CastForMoving(SemaRef, CtorArg.take());
  2252. // Construct the entity that we will be initializing. For an array, this
  2253. // will be first element in the array, which may require several levels
  2254. // of array-subscript entities.
  2255. SmallVector<InitializedEntity, 4> Entities;
  2256. Entities.reserve(1 + IndexVariables.size());
  2257. if (Indirect)
  2258. Entities.push_back(InitializedEntity::InitializeMember(Indirect));
  2259. else
  2260. Entities.push_back(InitializedEntity::InitializeMember(Field));
  2261. for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
  2262. Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
  2263. 0,
  2264. Entities.back()));
  2265. // Direct-initialize to use the copy constructor.
  2266. InitializationKind InitKind =
  2267. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  2268. Expr *CtorArgE = CtorArg.takeAs<Expr>();
  2269. InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
  2270. &CtorArgE, 1);
  2271. ExprResult MemberInit
  2272. = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
  2273. MultiExprArg(&CtorArgE, 1));
  2274. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  2275. if (MemberInit.isInvalid())
  2276. return true;
  2277. if (Indirect) {
  2278. assert(IndexVariables.size() == 0 &&
  2279. "Indirect field improperly initialized");
  2280. CXXMemberInit
  2281. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
  2282. Loc, Loc,
  2283. MemberInit.takeAs<Expr>(),
  2284. Loc);
  2285. } else
  2286. CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
  2287. Loc, MemberInit.takeAs<Expr>(),
  2288. Loc,
  2289. IndexVariables.data(),
  2290. IndexVariables.size());
  2291. return false;
  2292. }
  2293. assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
  2294. QualType FieldBaseElementType =
  2295. SemaRef.Context.getBaseElementType(Field->getType());
  2296. if (FieldBaseElementType->isRecordType()) {
  2297. InitializedEntity InitEntity
  2298. = Indirect? InitializedEntity::InitializeMember(Indirect)
  2299. : InitializedEntity::InitializeMember(Field);
  2300. InitializationKind InitKind =
  2301. InitializationKind::CreateDefault(Loc);
  2302. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
  2303. ExprResult MemberInit =
  2304. InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
  2305. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  2306. if (MemberInit.isInvalid())
  2307. return true;
  2308. if (Indirect)
  2309. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  2310. Indirect, Loc,
  2311. Loc,
  2312. MemberInit.get(),
  2313. Loc);
  2314. else
  2315. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  2316. Field, Loc, Loc,
  2317. MemberInit.get(),
  2318. Loc);
  2319. return false;
  2320. }
  2321. if (!Field->getParent()->isUnion()) {
  2322. if (FieldBaseElementType->isReferenceType()) {
  2323. SemaRef.Diag(Constructor->getLocation(),
  2324. diag::err_uninitialized_member_in_ctor)
  2325. << (int)Constructor->isImplicit()
  2326. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  2327. << 0 << Field->getDeclName();
  2328. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  2329. return true;
  2330. }
  2331. if (FieldBaseElementType.isConstQualified()) {
  2332. SemaRef.Diag(Constructor->getLocation(),
  2333. diag::err_uninitialized_member_in_ctor)
  2334. << (int)Constructor->isImplicit()
  2335. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  2336. << 1 << Field->getDeclName();
  2337. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  2338. return true;
  2339. }
  2340. }
  2341. if (SemaRef.getLangOptions().ObjCAutoRefCount &&
  2342. FieldBaseElementType->isObjCRetainableType() &&
  2343. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
  2344. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
  2345. // Instant objects:
  2346. // Default-initialize Objective-C pointers to NULL.
  2347. CXXMemberInit
  2348. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  2349. Loc, Loc,
  2350. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  2351. Loc);
  2352. return false;
  2353. }
  2354. // Nothing to initialize.
  2355. CXXMemberInit = 0;
  2356. return false;
  2357. }
  2358. namespace {
  2359. struct BaseAndFieldInfo {
  2360. Sema &S;
  2361. CXXConstructorDecl *Ctor;
  2362. bool AnyErrorsInInits;
  2363. ImplicitInitializerKind IIK;
  2364. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  2365. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  2366. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  2367. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  2368. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  2369. if (Generated && Ctor->isCopyConstructor())
  2370. IIK = IIK_Copy;
  2371. else if (Generated && Ctor->isMoveConstructor())
  2372. IIK = IIK_Move;
  2373. else
  2374. IIK = IIK_Default;
  2375. }
  2376. bool isImplicitCopyOrMove() const {
  2377. switch (IIK) {
  2378. case IIK_Copy:
  2379. case IIK_Move:
  2380. return true;
  2381. case IIK_Default:
  2382. return false;
  2383. }
  2384. llvm_unreachable("Invalid ImplicitInitializerKind!");
  2385. }
  2386. };
  2387. }
  2388. /// \brief Determine whether the given indirect field declaration is somewhere
  2389. /// within an anonymous union.
  2390. static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
  2391. for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
  2392. CEnd = F->chain_end();
  2393. C != CEnd; ++C)
  2394. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
  2395. if (Record->isUnion())
  2396. return true;
  2397. return false;
  2398. }
  2399. /// \brief Determine whether the given type is an incomplete or zero-lenfgth
  2400. /// array type.
  2401. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  2402. if (T->isIncompleteArrayType())
  2403. return true;
  2404. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  2405. if (!ArrayT->getSize())
  2406. return true;
  2407. T = ArrayT->getElementType();
  2408. }
  2409. return false;
  2410. }
  2411. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  2412. FieldDecl *Field,
  2413. IndirectFieldDecl *Indirect = 0) {
  2414. // Overwhelmingly common case: we have a direct initializer for this field.
  2415. if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
  2416. Info.AllToInit.push_back(Init);
  2417. return false;
  2418. }
  2419. // C++0x [class.base.init]p8: if the entity is a non-static data member that
  2420. // has a brace-or-equal-initializer, the entity is initialized as specified
  2421. // in [dcl.init].
  2422. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  2423. CXXCtorInitializer *Init;
  2424. if (Indirect)
  2425. Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
  2426. SourceLocation(),
  2427. SourceLocation(), 0,
  2428. SourceLocation());
  2429. else
  2430. Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  2431. SourceLocation(),
  2432. SourceLocation(), 0,
  2433. SourceLocation());
  2434. Info.AllToInit.push_back(Init);
  2435. return false;
  2436. }
  2437. // Don't build an implicit initializer for union members if none was
  2438. // explicitly specified.
  2439. if (Field->getParent()->isUnion() ||
  2440. (Indirect && isWithinAnonymousUnion(Indirect)))
  2441. return false;
  2442. // Don't initialize incomplete or zero-length arrays.
  2443. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  2444. return false;
  2445. // Don't try to build an implicit initializer if there were semantic
  2446. // errors in any of the initializers (and therefore we might be
  2447. // missing some that the user actually wrote).
  2448. if (Info.AnyErrorsInInits || Field->isInvalidDecl())
  2449. return false;
  2450. CXXCtorInitializer *Init = 0;
  2451. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  2452. Indirect, Init))
  2453. return true;
  2454. if (Init)
  2455. Info.AllToInit.push_back(Init);
  2456. return false;
  2457. }
  2458. bool
  2459. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  2460. CXXCtorInitializer *Initializer) {
  2461. assert(Initializer->isDelegatingInitializer());
  2462. Constructor->setNumCtorInitializers(1);
  2463. CXXCtorInitializer **initializer =
  2464. new (Context) CXXCtorInitializer*[1];
  2465. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  2466. Constructor->setCtorInitializers(initializer);
  2467. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  2468. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  2469. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  2470. }
  2471. DelegatingCtorDecls.push_back(Constructor);
  2472. return false;
  2473. }
  2474. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
  2475. CXXCtorInitializer **Initializers,
  2476. unsigned NumInitializers,
  2477. bool AnyErrors) {
  2478. if (Constructor->isDependentContext()) {
  2479. // Just store the initializers as written, they will be checked during
  2480. // instantiation.
  2481. if (NumInitializers > 0) {
  2482. Constructor->setNumCtorInitializers(NumInitializers);
  2483. CXXCtorInitializer **baseOrMemberInitializers =
  2484. new (Context) CXXCtorInitializer*[NumInitializers];
  2485. memcpy(baseOrMemberInitializers, Initializers,
  2486. NumInitializers * sizeof(CXXCtorInitializer*));
  2487. Constructor->setCtorInitializers(baseOrMemberInitializers);
  2488. }
  2489. return false;
  2490. }
  2491. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  2492. // We need to build the initializer AST according to order of construction
  2493. // and not what user specified in the Initializers list.
  2494. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  2495. if (!ClassDecl)
  2496. return true;
  2497. bool HadError = false;
  2498. for (unsigned i = 0; i < NumInitializers; i++) {
  2499. CXXCtorInitializer *Member = Initializers[i];
  2500. if (Member->isBaseInitializer())
  2501. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  2502. else
  2503. Info.AllBaseFields[Member->getAnyMember()] = Member;
  2504. }
  2505. // Keep track of the direct virtual bases.
  2506. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  2507. for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
  2508. E = ClassDecl->bases_end(); I != E; ++I) {
  2509. if (I->isVirtual())
  2510. DirectVBases.insert(I);
  2511. }
  2512. // Push virtual bases before others.
  2513. for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
  2514. E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
  2515. if (CXXCtorInitializer *Value
  2516. = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
  2517. Info.AllToInit.push_back(Value);
  2518. } else if (!AnyErrors) {
  2519. bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
  2520. CXXCtorInitializer *CXXBaseInit;
  2521. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  2522. VBase, IsInheritedVirtualBase,
  2523. CXXBaseInit)) {
  2524. HadError = true;
  2525. continue;
  2526. }
  2527. Info.AllToInit.push_back(CXXBaseInit);
  2528. }
  2529. }
  2530. // Non-virtual bases.
  2531. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  2532. E = ClassDecl->bases_end(); Base != E; ++Base) {
  2533. // Virtuals are in the virtual base list and already constructed.
  2534. if (Base->isVirtual())
  2535. continue;
  2536. if (CXXCtorInitializer *Value
  2537. = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
  2538. Info.AllToInit.push_back(Value);
  2539. } else if (!AnyErrors) {
  2540. CXXCtorInitializer *CXXBaseInit;
  2541. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  2542. Base, /*IsInheritedVirtualBase=*/false,
  2543. CXXBaseInit)) {
  2544. HadError = true;
  2545. continue;
  2546. }
  2547. Info.AllToInit.push_back(CXXBaseInit);
  2548. }
  2549. }
  2550. // Fields.
  2551. for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
  2552. MemEnd = ClassDecl->decls_end();
  2553. Mem != MemEnd; ++Mem) {
  2554. if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
  2555. // C++ [class.bit]p2:
  2556. // A declaration for a bit-field that omits the identifier declares an
  2557. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  2558. // initialized.
  2559. if (F->isUnnamedBitfield())
  2560. continue;
  2561. // If we're not generating the implicit copy/move constructor, then we'll
  2562. // handle anonymous struct/union fields based on their individual
  2563. // indirect fields.
  2564. if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
  2565. continue;
  2566. if (CollectFieldInitializer(*this, Info, F))
  2567. HadError = true;
  2568. continue;
  2569. }
  2570. // Beyond this point, we only consider default initialization.
  2571. if (Info.IIK != IIK_Default)
  2572. continue;
  2573. if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
  2574. if (F->getType()->isIncompleteArrayType()) {
  2575. assert(ClassDecl->hasFlexibleArrayMember() &&
  2576. "Incomplete array type is not valid");
  2577. continue;
  2578. }
  2579. // Initialize each field of an anonymous struct individually.
  2580. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  2581. HadError = true;
  2582. continue;
  2583. }
  2584. }
  2585. NumInitializers = Info.AllToInit.size();
  2586. if (NumInitializers > 0) {
  2587. Constructor->setNumCtorInitializers(NumInitializers);
  2588. CXXCtorInitializer **baseOrMemberInitializers =
  2589. new (Context) CXXCtorInitializer*[NumInitializers];
  2590. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  2591. NumInitializers * sizeof(CXXCtorInitializer*));
  2592. Constructor->setCtorInitializers(baseOrMemberInitializers);
  2593. // Constructors implicitly reference the base and member
  2594. // destructors.
  2595. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  2596. Constructor->getParent());
  2597. }
  2598. return HadError;
  2599. }
  2600. static void *GetKeyForTopLevelField(FieldDecl *Field) {
  2601. // For anonymous unions, use the class declaration as the key.
  2602. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  2603. if (RT->getDecl()->isAnonymousStructOrUnion())
  2604. return static_cast<void *>(RT->getDecl());
  2605. }
  2606. return static_cast<void *>(Field);
  2607. }
  2608. static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  2609. return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
  2610. }
  2611. static void *GetKeyForMember(ASTContext &Context,
  2612. CXXCtorInitializer *Member) {
  2613. if (!Member->isAnyMemberInitializer())
  2614. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  2615. // For fields injected into the class via declaration of an anonymous union,
  2616. // use its anonymous union class declaration as the unique key.
  2617. FieldDecl *Field = Member->getAnyMember();
  2618. // If the field is a member of an anonymous struct or union, our key
  2619. // is the anonymous record decl that's a direct child of the class.
  2620. RecordDecl *RD = Field->getParent();
  2621. if (RD->isAnonymousStructOrUnion()) {
  2622. while (true) {
  2623. RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
  2624. if (Parent->isAnonymousStructOrUnion())
  2625. RD = Parent;
  2626. else
  2627. break;
  2628. }
  2629. return static_cast<void *>(RD);
  2630. }
  2631. return static_cast<void *>(Field);
  2632. }
  2633. static void
  2634. DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
  2635. const CXXConstructorDecl *Constructor,
  2636. CXXCtorInitializer **Inits,
  2637. unsigned NumInits) {
  2638. if (Constructor->getDeclContext()->isDependentContext())
  2639. return;
  2640. // Don't check initializers order unless the warning is enabled at the
  2641. // location of at least one initializer.
  2642. bool ShouldCheckOrder = false;
  2643. for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
  2644. CXXCtorInitializer *Init = Inits[InitIndex];
  2645. if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
  2646. Init->getSourceLocation())
  2647. != DiagnosticsEngine::Ignored) {
  2648. ShouldCheckOrder = true;
  2649. break;
  2650. }
  2651. }
  2652. if (!ShouldCheckOrder)
  2653. return;
  2654. // Build the list of bases and members in the order that they'll
  2655. // actually be initialized. The explicit initializers should be in
  2656. // this same order but may be missing things.
  2657. SmallVector<const void*, 32> IdealInitKeys;
  2658. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  2659. // 1. Virtual bases.
  2660. for (CXXRecordDecl::base_class_const_iterator VBase =
  2661. ClassDecl->vbases_begin(),
  2662. E = ClassDecl->vbases_end(); VBase != E; ++VBase)
  2663. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
  2664. // 2. Non-virtual bases.
  2665. for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
  2666. E = ClassDecl->bases_end(); Base != E; ++Base) {
  2667. if (Base->isVirtual())
  2668. continue;
  2669. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
  2670. }
  2671. // 3. Direct fields.
  2672. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  2673. E = ClassDecl->field_end(); Field != E; ++Field) {
  2674. if (Field->isUnnamedBitfield())
  2675. continue;
  2676. IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
  2677. }
  2678. unsigned NumIdealInits = IdealInitKeys.size();
  2679. unsigned IdealIndex = 0;
  2680. CXXCtorInitializer *PrevInit = 0;
  2681. for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
  2682. CXXCtorInitializer *Init = Inits[InitIndex];
  2683. void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  2684. // Scan forward to try to find this initializer in the idealized
  2685. // initializers list.
  2686. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  2687. if (InitKey == IdealInitKeys[IdealIndex])
  2688. break;
  2689. // If we didn't find this initializer, it must be because we
  2690. // scanned past it on a previous iteration. That can only
  2691. // happen if we're out of order; emit a warning.
  2692. if (IdealIndex == NumIdealInits && PrevInit) {
  2693. Sema::SemaDiagnosticBuilder D =
  2694. SemaRef.Diag(PrevInit->getSourceLocation(),
  2695. diag::warn_initializer_out_of_order);
  2696. if (PrevInit->isAnyMemberInitializer())
  2697. D << 0 << PrevInit->getAnyMember()->getDeclName();
  2698. else
  2699. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  2700. if (Init->isAnyMemberInitializer())
  2701. D << 0 << Init->getAnyMember()->getDeclName();
  2702. else
  2703. D << 1 << Init->getTypeSourceInfo()->getType();
  2704. // Move back to the initializer's location in the ideal list.
  2705. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  2706. if (InitKey == IdealInitKeys[IdealIndex])
  2707. break;
  2708. assert(IdealIndex != NumIdealInits &&
  2709. "initializer not found in initializer list");
  2710. }
  2711. PrevInit = Init;
  2712. }
  2713. }
  2714. namespace {
  2715. bool CheckRedundantInit(Sema &S,
  2716. CXXCtorInitializer *Init,
  2717. CXXCtorInitializer *&PrevInit) {
  2718. if (!PrevInit) {
  2719. PrevInit = Init;
  2720. return false;
  2721. }
  2722. if (FieldDecl *Field = Init->getMember())
  2723. S.Diag(Init->getSourceLocation(),
  2724. diag::err_multiple_mem_initialization)
  2725. << Field->getDeclName()
  2726. << Init->getSourceRange();
  2727. else {
  2728. const Type *BaseClass = Init->getBaseClass();
  2729. assert(BaseClass && "neither field nor base");
  2730. S.Diag(Init->getSourceLocation(),
  2731. diag::err_multiple_base_initialization)
  2732. << QualType(BaseClass, 0)
  2733. << Init->getSourceRange();
  2734. }
  2735. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  2736. << 0 << PrevInit->getSourceRange();
  2737. return true;
  2738. }
  2739. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  2740. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  2741. bool CheckRedundantUnionInit(Sema &S,
  2742. CXXCtorInitializer *Init,
  2743. RedundantUnionMap &Unions) {
  2744. FieldDecl *Field = Init->getAnyMember();
  2745. RecordDecl *Parent = Field->getParent();
  2746. NamedDecl *Child = Field;
  2747. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  2748. if (Parent->isUnion()) {
  2749. UnionEntry &En = Unions[Parent];
  2750. if (En.first && En.first != Child) {
  2751. S.Diag(Init->getSourceLocation(),
  2752. diag::err_multiple_mem_union_initialization)
  2753. << Field->getDeclName()
  2754. << Init->getSourceRange();
  2755. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  2756. << 0 << En.second->getSourceRange();
  2757. return true;
  2758. }
  2759. if (!En.first) {
  2760. En.first = Child;
  2761. En.second = Init;
  2762. }
  2763. if (!Parent->isAnonymousStructOrUnion())
  2764. return false;
  2765. }
  2766. Child = Parent;
  2767. Parent = cast<RecordDecl>(Parent->getDeclContext());
  2768. }
  2769. return false;
  2770. }
  2771. }
  2772. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  2773. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  2774. SourceLocation ColonLoc,
  2775. CXXCtorInitializer **meminits,
  2776. unsigned NumMemInits,
  2777. bool AnyErrors) {
  2778. if (!ConstructorDecl)
  2779. return;
  2780. AdjustDeclIfTemplate(ConstructorDecl);
  2781. CXXConstructorDecl *Constructor
  2782. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  2783. if (!Constructor) {
  2784. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  2785. return;
  2786. }
  2787. CXXCtorInitializer **MemInits =
  2788. reinterpret_cast<CXXCtorInitializer **>(meminits);
  2789. // Mapping for the duplicate initializers check.
  2790. // For member initializers, this is keyed with a FieldDecl*.
  2791. // For base initializers, this is keyed with a Type*.
  2792. llvm::DenseMap<void*, CXXCtorInitializer *> Members;
  2793. // Mapping for the inconsistent anonymous-union initializers check.
  2794. RedundantUnionMap MemberUnions;
  2795. bool HadError = false;
  2796. for (unsigned i = 0; i < NumMemInits; i++) {
  2797. CXXCtorInitializer *Init = MemInits[i];
  2798. // Set the source order index.
  2799. Init->setSourceOrder(i);
  2800. if (Init->isAnyMemberInitializer()) {
  2801. FieldDecl *Field = Init->getAnyMember();
  2802. if (CheckRedundantInit(*this, Init, Members[Field]) ||
  2803. CheckRedundantUnionInit(*this, Init, MemberUnions))
  2804. HadError = true;
  2805. } else if (Init->isBaseInitializer()) {
  2806. void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
  2807. if (CheckRedundantInit(*this, Init, Members[Key]))
  2808. HadError = true;
  2809. } else {
  2810. assert(Init->isDelegatingInitializer());
  2811. // This must be the only initializer
  2812. if (i != 0 || NumMemInits > 1) {
  2813. Diag(MemInits[0]->getSourceLocation(),
  2814. diag::err_delegating_initializer_alone)
  2815. << MemInits[0]->getSourceRange();
  2816. HadError = true;
  2817. // We will treat this as being the only initializer.
  2818. }
  2819. SetDelegatingInitializer(Constructor, MemInits[i]);
  2820. // Return immediately as the initializer is set.
  2821. return;
  2822. }
  2823. }
  2824. if (HadError)
  2825. return;
  2826. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
  2827. SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
  2828. }
  2829. void
  2830. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  2831. CXXRecordDecl *ClassDecl) {
  2832. // Ignore dependent contexts. Also ignore unions, since their members never
  2833. // have destructors implicitly called.
  2834. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  2835. return;
  2836. // FIXME: all the access-control diagnostics are positioned on the
  2837. // field/base declaration. That's probably good; that said, the
  2838. // user might reasonably want to know why the destructor is being
  2839. // emitted, and we currently don't say.
  2840. // Non-static data members.
  2841. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  2842. E = ClassDecl->field_end(); I != E; ++I) {
  2843. FieldDecl *Field = *I;
  2844. if (Field->isInvalidDecl())
  2845. continue;
  2846. // Don't destroy incomplete or zero-length arrays.
  2847. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  2848. continue;
  2849. QualType FieldType = Context.getBaseElementType(Field->getType());
  2850. const RecordType* RT = FieldType->getAs<RecordType>();
  2851. if (!RT)
  2852. continue;
  2853. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  2854. if (FieldClassDecl->isInvalidDecl())
  2855. continue;
  2856. if (FieldClassDecl->hasTrivialDestructor())
  2857. continue;
  2858. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  2859. assert(Dtor && "No dtor found for FieldClassDecl!");
  2860. CheckDestructorAccess(Field->getLocation(), Dtor,
  2861. PDiag(diag::err_access_dtor_field)
  2862. << Field->getDeclName()
  2863. << FieldType);
  2864. MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
  2865. }
  2866. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  2867. // Bases.
  2868. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  2869. E = ClassDecl->bases_end(); Base != E; ++Base) {
  2870. // Bases are always records in a well-formed non-dependent class.
  2871. const RecordType *RT = Base->getType()->getAs<RecordType>();
  2872. // Remember direct virtual bases.
  2873. if (Base->isVirtual())
  2874. DirectVirtualBases.insert(RT);
  2875. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  2876. // If our base class is invalid, we probably can't get its dtor anyway.
  2877. if (BaseClassDecl->isInvalidDecl())
  2878. continue;
  2879. // Ignore trivial destructors.
  2880. if (BaseClassDecl->hasTrivialDestructor())
  2881. continue;
  2882. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  2883. assert(Dtor && "No dtor found for BaseClassDecl!");
  2884. // FIXME: caret should be on the start of the class name
  2885. CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
  2886. PDiag(diag::err_access_dtor_base)
  2887. << Base->getType()
  2888. << Base->getSourceRange());
  2889. MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
  2890. }
  2891. // Virtual bases.
  2892. for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
  2893. E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
  2894. // Bases are always records in a well-formed non-dependent class.
  2895. const RecordType *RT = VBase->getType()->getAs<RecordType>();
  2896. // Ignore direct virtual bases.
  2897. if (DirectVirtualBases.count(RT))
  2898. continue;
  2899. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  2900. // If our base class is invalid, we probably can't get its dtor anyway.
  2901. if (BaseClassDecl->isInvalidDecl())
  2902. continue;
  2903. // Ignore trivial destructors.
  2904. if (BaseClassDecl->hasTrivialDestructor())
  2905. continue;
  2906. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  2907. assert(Dtor && "No dtor found for BaseClassDecl!");
  2908. CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
  2909. PDiag(diag::err_access_dtor_vbase)
  2910. << VBase->getType());
  2911. MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
  2912. }
  2913. }
  2914. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  2915. if (!CDtorDecl)
  2916. return;
  2917. if (CXXConstructorDecl *Constructor
  2918. = dyn_cast<CXXConstructorDecl>(CDtorDecl))
  2919. SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
  2920. }
  2921. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  2922. unsigned DiagID, AbstractDiagSelID SelID) {
  2923. if (SelID == -1)
  2924. return RequireNonAbstractType(Loc, T, PDiag(DiagID));
  2925. else
  2926. return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
  2927. }
  2928. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  2929. const PartialDiagnostic &PD) {
  2930. if (!getLangOptions().CPlusPlus)
  2931. return false;
  2932. if (const ArrayType *AT = Context.getAsArrayType(T))
  2933. return RequireNonAbstractType(Loc, AT->getElementType(), PD);
  2934. if (const PointerType *PT = T->getAs<PointerType>()) {
  2935. // Find the innermost pointer type.
  2936. while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
  2937. PT = T;
  2938. if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
  2939. return RequireNonAbstractType(Loc, AT->getElementType(), PD);
  2940. }
  2941. const RecordType *RT = T->getAs<RecordType>();
  2942. if (!RT)
  2943. return false;
  2944. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  2945. // We can't answer whether something is abstract until it has a
  2946. // definition. If it's currently being defined, we'll walk back
  2947. // over all the declarations when we have a full definition.
  2948. const CXXRecordDecl *Def = RD->getDefinition();
  2949. if (!Def || Def->isBeingDefined())
  2950. return false;
  2951. if (!RD->isAbstract())
  2952. return false;
  2953. Diag(Loc, PD) << RD->getDeclName();
  2954. DiagnoseAbstractType(RD);
  2955. return true;
  2956. }
  2957. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  2958. // Check if we've already emitted the list of pure virtual functions
  2959. // for this class.
  2960. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  2961. return;
  2962. CXXFinalOverriderMap FinalOverriders;
  2963. RD->getFinalOverriders(FinalOverriders);
  2964. // Keep a set of seen pure methods so we won't diagnose the same method
  2965. // more than once.
  2966. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  2967. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  2968. MEnd = FinalOverriders.end();
  2969. M != MEnd;
  2970. ++M) {
  2971. for (OverridingMethods::iterator SO = M->second.begin(),
  2972. SOEnd = M->second.end();
  2973. SO != SOEnd; ++SO) {
  2974. // C++ [class.abstract]p4:
  2975. // A class is abstract if it contains or inherits at least one
  2976. // pure virtual function for which the final overrider is pure
  2977. // virtual.
  2978. //
  2979. if (SO->second.size() != 1)
  2980. continue;
  2981. if (!SO->second.front().Method->isPure())
  2982. continue;
  2983. if (!SeenPureMethods.insert(SO->second.front().Method))
  2984. continue;
  2985. Diag(SO->second.front().Method->getLocation(),
  2986. diag::note_pure_virtual_function)
  2987. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  2988. }
  2989. }
  2990. if (!PureVirtualClassDiagSet)
  2991. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  2992. PureVirtualClassDiagSet->insert(RD);
  2993. }
  2994. namespace {
  2995. struct AbstractUsageInfo {
  2996. Sema &S;
  2997. CXXRecordDecl *Record;
  2998. CanQualType AbstractType;
  2999. bool Invalid;
  3000. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  3001. : S(S), Record(Record),
  3002. AbstractType(S.Context.getCanonicalType(
  3003. S.Context.getTypeDeclType(Record))),
  3004. Invalid(false) {}
  3005. void DiagnoseAbstractType() {
  3006. if (Invalid) return;
  3007. S.DiagnoseAbstractType(Record);
  3008. Invalid = true;
  3009. }
  3010. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  3011. };
  3012. struct CheckAbstractUsage {
  3013. AbstractUsageInfo &Info;
  3014. const NamedDecl *Ctx;
  3015. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  3016. : Info(Info), Ctx(Ctx) {}
  3017. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3018. switch (TL.getTypeLocClass()) {
  3019. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  3020. #define TYPELOC(CLASS, PARENT) \
  3021. case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
  3022. #include "clang/AST/TypeLocNodes.def"
  3023. }
  3024. }
  3025. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3026. Visit(TL.getResultLoc(), Sema::AbstractReturnType);
  3027. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  3028. if (!TL.getArg(I))
  3029. continue;
  3030. TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
  3031. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  3032. }
  3033. }
  3034. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3035. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  3036. }
  3037. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3038. // Visit the type parameters from a permissive context.
  3039. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  3040. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  3041. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  3042. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  3043. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  3044. // TODO: other template argument types?
  3045. }
  3046. }
  3047. // Visit pointee types from a permissive context.
  3048. #define CheckPolymorphic(Type) \
  3049. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  3050. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  3051. }
  3052. CheckPolymorphic(PointerTypeLoc)
  3053. CheckPolymorphic(ReferenceTypeLoc)
  3054. CheckPolymorphic(MemberPointerTypeLoc)
  3055. CheckPolymorphic(BlockPointerTypeLoc)
  3056. CheckPolymorphic(AtomicTypeLoc)
  3057. /// Handle all the types we haven't given a more specific
  3058. /// implementation for above.
  3059. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3060. // Every other kind of type that we haven't called out already
  3061. // that has an inner type is either (1) sugar or (2) contains that
  3062. // inner type in some way as a subobject.
  3063. if (TypeLoc Next = TL.getNextTypeLoc())
  3064. return Visit(Next, Sel);
  3065. // If there's no inner type and we're in a permissive context,
  3066. // don't diagnose.
  3067. if (Sel == Sema::AbstractNone) return;
  3068. // Check whether the type matches the abstract type.
  3069. QualType T = TL.getType();
  3070. if (T->isArrayType()) {
  3071. Sel = Sema::AbstractArrayType;
  3072. T = Info.S.Context.getBaseElementType(T);
  3073. }
  3074. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  3075. if (CT != Info.AbstractType) return;
  3076. // It matched; do some magic.
  3077. if (Sel == Sema::AbstractArrayType) {
  3078. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  3079. << T << TL.getSourceRange();
  3080. } else {
  3081. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  3082. << Sel << T << TL.getSourceRange();
  3083. }
  3084. Info.DiagnoseAbstractType();
  3085. }
  3086. };
  3087. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  3088. Sema::AbstractDiagSelID Sel) {
  3089. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  3090. }
  3091. }
  3092. /// Check for invalid uses of an abstract type in a method declaration.
  3093. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  3094. CXXMethodDecl *MD) {
  3095. // No need to do the check on definitions, which require that
  3096. // the return/param types be complete.
  3097. if (MD->doesThisDeclarationHaveABody())
  3098. return;
  3099. // For safety's sake, just ignore it if we don't have type source
  3100. // information. This should never happen for non-implicit methods,
  3101. // but...
  3102. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  3103. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  3104. }
  3105. /// Check for invalid uses of an abstract type within a class definition.
  3106. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  3107. CXXRecordDecl *RD) {
  3108. for (CXXRecordDecl::decl_iterator
  3109. I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
  3110. Decl *D = *I;
  3111. if (D->isImplicit()) continue;
  3112. // Methods and method templates.
  3113. if (isa<CXXMethodDecl>(D)) {
  3114. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  3115. } else if (isa<FunctionTemplateDecl>(D)) {
  3116. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  3117. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  3118. // Fields and static variables.
  3119. } else if (isa<FieldDecl>(D)) {
  3120. FieldDecl *FD = cast<FieldDecl>(D);
  3121. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  3122. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  3123. } else if (isa<VarDecl>(D)) {
  3124. VarDecl *VD = cast<VarDecl>(D);
  3125. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  3126. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  3127. // Nested classes and class templates.
  3128. } else if (isa<CXXRecordDecl>(D)) {
  3129. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  3130. } else if (isa<ClassTemplateDecl>(D)) {
  3131. CheckAbstractClassUsage(Info,
  3132. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  3133. }
  3134. }
  3135. }
  3136. /// \brief Perform semantic checks on a class definition that has been
  3137. /// completing, introducing implicitly-declared members, checking for
  3138. /// abstract types, etc.
  3139. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  3140. if (!Record)
  3141. return;
  3142. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  3143. AbstractUsageInfo Info(*this, Record);
  3144. CheckAbstractClassUsage(Info, Record);
  3145. }
  3146. // If this is not an aggregate type and has no user-declared constructor,
  3147. // complain about any non-static data members of reference or const scalar
  3148. // type, since they will never get initializers.
  3149. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  3150. !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
  3151. bool Complained = false;
  3152. for (RecordDecl::field_iterator F = Record->field_begin(),
  3153. FEnd = Record->field_end();
  3154. F != FEnd; ++F) {
  3155. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  3156. continue;
  3157. if (F->getType()->isReferenceType() ||
  3158. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  3159. if (!Complained) {
  3160. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  3161. << Record->getTagKind() << Record;
  3162. Complained = true;
  3163. }
  3164. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  3165. << F->getType()->isReferenceType()
  3166. << F->getDeclName();
  3167. }
  3168. }
  3169. }
  3170. if (Record->isDynamicClass() && !Record->isDependentType())
  3171. DynamicClasses.push_back(Record);
  3172. if (Record->getIdentifier()) {
  3173. // C++ [class.mem]p13:
  3174. // If T is the name of a class, then each of the following shall have a
  3175. // name different from T:
  3176. // - every member of every anonymous union that is a member of class T.
  3177. //
  3178. // C++ [class.mem]p14:
  3179. // In addition, if class T has a user-declared constructor (12.1), every
  3180. // non-static data member of class T shall have a name different from T.
  3181. for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  3182. R.first != R.second; ++R.first) {
  3183. NamedDecl *D = *R.first;
  3184. if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
  3185. isa<IndirectFieldDecl>(D)) {
  3186. Diag(D->getLocation(), diag::err_member_name_of_class)
  3187. << D->getDeclName();
  3188. break;
  3189. }
  3190. }
  3191. }
  3192. // Warn if the class has virtual methods but non-virtual public destructor.
  3193. if (Record->isPolymorphic() && !Record->isDependentType()) {
  3194. CXXDestructorDecl *dtor = Record->getDestructor();
  3195. if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
  3196. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  3197. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  3198. }
  3199. // See if a method overloads virtual methods in a base
  3200. /// class without overriding any.
  3201. if (!Record->isDependentType()) {
  3202. for (CXXRecordDecl::method_iterator M = Record->method_begin(),
  3203. MEnd = Record->method_end();
  3204. M != MEnd; ++M) {
  3205. if (!(*M)->isStatic())
  3206. DiagnoseHiddenVirtualMethods(Record, *M);
  3207. }
  3208. }
  3209. // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
  3210. // function that is not a constructor declares that member function to be
  3211. // const. [...] The class of which that function is a member shall be
  3212. // a literal type.
  3213. //
  3214. // It's fine to diagnose constructors here too: such constructors cannot
  3215. // produce a constant expression, so are ill-formed (no diagnostic required).
  3216. //
  3217. // If the class has virtual bases, any constexpr members will already have
  3218. // been diagnosed by the checks performed on the member declaration, so
  3219. // suppress this (less useful) diagnostic.
  3220. if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
  3221. !Record->isLiteral() && !Record->getNumVBases()) {
  3222. for (CXXRecordDecl::method_iterator M = Record->method_begin(),
  3223. MEnd = Record->method_end();
  3224. M != MEnd; ++M) {
  3225. if (M->isConstexpr() && M->isInstance()) {
  3226. switch (Record->getTemplateSpecializationKind()) {
  3227. case TSK_ImplicitInstantiation:
  3228. case TSK_ExplicitInstantiationDeclaration:
  3229. case TSK_ExplicitInstantiationDefinition:
  3230. // If a template instantiates to a non-literal type, but its members
  3231. // instantiate to constexpr functions, the template is technically
  3232. // ill-formed, but we allow it for sanity. Such members are treated as
  3233. // non-constexpr.
  3234. (*M)->setConstexpr(false);
  3235. continue;
  3236. case TSK_Undeclared:
  3237. case TSK_ExplicitSpecialization:
  3238. RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
  3239. PDiag(diag::err_constexpr_method_non_literal));
  3240. break;
  3241. }
  3242. // Only produce one error per class.
  3243. break;
  3244. }
  3245. }
  3246. }
  3247. // Declare inherited constructors. We do this eagerly here because:
  3248. // - The standard requires an eager diagnostic for conflicting inherited
  3249. // constructors from different classes.
  3250. // - The lazy declaration of the other implicit constructors is so as to not
  3251. // waste space and performance on classes that are not meant to be
  3252. // instantiated (e.g. meta-functions). This doesn't apply to classes that
  3253. // have inherited constructors.
  3254. DeclareInheritedConstructors(Record);
  3255. if (!Record->isDependentType())
  3256. CheckExplicitlyDefaultedMethods(Record);
  3257. }
  3258. void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
  3259. for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
  3260. ME = Record->method_end();
  3261. MI != ME; ++MI) {
  3262. if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
  3263. switch (getSpecialMember(*MI)) {
  3264. case CXXDefaultConstructor:
  3265. CheckExplicitlyDefaultedDefaultConstructor(
  3266. cast<CXXConstructorDecl>(*MI));
  3267. break;
  3268. case CXXDestructor:
  3269. CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
  3270. break;
  3271. case CXXCopyConstructor:
  3272. CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
  3273. break;
  3274. case CXXCopyAssignment:
  3275. CheckExplicitlyDefaultedCopyAssignment(*MI);
  3276. break;
  3277. case CXXMoveConstructor:
  3278. CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
  3279. break;
  3280. case CXXMoveAssignment:
  3281. CheckExplicitlyDefaultedMoveAssignment(*MI);
  3282. break;
  3283. case CXXInvalid:
  3284. llvm_unreachable("non-special member explicitly defaulted!");
  3285. }
  3286. }
  3287. }
  3288. }
  3289. void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
  3290. assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
  3291. // Whether this was the first-declared instance of the constructor.
  3292. // This affects whether we implicitly add an exception spec (and, eventually,
  3293. // constexpr). It is also ill-formed to explicitly default a constructor such
  3294. // that it would be deleted. (C++0x [decl.fct.def.default])
  3295. bool First = CD == CD->getCanonicalDecl();
  3296. bool HadError = false;
  3297. if (CD->getNumParams() != 0) {
  3298. Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
  3299. << CD->getSourceRange();
  3300. HadError = true;
  3301. }
  3302. ImplicitExceptionSpecification Spec
  3303. = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
  3304. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  3305. if (EPI.ExceptionSpecType == EST_Delayed) {
  3306. // Exception specification depends on some deferred part of the class. We'll
  3307. // try again when the class's definition has been fully processed.
  3308. return;
  3309. }
  3310. const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
  3311. *ExceptionType = Context.getFunctionType(
  3312. Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
  3313. // C++11 [dcl.fct.def.default]p2:
  3314. // An explicitly-defaulted function may be declared constexpr only if it
  3315. // would have been implicitly declared as constexpr,
  3316. if (CD->isConstexpr()) {
  3317. if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
  3318. Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
  3319. << CXXDefaultConstructor;
  3320. HadError = true;
  3321. }
  3322. }
  3323. // and may have an explicit exception-specification only if it is compatible
  3324. // with the exception-specification on the implicit declaration.
  3325. if (CtorType->hasExceptionSpec()) {
  3326. if (CheckEquivalentExceptionSpec(
  3327. PDiag(diag::err_incorrect_defaulted_exception_spec)
  3328. << CXXDefaultConstructor,
  3329. PDiag(),
  3330. ExceptionType, SourceLocation(),
  3331. CtorType, CD->getLocation())) {
  3332. HadError = true;
  3333. }
  3334. }
  3335. // If a function is explicitly defaulted on its first declaration,
  3336. if (First) {
  3337. // -- it is implicitly considered to be constexpr if the implicit
  3338. // definition would be,
  3339. CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
  3340. // -- it is implicitly considered to have the same
  3341. // exception-specification as if it had been implicitly declared
  3342. //
  3343. // FIXME: a compatible, but different, explicit exception specification
  3344. // will be silently overridden. We should issue a warning if this happens.
  3345. EPI.ExtInfo = CtorType->getExtInfo();
  3346. }
  3347. if (HadError) {
  3348. CD->setInvalidDecl();
  3349. return;
  3350. }
  3351. if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
  3352. if (First) {
  3353. CD->setDeletedAsWritten();
  3354. } else {
  3355. Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
  3356. << CXXDefaultConstructor;
  3357. CD->setInvalidDecl();
  3358. }
  3359. }
  3360. }
  3361. void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
  3362. assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
  3363. // Whether this was the first-declared instance of the constructor.
  3364. bool First = CD == CD->getCanonicalDecl();
  3365. bool HadError = false;
  3366. if (CD->getNumParams() != 1) {
  3367. Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
  3368. << CD->getSourceRange();
  3369. HadError = true;
  3370. }
  3371. ImplicitExceptionSpecification Spec(Context);
  3372. bool Const;
  3373. llvm::tie(Spec, Const) =
  3374. ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
  3375. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  3376. const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
  3377. *ExceptionType = Context.getFunctionType(
  3378. Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
  3379. // Check for parameter type matching.
  3380. // This is a copy ctor so we know it's a cv-qualified reference to T.
  3381. QualType ArgType = CtorType->getArgType(0);
  3382. if (ArgType->getPointeeType().isVolatileQualified()) {
  3383. Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
  3384. HadError = true;
  3385. }
  3386. if (ArgType->getPointeeType().isConstQualified() && !Const) {
  3387. Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
  3388. HadError = true;
  3389. }
  3390. // C++11 [dcl.fct.def.default]p2:
  3391. // An explicitly-defaulted function may be declared constexpr only if it
  3392. // would have been implicitly declared as constexpr,
  3393. if (CD->isConstexpr()) {
  3394. if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
  3395. Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
  3396. << CXXCopyConstructor;
  3397. HadError = true;
  3398. }
  3399. }
  3400. // and may have an explicit exception-specification only if it is compatible
  3401. // with the exception-specification on the implicit declaration.
  3402. if (CtorType->hasExceptionSpec()) {
  3403. if (CheckEquivalentExceptionSpec(
  3404. PDiag(diag::err_incorrect_defaulted_exception_spec)
  3405. << CXXCopyConstructor,
  3406. PDiag(),
  3407. ExceptionType, SourceLocation(),
  3408. CtorType, CD->getLocation())) {
  3409. HadError = true;
  3410. }
  3411. }
  3412. // If a function is explicitly defaulted on its first declaration,
  3413. if (First) {
  3414. // -- it is implicitly considered to be constexpr if the implicit
  3415. // definition would be,
  3416. CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
  3417. // -- it is implicitly considered to have the same
  3418. // exception-specification as if it had been implicitly declared, and
  3419. //
  3420. // FIXME: a compatible, but different, explicit exception specification
  3421. // will be silently overridden. We should issue a warning if this happens.
  3422. EPI.ExtInfo = CtorType->getExtInfo();
  3423. // -- [...] it shall have the same parameter type as if it had been
  3424. // implicitly declared.
  3425. CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
  3426. }
  3427. if (HadError) {
  3428. CD->setInvalidDecl();
  3429. return;
  3430. }
  3431. if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
  3432. if (First) {
  3433. CD->setDeletedAsWritten();
  3434. } else {
  3435. Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
  3436. << CXXCopyConstructor;
  3437. CD->setInvalidDecl();
  3438. }
  3439. }
  3440. }
  3441. void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
  3442. assert(MD->isExplicitlyDefaulted());
  3443. // Whether this was the first-declared instance of the operator
  3444. bool First = MD == MD->getCanonicalDecl();
  3445. bool HadError = false;
  3446. if (MD->getNumParams() != 1) {
  3447. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
  3448. << MD->getSourceRange();
  3449. HadError = true;
  3450. }
  3451. QualType ReturnType =
  3452. MD->getType()->getAs<FunctionType>()->getResultType();
  3453. if (!ReturnType->isLValueReferenceType() ||
  3454. !Context.hasSameType(
  3455. Context.getCanonicalType(ReturnType->getPointeeType()),
  3456. Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
  3457. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
  3458. HadError = true;
  3459. }
  3460. ImplicitExceptionSpecification Spec(Context);
  3461. bool Const;
  3462. llvm::tie(Spec, Const) =
  3463. ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
  3464. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  3465. const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
  3466. *ExceptionType = Context.getFunctionType(
  3467. Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
  3468. QualType ArgType = OperType->getArgType(0);
  3469. if (!ArgType->isLValueReferenceType()) {
  3470. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  3471. HadError = true;
  3472. } else {
  3473. if (ArgType->getPointeeType().isVolatileQualified()) {
  3474. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
  3475. HadError = true;
  3476. }
  3477. if (ArgType->getPointeeType().isConstQualified() && !Const) {
  3478. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
  3479. HadError = true;
  3480. }
  3481. }
  3482. if (OperType->getTypeQuals()) {
  3483. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
  3484. HadError = true;
  3485. }
  3486. if (OperType->hasExceptionSpec()) {
  3487. if (CheckEquivalentExceptionSpec(
  3488. PDiag(diag::err_incorrect_defaulted_exception_spec)
  3489. << CXXCopyAssignment,
  3490. PDiag(),
  3491. ExceptionType, SourceLocation(),
  3492. OperType, MD->getLocation())) {
  3493. HadError = true;
  3494. }
  3495. }
  3496. if (First) {
  3497. // We set the declaration to have the computed exception spec here.
  3498. // We duplicate the one parameter type.
  3499. EPI.RefQualifier = OperType->getRefQualifier();
  3500. EPI.ExtInfo = OperType->getExtInfo();
  3501. MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
  3502. }
  3503. if (HadError) {
  3504. MD->setInvalidDecl();
  3505. return;
  3506. }
  3507. if (ShouldDeleteCopyAssignmentOperator(MD)) {
  3508. if (First) {
  3509. MD->setDeletedAsWritten();
  3510. } else {
  3511. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
  3512. << CXXCopyAssignment;
  3513. MD->setInvalidDecl();
  3514. }
  3515. }
  3516. }
  3517. void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
  3518. assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
  3519. // Whether this was the first-declared instance of the constructor.
  3520. bool First = CD == CD->getCanonicalDecl();
  3521. bool HadError = false;
  3522. if (CD->getNumParams() != 1) {
  3523. Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
  3524. << CD->getSourceRange();
  3525. HadError = true;
  3526. }
  3527. ImplicitExceptionSpecification Spec(
  3528. ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
  3529. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  3530. const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
  3531. *ExceptionType = Context.getFunctionType(
  3532. Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
  3533. // Check for parameter type matching.
  3534. // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
  3535. QualType ArgType = CtorType->getArgType(0);
  3536. if (ArgType->getPointeeType().isVolatileQualified()) {
  3537. Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
  3538. HadError = true;
  3539. }
  3540. if (ArgType->getPointeeType().isConstQualified()) {
  3541. Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
  3542. HadError = true;
  3543. }
  3544. // C++11 [dcl.fct.def.default]p2:
  3545. // An explicitly-defaulted function may be declared constexpr only if it
  3546. // would have been implicitly declared as constexpr,
  3547. if (CD->isConstexpr()) {
  3548. if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
  3549. Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
  3550. << CXXMoveConstructor;
  3551. HadError = true;
  3552. }
  3553. }
  3554. // and may have an explicit exception-specification only if it is compatible
  3555. // with the exception-specification on the implicit declaration.
  3556. if (CtorType->hasExceptionSpec()) {
  3557. if (CheckEquivalentExceptionSpec(
  3558. PDiag(diag::err_incorrect_defaulted_exception_spec)
  3559. << CXXMoveConstructor,
  3560. PDiag(),
  3561. ExceptionType, SourceLocation(),
  3562. CtorType, CD->getLocation())) {
  3563. HadError = true;
  3564. }
  3565. }
  3566. // If a function is explicitly defaulted on its first declaration,
  3567. if (First) {
  3568. // -- it is implicitly considered to be constexpr if the implicit
  3569. // definition would be,
  3570. CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
  3571. // -- it is implicitly considered to have the same
  3572. // exception-specification as if it had been implicitly declared, and
  3573. //
  3574. // FIXME: a compatible, but different, explicit exception specification
  3575. // will be silently overridden. We should issue a warning if this happens.
  3576. EPI.ExtInfo = CtorType->getExtInfo();
  3577. // -- [...] it shall have the same parameter type as if it had been
  3578. // implicitly declared.
  3579. CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
  3580. }
  3581. if (HadError) {
  3582. CD->setInvalidDecl();
  3583. return;
  3584. }
  3585. if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
  3586. if (First) {
  3587. CD->setDeletedAsWritten();
  3588. } else {
  3589. Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
  3590. << CXXMoveConstructor;
  3591. CD->setInvalidDecl();
  3592. }
  3593. }
  3594. }
  3595. void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
  3596. assert(MD->isExplicitlyDefaulted());
  3597. // Whether this was the first-declared instance of the operator
  3598. bool First = MD == MD->getCanonicalDecl();
  3599. bool HadError = false;
  3600. if (MD->getNumParams() != 1) {
  3601. Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
  3602. << MD->getSourceRange();
  3603. HadError = true;
  3604. }
  3605. QualType ReturnType =
  3606. MD->getType()->getAs<FunctionType>()->getResultType();
  3607. if (!ReturnType->isLValueReferenceType() ||
  3608. !Context.hasSameType(
  3609. Context.getCanonicalType(ReturnType->getPointeeType()),
  3610. Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
  3611. Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
  3612. HadError = true;
  3613. }
  3614. ImplicitExceptionSpecification Spec(
  3615. ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
  3616. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  3617. const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
  3618. *ExceptionType = Context.getFunctionType(
  3619. Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
  3620. QualType ArgType = OperType->getArgType(0);
  3621. if (!ArgType->isRValueReferenceType()) {
  3622. Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
  3623. HadError = true;
  3624. } else {
  3625. if (ArgType->getPointeeType().isVolatileQualified()) {
  3626. Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
  3627. HadError = true;
  3628. }
  3629. if (ArgType->getPointeeType().isConstQualified()) {
  3630. Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
  3631. HadError = true;
  3632. }
  3633. }
  3634. if (OperType->getTypeQuals()) {
  3635. Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
  3636. HadError = true;
  3637. }
  3638. if (OperType->hasExceptionSpec()) {
  3639. if (CheckEquivalentExceptionSpec(
  3640. PDiag(diag::err_incorrect_defaulted_exception_spec)
  3641. << CXXMoveAssignment,
  3642. PDiag(),
  3643. ExceptionType, SourceLocation(),
  3644. OperType, MD->getLocation())) {
  3645. HadError = true;
  3646. }
  3647. }
  3648. if (First) {
  3649. // We set the declaration to have the computed exception spec here.
  3650. // We duplicate the one parameter type.
  3651. EPI.RefQualifier = OperType->getRefQualifier();
  3652. EPI.ExtInfo = OperType->getExtInfo();
  3653. MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
  3654. }
  3655. if (HadError) {
  3656. MD->setInvalidDecl();
  3657. return;
  3658. }
  3659. if (ShouldDeleteMoveAssignmentOperator(MD)) {
  3660. if (First) {
  3661. MD->setDeletedAsWritten();
  3662. } else {
  3663. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
  3664. << CXXMoveAssignment;
  3665. MD->setInvalidDecl();
  3666. }
  3667. }
  3668. }
  3669. void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
  3670. assert(DD->isExplicitlyDefaulted());
  3671. // Whether this was the first-declared instance of the destructor.
  3672. bool First = DD == DD->getCanonicalDecl();
  3673. ImplicitExceptionSpecification Spec
  3674. = ComputeDefaultedDtorExceptionSpec(DD->getParent());
  3675. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  3676. const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
  3677. *ExceptionType = Context.getFunctionType(
  3678. Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
  3679. if (DtorType->hasExceptionSpec()) {
  3680. if (CheckEquivalentExceptionSpec(
  3681. PDiag(diag::err_incorrect_defaulted_exception_spec)
  3682. << CXXDestructor,
  3683. PDiag(),
  3684. ExceptionType, SourceLocation(),
  3685. DtorType, DD->getLocation())) {
  3686. DD->setInvalidDecl();
  3687. return;
  3688. }
  3689. }
  3690. if (First) {
  3691. // We set the declaration to have the computed exception spec here.
  3692. // There are no parameters.
  3693. EPI.ExtInfo = DtorType->getExtInfo();
  3694. DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
  3695. }
  3696. if (ShouldDeleteDestructor(DD)) {
  3697. if (First) {
  3698. DD->setDeletedAsWritten();
  3699. } else {
  3700. Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
  3701. << CXXDestructor;
  3702. DD->setInvalidDecl();
  3703. }
  3704. }
  3705. }
  3706. /// This function implements the following C++0x paragraphs:
  3707. /// - [class.ctor]/5
  3708. /// - [class.copy]/11
  3709. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
  3710. assert(!MD->isInvalidDecl());
  3711. CXXRecordDecl *RD = MD->getParent();
  3712. assert(!RD->isDependentType() && "do deletion after instantiation");
  3713. if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
  3714. return false;
  3715. bool IsUnion = RD->isUnion();
  3716. bool IsConstructor = false;
  3717. bool IsAssignment = false;
  3718. bool IsMove = false;
  3719. bool ConstArg = false;
  3720. switch (CSM) {
  3721. case CXXDefaultConstructor:
  3722. IsConstructor = true;
  3723. break;
  3724. case CXXCopyConstructor:
  3725. IsConstructor = true;
  3726. ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
  3727. break;
  3728. case CXXMoveConstructor:
  3729. IsConstructor = true;
  3730. IsMove = true;
  3731. break;
  3732. default:
  3733. llvm_unreachable("function only currently implemented for default ctors");
  3734. }
  3735. SourceLocation Loc = MD->getLocation();
  3736. // Do access control from the special member function
  3737. ContextRAII MethodContext(*this, MD);
  3738. bool AllConst = true;
  3739. // We do this because we should never actually use an anonymous
  3740. // union's constructor.
  3741. if (IsUnion && RD->isAnonymousStructOrUnion())
  3742. return false;
  3743. // FIXME: We should put some diagnostic logic right into this function.
  3744. for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
  3745. BE = RD->bases_end();
  3746. BI != BE; ++BI) {
  3747. // We'll handle this one later
  3748. if (BI->isVirtual())
  3749. continue;
  3750. CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
  3751. assert(BaseDecl && "base isn't a CXXRecordDecl");
  3752. // Unless we have an assignment operator, the base's destructor must
  3753. // be accessible and not deleted.
  3754. if (!IsAssignment) {
  3755. CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
  3756. if (BaseDtor->isDeleted())
  3757. return true;
  3758. if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
  3759. AR_accessible)
  3760. return true;
  3761. }
  3762. // Finding the corresponding member in the base should lead to a
  3763. // unique, accessible, non-deleted function. If we are doing
  3764. // a destructor, we have already checked this case.
  3765. if (CSM != CXXDestructor) {
  3766. SpecialMemberOverloadResult *SMOR =
  3767. LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
  3768. false);
  3769. if (!SMOR->hasSuccess())
  3770. return true;
  3771. CXXMethodDecl *BaseMember = SMOR->getMethod();
  3772. if (IsConstructor) {
  3773. CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
  3774. if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
  3775. PDiag()) != AR_accessible)
  3776. return true;
  3777. // For a move operation, the corresponding operation must actually
  3778. // be a move operation (and not a copy selected by overload
  3779. // resolution) unless we are working on a trivially copyable class.
  3780. if (IsMove && !BaseCtor->isMoveConstructor() &&
  3781. !BaseDecl->isTriviallyCopyable())
  3782. return true;
  3783. }
  3784. }
  3785. }
  3786. for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
  3787. BE = RD->vbases_end();
  3788. BI != BE; ++BI) {
  3789. CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
  3790. assert(BaseDecl && "base isn't a CXXRecordDecl");
  3791. // Unless we have an assignment operator, the base's destructor must
  3792. // be accessible and not deleted.
  3793. if (!IsAssignment) {
  3794. CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
  3795. if (BaseDtor->isDeleted())
  3796. return true;
  3797. if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
  3798. AR_accessible)
  3799. return true;
  3800. }
  3801. // Finding the corresponding member in the base should lead to a
  3802. // unique, accessible, non-deleted function.
  3803. if (CSM != CXXDestructor) {
  3804. SpecialMemberOverloadResult *SMOR =
  3805. LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
  3806. false);
  3807. if (!SMOR->hasSuccess())
  3808. return true;
  3809. CXXMethodDecl *BaseMember = SMOR->getMethod();
  3810. if (IsConstructor) {
  3811. CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
  3812. if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
  3813. PDiag()) != AR_accessible)
  3814. return true;
  3815. // For a move operation, the corresponding operation must actually
  3816. // be a move operation (and not a copy selected by overload
  3817. // resolution) unless we are working on a trivially copyable class.
  3818. if (IsMove && !BaseCtor->isMoveConstructor() &&
  3819. !BaseDecl->isTriviallyCopyable())
  3820. return true;
  3821. }
  3822. }
  3823. }
  3824. for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
  3825. FE = RD->field_end();
  3826. FI != FE; ++FI) {
  3827. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  3828. continue;
  3829. QualType FieldType = Context.getBaseElementType(FI->getType());
  3830. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  3831. // For a default constructor, all references must be initialized in-class
  3832. // and, if a union, it must have a non-const member.
  3833. if (CSM == CXXDefaultConstructor) {
  3834. if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
  3835. return true;
  3836. if (IsUnion && !FieldType.isConstQualified())
  3837. AllConst = false;
  3838. // For a copy constructor, data members must not be of rvalue reference
  3839. // type.
  3840. } else if (CSM == CXXCopyConstructor) {
  3841. if (FieldType->isRValueReferenceType())
  3842. return true;
  3843. }
  3844. if (FieldRecord) {
  3845. // For a default constructor, a const member must have a user-provided
  3846. // default constructor or else be explicitly initialized.
  3847. if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
  3848. !FI->hasInClassInitializer() &&
  3849. !FieldRecord->hasUserProvidedDefaultConstructor())
  3850. return true;
  3851. // Some additional restrictions exist on the variant members.
  3852. if (!IsUnion && FieldRecord->isUnion() &&
  3853. FieldRecord->isAnonymousStructOrUnion()) {
  3854. // We're okay to reuse AllConst here since we only care about the
  3855. // value otherwise if we're in a union.
  3856. AllConst = true;
  3857. for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
  3858. UE = FieldRecord->field_end();
  3859. UI != UE; ++UI) {
  3860. QualType UnionFieldType = Context.getBaseElementType(UI->getType());
  3861. CXXRecordDecl *UnionFieldRecord =
  3862. UnionFieldType->getAsCXXRecordDecl();
  3863. if (!UnionFieldType.isConstQualified())
  3864. AllConst = false;
  3865. if (UnionFieldRecord) {
  3866. // FIXME: Checking for accessibility and validity of this
  3867. // destructor is technically going beyond the
  3868. // standard, but this is believed to be a defect.
  3869. if (!IsAssignment) {
  3870. CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
  3871. if (FieldDtor->isDeleted())
  3872. return true;
  3873. if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
  3874. AR_accessible)
  3875. return true;
  3876. if (!FieldDtor->isTrivial())
  3877. return true;
  3878. }
  3879. if (CSM != CXXDestructor) {
  3880. SpecialMemberOverloadResult *SMOR =
  3881. LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
  3882. false, false, false);
  3883. // FIXME: Checking for accessibility and validity of this
  3884. // corresponding member is technically going beyond the
  3885. // standard, but this is believed to be a defect.
  3886. if (!SMOR->hasSuccess())
  3887. return true;
  3888. CXXMethodDecl *FieldMember = SMOR->getMethod();
  3889. // A member of a union must have a trivial corresponding
  3890. // constructor.
  3891. if (!FieldMember->isTrivial())
  3892. return true;
  3893. if (IsConstructor) {
  3894. CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
  3895. if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
  3896. PDiag()) != AR_accessible)
  3897. return true;
  3898. }
  3899. }
  3900. }
  3901. }
  3902. // At least one member in each anonymous union must be non-const
  3903. if (CSM == CXXDefaultConstructor && AllConst)
  3904. return true;
  3905. // Don't try to initialize the anonymous union
  3906. // This is technically non-conformant, but sanity demands it.
  3907. continue;
  3908. }
  3909. // Unless we're doing assignment, the field's destructor must be
  3910. // accessible and not deleted.
  3911. if (!IsAssignment) {
  3912. CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
  3913. if (FieldDtor->isDeleted())
  3914. return true;
  3915. if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
  3916. AR_accessible)
  3917. return true;
  3918. }
  3919. // Check that the corresponding member of the field is accessible,
  3920. // unique, and non-deleted. We don't do this if it has an explicit
  3921. // initialization when default-constructing.
  3922. if (CSM != CXXDestructor &&
  3923. (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
  3924. SpecialMemberOverloadResult *SMOR =
  3925. LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
  3926. false);
  3927. if (!SMOR->hasSuccess())
  3928. return true;
  3929. CXXMethodDecl *FieldMember = SMOR->getMethod();
  3930. if (IsConstructor) {
  3931. CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
  3932. if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
  3933. PDiag()) != AR_accessible)
  3934. return true;
  3935. // For a move operation, the corresponding operation must actually
  3936. // be a move operation (and not a copy selected by overload
  3937. // resolution) unless we are working on a trivially copyable class.
  3938. if (IsMove && !FieldCtor->isMoveConstructor() &&
  3939. !FieldRecord->isTriviallyCopyable())
  3940. return true;
  3941. }
  3942. // We need the corresponding member of a union to be trivial so that
  3943. // we can safely copy them all simultaneously.
  3944. // FIXME: Note that performing the check here (where we rely on the lack
  3945. // of an in-class initializer) is technically ill-formed. However, this
  3946. // seems most obviously to be a bug in the standard.
  3947. if (IsUnion && !FieldMember->isTrivial())
  3948. return true;
  3949. }
  3950. } else if (CSM == CXXDefaultConstructor && !IsUnion &&
  3951. FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
  3952. // We can't initialize a const member of non-class type to any value.
  3953. return true;
  3954. }
  3955. }
  3956. // We can't have all const members in a union when default-constructing,
  3957. // or else they're all nonsensical garbage values that can't be changed.
  3958. if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
  3959. return true;
  3960. return false;
  3961. }
  3962. bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
  3963. CXXRecordDecl *RD = MD->getParent();
  3964. assert(!RD->isDependentType() && "do deletion after instantiation");
  3965. if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
  3966. return false;
  3967. SourceLocation Loc = MD->getLocation();
  3968. // Do access control from the constructor
  3969. ContextRAII MethodContext(*this, MD);
  3970. bool Union = RD->isUnion();
  3971. unsigned ArgQuals =
  3972. MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
  3973. Qualifiers::Const : 0;
  3974. // We do this because we should never actually use an anonymous
  3975. // union's constructor.
  3976. if (Union && RD->isAnonymousStructOrUnion())
  3977. return false;
  3978. // FIXME: We should put some diagnostic logic right into this function.
  3979. // C++0x [class.copy]/20
  3980. // A defaulted [copy] assignment operator for class X is defined as deleted
  3981. // if X has:
  3982. for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
  3983. BE = RD->bases_end();
  3984. BI != BE; ++BI) {
  3985. // We'll handle this one later
  3986. if (BI->isVirtual())
  3987. continue;
  3988. QualType BaseType = BI->getType();
  3989. CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
  3990. assert(BaseDecl && "base isn't a CXXRecordDecl");
  3991. // -- a [direct base class] B that cannot be [copied] because overload
  3992. // resolution, as applied to B's [copy] assignment operator, results in
  3993. // an ambiguity or a function that is deleted or inaccessible from the
  3994. // assignment operator
  3995. CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
  3996. 0);
  3997. if (!CopyOper || CopyOper->isDeleted())
  3998. return true;
  3999. if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
  4000. return true;
  4001. }
  4002. for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
  4003. BE = RD->vbases_end();
  4004. BI != BE; ++BI) {
  4005. QualType BaseType = BI->getType();
  4006. CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
  4007. assert(BaseDecl && "base isn't a CXXRecordDecl");
  4008. // -- a [virtual base class] B that cannot be [copied] because overload
  4009. // resolution, as applied to B's [copy] assignment operator, results in
  4010. // an ambiguity or a function that is deleted or inaccessible from the
  4011. // assignment operator
  4012. CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
  4013. 0);
  4014. if (!CopyOper || CopyOper->isDeleted())
  4015. return true;
  4016. if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
  4017. return true;
  4018. }
  4019. for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
  4020. FE = RD->field_end();
  4021. FI != FE; ++FI) {
  4022. if (FI->isUnnamedBitfield())
  4023. continue;
  4024. QualType FieldType = Context.getBaseElementType(FI->getType());
  4025. // -- a non-static data member of reference type
  4026. if (FieldType->isReferenceType())
  4027. return true;
  4028. // -- a non-static data member of const non-class type (or array thereof)
  4029. if (FieldType.isConstQualified() && !FieldType->isRecordType())
  4030. return true;
  4031. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  4032. if (FieldRecord) {
  4033. // This is an anonymous union
  4034. if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
  4035. // Anonymous unions inside unions do not variant members create
  4036. if (!Union) {
  4037. for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
  4038. UE = FieldRecord->field_end();
  4039. UI != UE; ++UI) {
  4040. QualType UnionFieldType = Context.getBaseElementType(UI->getType());
  4041. CXXRecordDecl *UnionFieldRecord =
  4042. UnionFieldType->getAsCXXRecordDecl();
  4043. // -- a variant member with a non-trivial [copy] assignment operator
  4044. // and X is a union-like class
  4045. if (UnionFieldRecord &&
  4046. !UnionFieldRecord->hasTrivialCopyAssignment())
  4047. return true;
  4048. }
  4049. }
  4050. // Don't try to initalize an anonymous union
  4051. continue;
  4052. // -- a variant member with a non-trivial [copy] assignment operator
  4053. // and X is a union-like class
  4054. } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
  4055. return true;
  4056. }
  4057. CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
  4058. false, 0);
  4059. if (!CopyOper || CopyOper->isDeleted())
  4060. return true;
  4061. if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
  4062. return true;
  4063. }
  4064. }
  4065. return false;
  4066. }
  4067. bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
  4068. CXXRecordDecl *RD = MD->getParent();
  4069. assert(!RD->isDependentType() && "do deletion after instantiation");
  4070. if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
  4071. return false;
  4072. SourceLocation Loc = MD->getLocation();
  4073. // Do access control from the constructor
  4074. ContextRAII MethodContext(*this, MD);
  4075. bool Union = RD->isUnion();
  4076. // We do this because we should never actually use an anonymous
  4077. // union's constructor.
  4078. if (Union && RD->isAnonymousStructOrUnion())
  4079. return false;
  4080. // C++0x [class.copy]/20
  4081. // A defaulted [move] assignment operator for class X is defined as deleted
  4082. // if X has:
  4083. // -- for the move constructor, [...] any direct or indirect virtual base
  4084. // class.
  4085. if (RD->getNumVBases() != 0)
  4086. return true;
  4087. for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
  4088. BE = RD->bases_end();
  4089. BI != BE; ++BI) {
  4090. QualType BaseType = BI->getType();
  4091. CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
  4092. assert(BaseDecl && "base isn't a CXXRecordDecl");
  4093. // -- a [direct base class] B that cannot be [moved] because overload
  4094. // resolution, as applied to B's [move] assignment operator, results in
  4095. // an ambiguity or a function that is deleted or inaccessible from the
  4096. // assignment operator
  4097. CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
  4098. if (!MoveOper || MoveOper->isDeleted())
  4099. return true;
  4100. if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
  4101. return true;
  4102. // -- for the move assignment operator, a [direct base class] with a type
  4103. // that does not have a move assignment operator and is not trivially
  4104. // copyable.
  4105. if (!MoveOper->isMoveAssignmentOperator() &&
  4106. !BaseDecl->isTriviallyCopyable())
  4107. return true;
  4108. }
  4109. for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
  4110. FE = RD->field_end();
  4111. FI != FE; ++FI) {
  4112. if (FI->isUnnamedBitfield())
  4113. continue;
  4114. QualType FieldType = Context.getBaseElementType(FI->getType());
  4115. // -- a non-static data member of reference type
  4116. if (FieldType->isReferenceType())
  4117. return true;
  4118. // -- a non-static data member of const non-class type (or array thereof)
  4119. if (FieldType.isConstQualified() && !FieldType->isRecordType())
  4120. return true;
  4121. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  4122. if (FieldRecord) {
  4123. // This is an anonymous union
  4124. if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
  4125. // Anonymous unions inside unions do not variant members create
  4126. if (!Union) {
  4127. for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
  4128. UE = FieldRecord->field_end();
  4129. UI != UE; ++UI) {
  4130. QualType UnionFieldType = Context.getBaseElementType(UI->getType());
  4131. CXXRecordDecl *UnionFieldRecord =
  4132. UnionFieldType->getAsCXXRecordDecl();
  4133. // -- a variant member with a non-trivial [move] assignment operator
  4134. // and X is a union-like class
  4135. if (UnionFieldRecord &&
  4136. !UnionFieldRecord->hasTrivialMoveAssignment())
  4137. return true;
  4138. }
  4139. }
  4140. // Don't try to initalize an anonymous union
  4141. continue;
  4142. // -- a variant member with a non-trivial [move] assignment operator
  4143. // and X is a union-like class
  4144. } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
  4145. return true;
  4146. }
  4147. CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
  4148. if (!MoveOper || MoveOper->isDeleted())
  4149. return true;
  4150. if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
  4151. return true;
  4152. // -- for the move assignment operator, a [non-static data member] with a
  4153. // type that does not have a move assignment operator and is not
  4154. // trivially copyable.
  4155. if (!MoveOper->isMoveAssignmentOperator() &&
  4156. !FieldRecord->isTriviallyCopyable())
  4157. return true;
  4158. }
  4159. }
  4160. return false;
  4161. }
  4162. bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
  4163. CXXRecordDecl *RD = DD->getParent();
  4164. assert(!RD->isDependentType() && "do deletion after instantiation");
  4165. if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
  4166. return false;
  4167. SourceLocation Loc = DD->getLocation();
  4168. // Do access control from the destructor
  4169. ContextRAII CtorContext(*this, DD);
  4170. bool Union = RD->isUnion();
  4171. // We do this because we should never actually use an anonymous
  4172. // union's destructor.
  4173. if (Union && RD->isAnonymousStructOrUnion())
  4174. return false;
  4175. // C++0x [class.dtor]p5
  4176. // A defaulted destructor for a class X is defined as deleted if:
  4177. for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
  4178. BE = RD->bases_end();
  4179. BI != BE; ++BI) {
  4180. // We'll handle this one later
  4181. if (BI->isVirtual())
  4182. continue;
  4183. CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
  4184. CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
  4185. assert(BaseDtor && "base has no destructor");
  4186. // -- any direct or virtual base class has a deleted destructor or
  4187. // a destructor that is inaccessible from the defaulted destructor
  4188. if (BaseDtor->isDeleted())
  4189. return true;
  4190. if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
  4191. AR_accessible)
  4192. return true;
  4193. }
  4194. for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
  4195. BE = RD->vbases_end();
  4196. BI != BE; ++BI) {
  4197. CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
  4198. CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
  4199. assert(BaseDtor && "base has no destructor");
  4200. // -- any direct or virtual base class has a deleted destructor or
  4201. // a destructor that is inaccessible from the defaulted destructor
  4202. if (BaseDtor->isDeleted())
  4203. return true;
  4204. if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
  4205. AR_accessible)
  4206. return true;
  4207. }
  4208. for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
  4209. FE = RD->field_end();
  4210. FI != FE; ++FI) {
  4211. QualType FieldType = Context.getBaseElementType(FI->getType());
  4212. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  4213. if (FieldRecord) {
  4214. if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
  4215. for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
  4216. UE = FieldRecord->field_end();
  4217. UI != UE; ++UI) {
  4218. QualType UnionFieldType = Context.getBaseElementType(FI->getType());
  4219. CXXRecordDecl *UnionFieldRecord =
  4220. UnionFieldType->getAsCXXRecordDecl();
  4221. // -- X is a union-like class that has a variant member with a non-
  4222. // trivial destructor.
  4223. if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
  4224. return true;
  4225. }
  4226. // Technically we are supposed to do this next check unconditionally.
  4227. // But that makes absolutely no sense.
  4228. } else {
  4229. CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
  4230. // -- any of the non-static data members has class type M (or array
  4231. // thereof) and M has a deleted destructor or a destructor that is
  4232. // inaccessible from the defaulted destructor
  4233. if (FieldDtor->isDeleted())
  4234. return true;
  4235. if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
  4236. AR_accessible)
  4237. return true;
  4238. // -- X is a union-like class that has a variant member with a non-
  4239. // trivial destructor.
  4240. if (Union && !FieldDtor->isTrivial())
  4241. return true;
  4242. }
  4243. }
  4244. }
  4245. if (DD->isVirtual()) {
  4246. FunctionDecl *OperatorDelete = 0;
  4247. DeclarationName Name =
  4248. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  4249. if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
  4250. false))
  4251. return true;
  4252. }
  4253. return false;
  4254. }
  4255. /// \brief Data used with FindHiddenVirtualMethod
  4256. namespace {
  4257. struct FindHiddenVirtualMethodData {
  4258. Sema *S;
  4259. CXXMethodDecl *Method;
  4260. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  4261. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  4262. };
  4263. }
  4264. /// \brief Member lookup function that determines whether a given C++
  4265. /// method overloads virtual methods in a base class without overriding any,
  4266. /// to be used with CXXRecordDecl::lookupInBases().
  4267. static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
  4268. CXXBasePath &Path,
  4269. void *UserData) {
  4270. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  4271. FindHiddenVirtualMethodData &Data
  4272. = *static_cast<FindHiddenVirtualMethodData*>(UserData);
  4273. DeclarationName Name = Data.Method->getDeclName();
  4274. assert(Name.getNameKind() == DeclarationName::Identifier);
  4275. bool foundSameNameMethod = false;
  4276. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  4277. for (Path.Decls = BaseRecord->lookup(Name);
  4278. Path.Decls.first != Path.Decls.second;
  4279. ++Path.Decls.first) {
  4280. NamedDecl *D = *Path.Decls.first;
  4281. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  4282. MD = MD->getCanonicalDecl();
  4283. foundSameNameMethod = true;
  4284. // Interested only in hidden virtual methods.
  4285. if (!MD->isVirtual())
  4286. continue;
  4287. // If the method we are checking overrides a method from its base
  4288. // don't warn about the other overloaded methods.
  4289. if (!Data.S->IsOverload(Data.Method, MD, false))
  4290. return true;
  4291. // Collect the overload only if its hidden.
  4292. if (!Data.OverridenAndUsingBaseMethods.count(MD))
  4293. overloadedMethods.push_back(MD);
  4294. }
  4295. }
  4296. if (foundSameNameMethod)
  4297. Data.OverloadedMethods.append(overloadedMethods.begin(),
  4298. overloadedMethods.end());
  4299. return foundSameNameMethod;
  4300. }
  4301. /// \brief See if a method overloads virtual methods in a base class without
  4302. /// overriding any.
  4303. void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  4304. if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
  4305. MD->getLocation()) == DiagnosticsEngine::Ignored)
  4306. return;
  4307. if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
  4308. return;
  4309. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  4310. /*bool RecordPaths=*/false,
  4311. /*bool DetectVirtual=*/false);
  4312. FindHiddenVirtualMethodData Data;
  4313. Data.Method = MD;
  4314. Data.S = this;
  4315. // Keep the base methods that were overriden or introduced in the subclass
  4316. // by 'using' in a set. A base method not in this set is hidden.
  4317. for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
  4318. res.first != res.second; ++res.first) {
  4319. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
  4320. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  4321. E = MD->end_overridden_methods();
  4322. I != E; ++I)
  4323. Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
  4324. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
  4325. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
  4326. Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
  4327. }
  4328. if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
  4329. !Data.OverloadedMethods.empty()) {
  4330. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  4331. << MD << (Data.OverloadedMethods.size() > 1);
  4332. for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
  4333. CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
  4334. Diag(overloadedMD->getLocation(),
  4335. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  4336. }
  4337. }
  4338. }
  4339. void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
  4340. Decl *TagDecl,
  4341. SourceLocation LBrac,
  4342. SourceLocation RBrac,
  4343. AttributeList *AttrList) {
  4344. if (!TagDecl)
  4345. return;
  4346. AdjustDeclIfTemplate(TagDecl);
  4347. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  4348. // strict aliasing violation!
  4349. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  4350. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  4351. CheckCompletedCXXClass(
  4352. dyn_cast_or_null<CXXRecordDecl>(TagDecl));
  4353. }
  4354. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  4355. /// special functions, such as the default constructor, copy
  4356. /// constructor, or destructor, to the given C++ class (C++
  4357. /// [special]p1). This routine can only be executed just before the
  4358. /// definition of the class is complete.
  4359. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  4360. if (!ClassDecl->hasUserDeclaredConstructor())
  4361. ++ASTContext::NumImplicitDefaultConstructors;
  4362. if (!ClassDecl->hasUserDeclaredCopyConstructor())
  4363. ++ASTContext::NumImplicitCopyConstructors;
  4364. if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
  4365. ++ASTContext::NumImplicitMoveConstructors;
  4366. if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
  4367. ++ASTContext::NumImplicitCopyAssignmentOperators;
  4368. // If we have a dynamic class, then the copy assignment operator may be
  4369. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  4370. // it shows up in the right place in the vtable and that we diagnose
  4371. // problems with the implicit exception specification.
  4372. if (ClassDecl->isDynamicClass())
  4373. DeclareImplicitCopyAssignment(ClassDecl);
  4374. }
  4375. if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
  4376. ++ASTContext::NumImplicitMoveAssignmentOperators;
  4377. // Likewise for the move assignment operator.
  4378. if (ClassDecl->isDynamicClass())
  4379. DeclareImplicitMoveAssignment(ClassDecl);
  4380. }
  4381. if (!ClassDecl->hasUserDeclaredDestructor()) {
  4382. ++ASTContext::NumImplicitDestructors;
  4383. // If we have a dynamic class, then the destructor may be virtual, so we
  4384. // have to declare the destructor immediately. This ensures that, e.g., it
  4385. // shows up in the right place in the vtable and that we diagnose problems
  4386. // with the implicit exception specification.
  4387. if (ClassDecl->isDynamicClass())
  4388. DeclareImplicitDestructor(ClassDecl);
  4389. }
  4390. }
  4391. void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
  4392. if (!D)
  4393. return;
  4394. int NumParamList = D->getNumTemplateParameterLists();
  4395. for (int i = 0; i < NumParamList; i++) {
  4396. TemplateParameterList* Params = D->getTemplateParameterList(i);
  4397. for (TemplateParameterList::iterator Param = Params->begin(),
  4398. ParamEnd = Params->end();
  4399. Param != ParamEnd; ++Param) {
  4400. NamedDecl *Named = cast<NamedDecl>(*Param);
  4401. if (Named->getDeclName()) {
  4402. S->AddDecl(Named);
  4403. IdResolver.AddDecl(Named);
  4404. }
  4405. }
  4406. }
  4407. }
  4408. void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  4409. if (!D)
  4410. return;
  4411. TemplateParameterList *Params = 0;
  4412. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
  4413. Params = Template->getTemplateParameters();
  4414. else if (ClassTemplatePartialSpecializationDecl *PartialSpec
  4415. = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  4416. Params = PartialSpec->getTemplateParameters();
  4417. else
  4418. return;
  4419. for (TemplateParameterList::iterator Param = Params->begin(),
  4420. ParamEnd = Params->end();
  4421. Param != ParamEnd; ++Param) {
  4422. NamedDecl *Named = cast<NamedDecl>(*Param);
  4423. if (Named->getDeclName()) {
  4424. S->AddDecl(Named);
  4425. IdResolver.AddDecl(Named);
  4426. }
  4427. }
  4428. }
  4429. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  4430. if (!RecordD) return;
  4431. AdjustDeclIfTemplate(RecordD);
  4432. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  4433. PushDeclContext(S, Record);
  4434. }
  4435. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  4436. if (!RecordD) return;
  4437. PopDeclContext();
  4438. }
  4439. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  4440. /// parsing a top-level (non-nested) C++ class, and we are now
  4441. /// parsing those parts of the given Method declaration that could
  4442. /// not be parsed earlier (C++ [class.mem]p2), such as default
  4443. /// arguments. This action should enter the scope of the given
  4444. /// Method declaration as if we had just parsed the qualified method
  4445. /// name. However, it should not bring the parameters into scope;
  4446. /// that will be performed by ActOnDelayedCXXMethodParameter.
  4447. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  4448. }
  4449. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  4450. /// C++ method declaration. We're (re-)introducing the given
  4451. /// function parameter into scope for use in parsing later parts of
  4452. /// the method declaration. For example, we could see an
  4453. /// ActOnParamDefaultArgument event for this parameter.
  4454. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  4455. if (!ParamD)
  4456. return;
  4457. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  4458. // If this parameter has an unparsed default argument, clear it out
  4459. // to make way for the parsed default argument.
  4460. if (Param->hasUnparsedDefaultArg())
  4461. Param->setDefaultArg(0);
  4462. S->AddDecl(Param);
  4463. if (Param->getDeclName())
  4464. IdResolver.AddDecl(Param);
  4465. }
  4466. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  4467. /// processing the delayed method declaration for Method. The method
  4468. /// declaration is now considered finished. There may be a separate
  4469. /// ActOnStartOfFunctionDef action later (not necessarily
  4470. /// immediately!) for this method, if it was also defined inside the
  4471. /// class body.
  4472. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  4473. if (!MethodD)
  4474. return;
  4475. AdjustDeclIfTemplate(MethodD);
  4476. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  4477. // Now that we have our default arguments, check the constructor
  4478. // again. It could produce additional diagnostics or affect whether
  4479. // the class has implicitly-declared destructors, among other
  4480. // things.
  4481. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  4482. CheckConstructor(Constructor);
  4483. // Check the default arguments, which we may have added.
  4484. if (!Method->isInvalidDecl())
  4485. CheckCXXDefaultArguments(Method);
  4486. }
  4487. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  4488. /// the well-formedness of the constructor declarator @p D with type @p
  4489. /// R. If there are any errors in the declarator, this routine will
  4490. /// emit diagnostics and set the invalid bit to true. In any case, the type
  4491. /// will be updated to reflect a well-formed type for the constructor and
  4492. /// returned.
  4493. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  4494. StorageClass &SC) {
  4495. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  4496. // C++ [class.ctor]p3:
  4497. // A constructor shall not be virtual (10.3) or static (9.4). A
  4498. // constructor can be invoked for a const, volatile or const
  4499. // volatile object. A constructor shall not be declared const,
  4500. // volatile, or const volatile (9.3.2).
  4501. if (isVirtual) {
  4502. if (!D.isInvalidType())
  4503. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  4504. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  4505. << SourceRange(D.getIdentifierLoc());
  4506. D.setInvalidType();
  4507. }
  4508. if (SC == SC_Static) {
  4509. if (!D.isInvalidType())
  4510. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  4511. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  4512. << SourceRange(D.getIdentifierLoc());
  4513. D.setInvalidType();
  4514. SC = SC_None;
  4515. }
  4516. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  4517. if (FTI.TypeQuals != 0) {
  4518. if (FTI.TypeQuals & Qualifiers::Const)
  4519. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  4520. << "const" << SourceRange(D.getIdentifierLoc());
  4521. if (FTI.TypeQuals & Qualifiers::Volatile)
  4522. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  4523. << "volatile" << SourceRange(D.getIdentifierLoc());
  4524. if (FTI.TypeQuals & Qualifiers::Restrict)
  4525. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  4526. << "restrict" << SourceRange(D.getIdentifierLoc());
  4527. D.setInvalidType();
  4528. }
  4529. // C++0x [class.ctor]p4:
  4530. // A constructor shall not be declared with a ref-qualifier.
  4531. if (FTI.hasRefQualifier()) {
  4532. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  4533. << FTI.RefQualifierIsLValueRef
  4534. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  4535. D.setInvalidType();
  4536. }
  4537. // Rebuild the function type "R" without any type qualifiers (in
  4538. // case any of the errors above fired) and with "void" as the
  4539. // return type, since constructors don't have return types.
  4540. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  4541. if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
  4542. return R;
  4543. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  4544. EPI.TypeQuals = 0;
  4545. EPI.RefQualifier = RQ_None;
  4546. return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
  4547. Proto->getNumArgs(), EPI);
  4548. }
  4549. /// CheckConstructor - Checks a fully-formed constructor for
  4550. /// well-formedness, issuing any diagnostics required. Returns true if
  4551. /// the constructor declarator is invalid.
  4552. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  4553. CXXRecordDecl *ClassDecl
  4554. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  4555. if (!ClassDecl)
  4556. return Constructor->setInvalidDecl();
  4557. // C++ [class.copy]p3:
  4558. // A declaration of a constructor for a class X is ill-formed if
  4559. // its first parameter is of type (optionally cv-qualified) X and
  4560. // either there are no other parameters or else all other
  4561. // parameters have default arguments.
  4562. if (!Constructor->isInvalidDecl() &&
  4563. ((Constructor->getNumParams() == 1) ||
  4564. (Constructor->getNumParams() > 1 &&
  4565. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  4566. Constructor->getTemplateSpecializationKind()
  4567. != TSK_ImplicitInstantiation) {
  4568. QualType ParamType = Constructor->getParamDecl(0)->getType();
  4569. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  4570. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  4571. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  4572. const char *ConstRef
  4573. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  4574. : " const &";
  4575. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  4576. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  4577. // FIXME: Rather that making the constructor invalid, we should endeavor
  4578. // to fix the type.
  4579. Constructor->setInvalidDecl();
  4580. }
  4581. }
  4582. }
  4583. /// CheckDestructor - Checks a fully-formed destructor definition for
  4584. /// well-formedness, issuing any diagnostics required. Returns true
  4585. /// on error.
  4586. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  4587. CXXRecordDecl *RD = Destructor->getParent();
  4588. if (Destructor->isVirtual()) {
  4589. SourceLocation Loc;
  4590. if (!Destructor->isImplicit())
  4591. Loc = Destructor->getLocation();
  4592. else
  4593. Loc = RD->getLocation();
  4594. // If we have a virtual destructor, look up the deallocation function
  4595. FunctionDecl *OperatorDelete = 0;
  4596. DeclarationName Name =
  4597. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  4598. if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
  4599. return true;
  4600. MarkFunctionReferenced(Loc, OperatorDelete);
  4601. Destructor->setOperatorDelete(OperatorDelete);
  4602. }
  4603. return false;
  4604. }
  4605. static inline bool
  4606. FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
  4607. return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  4608. FTI.ArgInfo[0].Param &&
  4609. cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
  4610. }
  4611. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  4612. /// the well-formednes of the destructor declarator @p D with type @p
  4613. /// R. If there are any errors in the declarator, this routine will
  4614. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  4615. /// will be updated to reflect a well-formed type for the destructor and
  4616. /// returned.
  4617. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  4618. StorageClass& SC) {
  4619. // C++ [class.dtor]p1:
  4620. // [...] A typedef-name that names a class is a class-name
  4621. // (7.1.3); however, a typedef-name that names a class shall not
  4622. // be used as the identifier in the declarator for a destructor
  4623. // declaration.
  4624. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  4625. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  4626. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  4627. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  4628. else if (const TemplateSpecializationType *TST =
  4629. DeclaratorType->getAs<TemplateSpecializationType>())
  4630. if (TST->isTypeAlias())
  4631. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  4632. << DeclaratorType << 1;
  4633. // C++ [class.dtor]p2:
  4634. // A destructor is used to destroy objects of its class type. A
  4635. // destructor takes no parameters, and no return type can be
  4636. // specified for it (not even void). The address of a destructor
  4637. // shall not be taken. A destructor shall not be static. A
  4638. // destructor can be invoked for a const, volatile or const
  4639. // volatile object. A destructor shall not be declared const,
  4640. // volatile or const volatile (9.3.2).
  4641. if (SC == SC_Static) {
  4642. if (!D.isInvalidType())
  4643. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  4644. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  4645. << SourceRange(D.getIdentifierLoc())
  4646. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4647. SC = SC_None;
  4648. }
  4649. if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
  4650. // Destructors don't have return types, but the parser will
  4651. // happily parse something like:
  4652. //
  4653. // class X {
  4654. // float ~X();
  4655. // };
  4656. //
  4657. // The return type will be eliminated later.
  4658. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  4659. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4660. << SourceRange(D.getIdentifierLoc());
  4661. }
  4662. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  4663. if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
  4664. if (FTI.TypeQuals & Qualifiers::Const)
  4665. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  4666. << "const" << SourceRange(D.getIdentifierLoc());
  4667. if (FTI.TypeQuals & Qualifiers::Volatile)
  4668. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  4669. << "volatile" << SourceRange(D.getIdentifierLoc());
  4670. if (FTI.TypeQuals & Qualifiers::Restrict)
  4671. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  4672. << "restrict" << SourceRange(D.getIdentifierLoc());
  4673. D.setInvalidType();
  4674. }
  4675. // C++0x [class.dtor]p2:
  4676. // A destructor shall not be declared with a ref-qualifier.
  4677. if (FTI.hasRefQualifier()) {
  4678. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  4679. << FTI.RefQualifierIsLValueRef
  4680. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  4681. D.setInvalidType();
  4682. }
  4683. // Make sure we don't have any parameters.
  4684. if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
  4685. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  4686. // Delete the parameters.
  4687. FTI.freeArgs();
  4688. D.setInvalidType();
  4689. }
  4690. // Make sure the destructor isn't variadic.
  4691. if (FTI.isVariadic) {
  4692. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  4693. D.setInvalidType();
  4694. }
  4695. // Rebuild the function type "R" without any type qualifiers or
  4696. // parameters (in case any of the errors above fired) and with
  4697. // "void" as the return type, since destructors don't have return
  4698. // types.
  4699. if (!D.isInvalidType())
  4700. return R;
  4701. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  4702. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  4703. EPI.Variadic = false;
  4704. EPI.TypeQuals = 0;
  4705. EPI.RefQualifier = RQ_None;
  4706. return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
  4707. }
  4708. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  4709. /// well-formednes of the conversion function declarator @p D with
  4710. /// type @p R. If there are any errors in the declarator, this routine
  4711. /// will emit diagnostics and return true. Otherwise, it will return
  4712. /// false. Either way, the type @p R will be updated to reflect a
  4713. /// well-formed type for the conversion operator.
  4714. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  4715. StorageClass& SC) {
  4716. // C++ [class.conv.fct]p1:
  4717. // Neither parameter types nor return type can be specified. The
  4718. // type of a conversion function (8.3.5) is "function taking no
  4719. // parameter returning conversion-type-id."
  4720. if (SC == SC_Static) {
  4721. if (!D.isInvalidType())
  4722. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  4723. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  4724. << SourceRange(D.getIdentifierLoc());
  4725. D.setInvalidType();
  4726. SC = SC_None;
  4727. }
  4728. QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
  4729. if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
  4730. // Conversion functions don't have return types, but the parser will
  4731. // happily parse something like:
  4732. //
  4733. // class X {
  4734. // float operator bool();
  4735. // };
  4736. //
  4737. // The return type will be changed later anyway.
  4738. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  4739. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4740. << SourceRange(D.getIdentifierLoc());
  4741. D.setInvalidType();
  4742. }
  4743. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  4744. // Make sure we don't have any parameters.
  4745. if (Proto->getNumArgs() > 0) {
  4746. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  4747. // Delete the parameters.
  4748. D.getFunctionTypeInfo().freeArgs();
  4749. D.setInvalidType();
  4750. } else if (Proto->isVariadic()) {
  4751. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  4752. D.setInvalidType();
  4753. }
  4754. // Diagnose "&operator bool()" and other such nonsense. This
  4755. // is actually a gcc extension which we don't support.
  4756. if (Proto->getResultType() != ConvType) {
  4757. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
  4758. << Proto->getResultType();
  4759. D.setInvalidType();
  4760. ConvType = Proto->getResultType();
  4761. }
  4762. // C++ [class.conv.fct]p4:
  4763. // The conversion-type-id shall not represent a function type nor
  4764. // an array type.
  4765. if (ConvType->isArrayType()) {
  4766. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  4767. ConvType = Context.getPointerType(ConvType);
  4768. D.setInvalidType();
  4769. } else if (ConvType->isFunctionType()) {
  4770. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  4771. ConvType = Context.getPointerType(ConvType);
  4772. D.setInvalidType();
  4773. }
  4774. // Rebuild the function type "R" without any parameters (in case any
  4775. // of the errors above fired) and with the conversion type as the
  4776. // return type.
  4777. if (D.isInvalidType())
  4778. R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
  4779. // C++0x explicit conversion operators.
  4780. if (D.getDeclSpec().isExplicitSpecified())
  4781. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4782. getLangOptions().CPlusPlus0x ?
  4783. diag::warn_cxx98_compat_explicit_conversion_functions :
  4784. diag::ext_explicit_conversion_functions)
  4785. << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
  4786. }
  4787. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  4788. /// the declaration of the given C++ conversion function. This routine
  4789. /// is responsible for recording the conversion function in the C++
  4790. /// class, if possible.
  4791. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  4792. assert(Conversion && "Expected to receive a conversion function declaration");
  4793. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  4794. // Make sure we aren't redeclaring the conversion function.
  4795. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  4796. // C++ [class.conv.fct]p1:
  4797. // [...] A conversion function is never used to convert a
  4798. // (possibly cv-qualified) object to the (possibly cv-qualified)
  4799. // same object type (or a reference to it), to a (possibly
  4800. // cv-qualified) base class of that type (or a reference to it),
  4801. // or to (possibly cv-qualified) void.
  4802. // FIXME: Suppress this warning if the conversion function ends up being a
  4803. // virtual function that overrides a virtual function in a base class.
  4804. QualType ClassType
  4805. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  4806. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  4807. ConvType = ConvTypeRef->getPointeeType();
  4808. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  4809. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  4810. /* Suppress diagnostics for instantiations. */;
  4811. else if (ConvType->isRecordType()) {
  4812. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  4813. if (ConvType == ClassType)
  4814. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  4815. << ClassType;
  4816. else if (IsDerivedFrom(ClassType, ConvType))
  4817. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  4818. << ClassType << ConvType;
  4819. } else if (ConvType->isVoidType()) {
  4820. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  4821. << ClassType << ConvType;
  4822. }
  4823. if (FunctionTemplateDecl *ConversionTemplate
  4824. = Conversion->getDescribedFunctionTemplate())
  4825. return ConversionTemplate;
  4826. return Conversion;
  4827. }
  4828. //===----------------------------------------------------------------------===//
  4829. // Namespace Handling
  4830. //===----------------------------------------------------------------------===//
  4831. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  4832. /// definition.
  4833. Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
  4834. SourceLocation InlineLoc,
  4835. SourceLocation NamespaceLoc,
  4836. SourceLocation IdentLoc,
  4837. IdentifierInfo *II,
  4838. SourceLocation LBrace,
  4839. AttributeList *AttrList) {
  4840. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  4841. // For anonymous namespace, take the location of the left brace.
  4842. SourceLocation Loc = II ? IdentLoc : LBrace;
  4843. bool IsInline = InlineLoc.isValid();
  4844. bool IsInvalid = false;
  4845. bool IsStd = false;
  4846. bool AddToKnown = false;
  4847. Scope *DeclRegionScope = NamespcScope->getParent();
  4848. NamespaceDecl *PrevNS = 0;
  4849. if (II) {
  4850. // C++ [namespace.def]p2:
  4851. // The identifier in an original-namespace-definition shall not
  4852. // have been previously defined in the declarative region in
  4853. // which the original-namespace-definition appears. The
  4854. // identifier in an original-namespace-definition is the name of
  4855. // the namespace. Subsequently in that declarative region, it is
  4856. // treated as an original-namespace-name.
  4857. //
  4858. // Since namespace names are unique in their scope, and we don't
  4859. // look through using directives, just look for any ordinary names.
  4860. const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
  4861. Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
  4862. Decl::IDNS_Namespace;
  4863. NamedDecl *PrevDecl = 0;
  4864. for (DeclContext::lookup_result R
  4865. = CurContext->getRedeclContext()->lookup(II);
  4866. R.first != R.second; ++R.first) {
  4867. if ((*R.first)->getIdentifierNamespace() & IDNS) {
  4868. PrevDecl = *R.first;
  4869. break;
  4870. }
  4871. }
  4872. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  4873. if (PrevNS) {
  4874. // This is an extended namespace definition.
  4875. if (IsInline != PrevNS->isInline()) {
  4876. // inline-ness must match
  4877. if (PrevNS->isInline()) {
  4878. // The user probably just forgot the 'inline', so suggest that it
  4879. // be added back.
  4880. Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  4881. << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
  4882. } else {
  4883. Diag(Loc, diag::err_inline_namespace_mismatch)
  4884. << IsInline;
  4885. }
  4886. Diag(PrevNS->getLocation(), diag::note_previous_definition);
  4887. IsInline = PrevNS->isInline();
  4888. }
  4889. } else if (PrevDecl) {
  4890. // This is an invalid name redefinition.
  4891. Diag(Loc, diag::err_redefinition_different_kind)
  4892. << II;
  4893. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  4894. IsInvalid = true;
  4895. // Continue on to push Namespc as current DeclContext and return it.
  4896. } else if (II->isStr("std") &&
  4897. CurContext->getRedeclContext()->isTranslationUnit()) {
  4898. // This is the first "real" definition of the namespace "std", so update
  4899. // our cache of the "std" namespace to point at this definition.
  4900. PrevNS = getStdNamespace();
  4901. IsStd = true;
  4902. AddToKnown = !IsInline;
  4903. } else {
  4904. // We've seen this namespace for the first time.
  4905. AddToKnown = !IsInline;
  4906. }
  4907. } else {
  4908. // Anonymous namespaces.
  4909. // Determine whether the parent already has an anonymous namespace.
  4910. DeclContext *Parent = CurContext->getRedeclContext();
  4911. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  4912. PrevNS = TU->getAnonymousNamespace();
  4913. } else {
  4914. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  4915. PrevNS = ND->getAnonymousNamespace();
  4916. }
  4917. if (PrevNS && IsInline != PrevNS->isInline()) {
  4918. // inline-ness must match
  4919. Diag(Loc, diag::err_inline_namespace_mismatch)
  4920. << IsInline;
  4921. Diag(PrevNS->getLocation(), diag::note_previous_definition);
  4922. // Recover by ignoring the new namespace's inline status.
  4923. IsInline = PrevNS->isInline();
  4924. }
  4925. }
  4926. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  4927. StartLoc, Loc, II, PrevNS);
  4928. if (IsInvalid)
  4929. Namespc->setInvalidDecl();
  4930. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  4931. // FIXME: Should we be merging attributes?
  4932. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  4933. PushNamespaceVisibilityAttr(Attr, Loc);
  4934. if (IsStd)
  4935. StdNamespace = Namespc;
  4936. if (AddToKnown)
  4937. KnownNamespaces[Namespc] = false;
  4938. if (II) {
  4939. PushOnScopeChains(Namespc, DeclRegionScope);
  4940. } else {
  4941. // Link the anonymous namespace into its parent.
  4942. DeclContext *Parent = CurContext->getRedeclContext();
  4943. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  4944. TU->setAnonymousNamespace(Namespc);
  4945. } else {
  4946. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  4947. }
  4948. CurContext->addDecl(Namespc);
  4949. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  4950. // behaves as if it were replaced by
  4951. // namespace unique { /* empty body */ }
  4952. // using namespace unique;
  4953. // namespace unique { namespace-body }
  4954. // where all occurrences of 'unique' in a translation unit are
  4955. // replaced by the same identifier and this identifier differs
  4956. // from all other identifiers in the entire program.
  4957. // We just create the namespace with an empty name and then add an
  4958. // implicit using declaration, just like the standard suggests.
  4959. //
  4960. // CodeGen enforces the "universally unique" aspect by giving all
  4961. // declarations semantically contained within an anonymous
  4962. // namespace internal linkage.
  4963. if (!PrevNS) {
  4964. UsingDirectiveDecl* UD
  4965. = UsingDirectiveDecl::Create(Context, CurContext,
  4966. /* 'using' */ LBrace,
  4967. /* 'namespace' */ SourceLocation(),
  4968. /* qualifier */ NestedNameSpecifierLoc(),
  4969. /* identifier */ SourceLocation(),
  4970. Namespc,
  4971. /* Ancestor */ CurContext);
  4972. UD->setImplicit();
  4973. CurContext->addDecl(UD);
  4974. }
  4975. }
  4976. // Although we could have an invalid decl (i.e. the namespace name is a
  4977. // redefinition), push it as current DeclContext and try to continue parsing.
  4978. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  4979. // for the namespace has the declarations that showed up in that particular
  4980. // namespace definition.
  4981. PushDeclContext(NamespcScope, Namespc);
  4982. return Namespc;
  4983. }
  4984. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  4985. /// is a namespace alias, returns the namespace it points to.
  4986. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  4987. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  4988. return AD->getNamespace();
  4989. return dyn_cast_or_null<NamespaceDecl>(D);
  4990. }
  4991. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  4992. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  4993. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  4994. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  4995. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  4996. Namespc->setRBraceLoc(RBrace);
  4997. PopDeclContext();
  4998. if (Namespc->hasAttr<VisibilityAttr>())
  4999. PopPragmaVisibility(true, RBrace);
  5000. }
  5001. CXXRecordDecl *Sema::getStdBadAlloc() const {
  5002. return cast_or_null<CXXRecordDecl>(
  5003. StdBadAlloc.get(Context.getExternalSource()));
  5004. }
  5005. NamespaceDecl *Sema::getStdNamespace() const {
  5006. return cast_or_null<NamespaceDecl>(
  5007. StdNamespace.get(Context.getExternalSource()));
  5008. }
  5009. /// \brief Retrieve the special "std" namespace, which may require us to
  5010. /// implicitly define the namespace.
  5011. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  5012. if (!StdNamespace) {
  5013. // The "std" namespace has not yet been defined, so build one implicitly.
  5014. StdNamespace = NamespaceDecl::Create(Context,
  5015. Context.getTranslationUnitDecl(),
  5016. /*Inline=*/false,
  5017. SourceLocation(), SourceLocation(),
  5018. &PP.getIdentifierTable().get("std"),
  5019. /*PrevDecl=*/0);
  5020. getStdNamespace()->setImplicit(true);
  5021. }
  5022. return getStdNamespace();
  5023. }
  5024. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  5025. assert(getLangOptions().CPlusPlus &&
  5026. "Looking for std::initializer_list outside of C++.");
  5027. // We're looking for implicit instantiations of
  5028. // template <typename E> class std::initializer_list.
  5029. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  5030. return false;
  5031. ClassTemplateDecl *Template = 0;
  5032. const TemplateArgument *Arguments = 0;
  5033. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  5034. ClassTemplateSpecializationDecl *Specialization =
  5035. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  5036. if (!Specialization)
  5037. return false;
  5038. Template = Specialization->getSpecializedTemplate();
  5039. Arguments = Specialization->getTemplateArgs().data();
  5040. } else if (const TemplateSpecializationType *TST =
  5041. Ty->getAs<TemplateSpecializationType>()) {
  5042. Template = dyn_cast_or_null<ClassTemplateDecl>(
  5043. TST->getTemplateName().getAsTemplateDecl());
  5044. Arguments = TST->getArgs();
  5045. }
  5046. if (!Template)
  5047. return false;
  5048. if (!StdInitializerList) {
  5049. // Haven't recognized std::initializer_list yet, maybe this is it.
  5050. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  5051. if (TemplateClass->getIdentifier() !=
  5052. &PP.getIdentifierTable().get("initializer_list") ||
  5053. !getStdNamespace()->InEnclosingNamespaceSetOf(
  5054. TemplateClass->getDeclContext()))
  5055. return false;
  5056. // This is a template called std::initializer_list, but is it the right
  5057. // template?
  5058. TemplateParameterList *Params = Template->getTemplateParameters();
  5059. if (Params->getMinRequiredArguments() != 1)
  5060. return false;
  5061. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  5062. return false;
  5063. // It's the right template.
  5064. StdInitializerList = Template;
  5065. }
  5066. if (Template != StdInitializerList)
  5067. return false;
  5068. // This is an instance of std::initializer_list. Find the argument type.
  5069. if (Element)
  5070. *Element = Arguments[0].getAsType();
  5071. return true;
  5072. }
  5073. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  5074. NamespaceDecl *Std = S.getStdNamespace();
  5075. if (!Std) {
  5076. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  5077. return 0;
  5078. }
  5079. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  5080. Loc, Sema::LookupOrdinaryName);
  5081. if (!S.LookupQualifiedName(Result, Std)) {
  5082. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  5083. return 0;
  5084. }
  5085. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  5086. if (!Template) {
  5087. Result.suppressDiagnostics();
  5088. // We found something weird. Complain about the first thing we found.
  5089. NamedDecl *Found = *Result.begin();
  5090. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  5091. return 0;
  5092. }
  5093. // We found some template called std::initializer_list. Now verify that it's
  5094. // correct.
  5095. TemplateParameterList *Params = Template->getTemplateParameters();
  5096. if (Params->getMinRequiredArguments() != 1 ||
  5097. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  5098. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  5099. return 0;
  5100. }
  5101. return Template;
  5102. }
  5103. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  5104. if (!StdInitializerList) {
  5105. StdInitializerList = LookupStdInitializerList(*this, Loc);
  5106. if (!StdInitializerList)
  5107. return QualType();
  5108. }
  5109. TemplateArgumentListInfo Args(Loc, Loc);
  5110. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  5111. Context.getTrivialTypeSourceInfo(Element,
  5112. Loc)));
  5113. return Context.getCanonicalType(
  5114. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  5115. }
  5116. bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
  5117. // C++ [dcl.init.list]p2:
  5118. // A constructor is an initializer-list constructor if its first parameter
  5119. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  5120. // std::initializer_list<E> for some type E, and either there are no other
  5121. // parameters or else all other parameters have default arguments.
  5122. if (Ctor->getNumParams() < 1 ||
  5123. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  5124. return false;
  5125. QualType ArgType = Ctor->getParamDecl(0)->getType();
  5126. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  5127. ArgType = RT->getPointeeType().getUnqualifiedType();
  5128. return isStdInitializerList(ArgType, 0);
  5129. }
  5130. /// \brief Determine whether a using statement is in a context where it will be
  5131. /// apply in all contexts.
  5132. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  5133. switch (CurContext->getDeclKind()) {
  5134. case Decl::TranslationUnit:
  5135. return true;
  5136. case Decl::LinkageSpec:
  5137. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  5138. default:
  5139. return false;
  5140. }
  5141. }
  5142. namespace {
  5143. // Callback to only accept typo corrections that are namespaces.
  5144. class NamespaceValidatorCCC : public CorrectionCandidateCallback {
  5145. public:
  5146. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  5147. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  5148. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  5149. }
  5150. return false;
  5151. }
  5152. };
  5153. }
  5154. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  5155. CXXScopeSpec &SS,
  5156. SourceLocation IdentLoc,
  5157. IdentifierInfo *Ident) {
  5158. NamespaceValidatorCCC Validator;
  5159. R.clear();
  5160. if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
  5161. R.getLookupKind(), Sc, &SS,
  5162. Validator)) {
  5163. std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
  5164. std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
  5165. if (DeclContext *DC = S.computeDeclContext(SS, false))
  5166. S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
  5167. << Ident << DC << CorrectedQuotedStr << SS.getRange()
  5168. << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
  5169. else
  5170. S.Diag(IdentLoc, diag::err_using_directive_suggest)
  5171. << Ident << CorrectedQuotedStr
  5172. << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
  5173. S.Diag(Corrected.getCorrectionDecl()->getLocation(),
  5174. diag::note_namespace_defined_here) << CorrectedQuotedStr;
  5175. Ident = Corrected.getCorrectionAsIdentifierInfo();
  5176. R.addDecl(Corrected.getCorrectionDecl());
  5177. return true;
  5178. }
  5179. return false;
  5180. }
  5181. Decl *Sema::ActOnUsingDirective(Scope *S,
  5182. SourceLocation UsingLoc,
  5183. SourceLocation NamespcLoc,
  5184. CXXScopeSpec &SS,
  5185. SourceLocation IdentLoc,
  5186. IdentifierInfo *NamespcName,
  5187. AttributeList *AttrList) {
  5188. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  5189. assert(NamespcName && "Invalid NamespcName.");
  5190. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  5191. // This can only happen along a recovery path.
  5192. while (S->getFlags() & Scope::TemplateParamScope)
  5193. S = S->getParent();
  5194. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  5195. UsingDirectiveDecl *UDir = 0;
  5196. NestedNameSpecifier *Qualifier = 0;
  5197. if (SS.isSet())
  5198. Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
  5199. // Lookup namespace name.
  5200. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  5201. LookupParsedName(R, S, &SS);
  5202. if (R.isAmbiguous())
  5203. return 0;
  5204. if (R.empty()) {
  5205. R.clear();
  5206. // Allow "using namespace std;" or "using namespace ::std;" even if
  5207. // "std" hasn't been defined yet, for GCC compatibility.
  5208. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  5209. NamespcName->isStr("std")) {
  5210. Diag(IdentLoc, diag::ext_using_undefined_std);
  5211. R.addDecl(getOrCreateStdNamespace());
  5212. R.resolveKind();
  5213. }
  5214. // Otherwise, attempt typo correction.
  5215. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  5216. }
  5217. if (!R.empty()) {
  5218. NamedDecl *Named = R.getFoundDecl();
  5219. assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
  5220. && "expected namespace decl");
  5221. // C++ [namespace.udir]p1:
  5222. // A using-directive specifies that the names in the nominated
  5223. // namespace can be used in the scope in which the
  5224. // using-directive appears after the using-directive. During
  5225. // unqualified name lookup (3.4.1), the names appear as if they
  5226. // were declared in the nearest enclosing namespace which
  5227. // contains both the using-directive and the nominated
  5228. // namespace. [Note: in this context, "contains" means "contains
  5229. // directly or indirectly". ]
  5230. // Find enclosing context containing both using-directive and
  5231. // nominated namespace.
  5232. NamespaceDecl *NS = getNamespaceDecl(Named);
  5233. DeclContext *CommonAncestor = cast<DeclContext>(NS);
  5234. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  5235. CommonAncestor = CommonAncestor->getParent();
  5236. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  5237. SS.getWithLocInContext(Context),
  5238. IdentLoc, Named, CommonAncestor);
  5239. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  5240. !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  5241. Diag(IdentLoc, diag::warn_using_directive_in_header);
  5242. }
  5243. PushUsingDirective(S, UDir);
  5244. } else {
  5245. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  5246. }
  5247. // FIXME: We ignore attributes for now.
  5248. return UDir;
  5249. }
  5250. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  5251. // If scope has associated entity, then using directive is at namespace
  5252. // or translation unit scope. We add UsingDirectiveDecls, into
  5253. // it's lookup structure.
  5254. if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
  5255. Ctx->addDecl(UDir);
  5256. else
  5257. // Otherwise it is block-sope. using-directives will affect lookup
  5258. // only to the end of scope.
  5259. S->PushUsingDirective(UDir);
  5260. }
  5261. Decl *Sema::ActOnUsingDeclaration(Scope *S,
  5262. AccessSpecifier AS,
  5263. bool HasUsingKeyword,
  5264. SourceLocation UsingLoc,
  5265. CXXScopeSpec &SS,
  5266. UnqualifiedId &Name,
  5267. AttributeList *AttrList,
  5268. bool IsTypeName,
  5269. SourceLocation TypenameLoc) {
  5270. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  5271. switch (Name.getKind()) {
  5272. case UnqualifiedId::IK_ImplicitSelfParam:
  5273. case UnqualifiedId::IK_Identifier:
  5274. case UnqualifiedId::IK_OperatorFunctionId:
  5275. case UnqualifiedId::IK_LiteralOperatorId:
  5276. case UnqualifiedId::IK_ConversionFunctionId:
  5277. break;
  5278. case UnqualifiedId::IK_ConstructorName:
  5279. case UnqualifiedId::IK_ConstructorTemplateId:
  5280. // C++0x inherited constructors.
  5281. Diag(Name.getSourceRange().getBegin(),
  5282. getLangOptions().CPlusPlus0x ?
  5283. diag::warn_cxx98_compat_using_decl_constructor :
  5284. diag::err_using_decl_constructor)
  5285. << SS.getRange();
  5286. if (getLangOptions().CPlusPlus0x) break;
  5287. return 0;
  5288. case UnqualifiedId::IK_DestructorName:
  5289. Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
  5290. << SS.getRange();
  5291. return 0;
  5292. case UnqualifiedId::IK_TemplateId:
  5293. Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
  5294. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  5295. return 0;
  5296. }
  5297. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  5298. DeclarationName TargetName = TargetNameInfo.getName();
  5299. if (!TargetName)
  5300. return 0;
  5301. // Warn about using declarations.
  5302. // TODO: store that the declaration was written without 'using' and
  5303. // talk about access decls instead of using decls in the
  5304. // diagnostics.
  5305. if (!HasUsingKeyword) {
  5306. UsingLoc = Name.getSourceRange().getBegin();
  5307. Diag(UsingLoc, diag::warn_access_decl_deprecated)
  5308. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  5309. }
  5310. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  5311. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  5312. return 0;
  5313. NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
  5314. TargetNameInfo, AttrList,
  5315. /* IsInstantiation */ false,
  5316. IsTypeName, TypenameLoc);
  5317. if (UD)
  5318. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  5319. return UD;
  5320. }
  5321. /// \brief Determine whether a using declaration considers the given
  5322. /// declarations as "equivalent", e.g., if they are redeclarations of
  5323. /// the same entity or are both typedefs of the same type.
  5324. static bool
  5325. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
  5326. bool &SuppressRedeclaration) {
  5327. if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
  5328. SuppressRedeclaration = false;
  5329. return true;
  5330. }
  5331. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  5332. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
  5333. SuppressRedeclaration = true;
  5334. return Context.hasSameType(TD1->getUnderlyingType(),
  5335. TD2->getUnderlyingType());
  5336. }
  5337. return false;
  5338. }
  5339. /// Determines whether to create a using shadow decl for a particular
  5340. /// decl, given the set of decls existing prior to this using lookup.
  5341. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  5342. const LookupResult &Previous) {
  5343. // Diagnose finding a decl which is not from a base class of the
  5344. // current class. We do this now because there are cases where this
  5345. // function will silently decide not to build a shadow decl, which
  5346. // will pre-empt further diagnostics.
  5347. //
  5348. // We don't need to do this in C++0x because we do the check once on
  5349. // the qualifier.
  5350. //
  5351. // FIXME: diagnose the following if we care enough:
  5352. // struct A { int foo; };
  5353. // struct B : A { using A::foo; };
  5354. // template <class T> struct C : A {};
  5355. // template <class T> struct D : C<T> { using B::foo; } // <---
  5356. // This is invalid (during instantiation) in C++03 because B::foo
  5357. // resolves to the using decl in B, which is not a base class of D<T>.
  5358. // We can't diagnose it immediately because C<T> is an unknown
  5359. // specialization. The UsingShadowDecl in D<T> then points directly
  5360. // to A::foo, which will look well-formed when we instantiate.
  5361. // The right solution is to not collapse the shadow-decl chain.
  5362. if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
  5363. DeclContext *OrigDC = Orig->getDeclContext();
  5364. // Handle enums and anonymous structs.
  5365. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  5366. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  5367. while (OrigRec->isAnonymousStructOrUnion())
  5368. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  5369. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  5370. if (OrigDC == CurContext) {
  5371. Diag(Using->getLocation(),
  5372. diag::err_using_decl_nested_name_specifier_is_current_class)
  5373. << Using->getQualifierLoc().getSourceRange();
  5374. Diag(Orig->getLocation(), diag::note_using_decl_target);
  5375. return true;
  5376. }
  5377. Diag(Using->getQualifierLoc().getBeginLoc(),
  5378. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  5379. << Using->getQualifier()
  5380. << cast<CXXRecordDecl>(CurContext)
  5381. << Using->getQualifierLoc().getSourceRange();
  5382. Diag(Orig->getLocation(), diag::note_using_decl_target);
  5383. return true;
  5384. }
  5385. }
  5386. if (Previous.empty()) return false;
  5387. NamedDecl *Target = Orig;
  5388. if (isa<UsingShadowDecl>(Target))
  5389. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  5390. // If the target happens to be one of the previous declarations, we
  5391. // don't have a conflict.
  5392. //
  5393. // FIXME: but we might be increasing its access, in which case we
  5394. // should redeclare it.
  5395. NamedDecl *NonTag = 0, *Tag = 0;
  5396. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5397. I != E; ++I) {
  5398. NamedDecl *D = (*I)->getUnderlyingDecl();
  5399. bool Result;
  5400. if (IsEquivalentForUsingDecl(Context, D, Target, Result))
  5401. return Result;
  5402. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  5403. }
  5404. if (Target->isFunctionOrFunctionTemplate()) {
  5405. FunctionDecl *FD;
  5406. if (isa<FunctionTemplateDecl>(Target))
  5407. FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
  5408. else
  5409. FD = cast<FunctionDecl>(Target);
  5410. NamedDecl *OldDecl = 0;
  5411. switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
  5412. case Ovl_Overload:
  5413. return false;
  5414. case Ovl_NonFunction:
  5415. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  5416. break;
  5417. // We found a decl with the exact signature.
  5418. case Ovl_Match:
  5419. // If we're in a record, we want to hide the target, so we
  5420. // return true (without a diagnostic) to tell the caller not to
  5421. // build a shadow decl.
  5422. if (CurContext->isRecord())
  5423. return true;
  5424. // If we're not in a record, this is an error.
  5425. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  5426. break;
  5427. }
  5428. Diag(Target->getLocation(), diag::note_using_decl_target);
  5429. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  5430. return true;
  5431. }
  5432. // Target is not a function.
  5433. if (isa<TagDecl>(Target)) {
  5434. // No conflict between a tag and a non-tag.
  5435. if (!Tag) return false;
  5436. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  5437. Diag(Target->getLocation(), diag::note_using_decl_target);
  5438. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  5439. return true;
  5440. }
  5441. // No conflict between a tag and a non-tag.
  5442. if (!NonTag) return false;
  5443. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  5444. Diag(Target->getLocation(), diag::note_using_decl_target);
  5445. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  5446. return true;
  5447. }
  5448. /// Builds a shadow declaration corresponding to a 'using' declaration.
  5449. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  5450. UsingDecl *UD,
  5451. NamedDecl *Orig) {
  5452. // If we resolved to another shadow declaration, just coalesce them.
  5453. NamedDecl *Target = Orig;
  5454. if (isa<UsingShadowDecl>(Target)) {
  5455. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  5456. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  5457. }
  5458. UsingShadowDecl *Shadow
  5459. = UsingShadowDecl::Create(Context, CurContext,
  5460. UD->getLocation(), UD, Target);
  5461. UD->addShadowDecl(Shadow);
  5462. Shadow->setAccess(UD->getAccess());
  5463. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  5464. Shadow->setInvalidDecl();
  5465. if (S)
  5466. PushOnScopeChains(Shadow, S);
  5467. else
  5468. CurContext->addDecl(Shadow);
  5469. return Shadow;
  5470. }
  5471. /// Hides a using shadow declaration. This is required by the current
  5472. /// using-decl implementation when a resolvable using declaration in a
  5473. /// class is followed by a declaration which would hide or override
  5474. /// one or more of the using decl's targets; for example:
  5475. ///
  5476. /// struct Base { void foo(int); };
  5477. /// struct Derived : Base {
  5478. /// using Base::foo;
  5479. /// void foo(int);
  5480. /// };
  5481. ///
  5482. /// The governing language is C++03 [namespace.udecl]p12:
  5483. ///
  5484. /// When a using-declaration brings names from a base class into a
  5485. /// derived class scope, member functions in the derived class
  5486. /// override and/or hide member functions with the same name and
  5487. /// parameter types in a base class (rather than conflicting).
  5488. ///
  5489. /// There are two ways to implement this:
  5490. /// (1) optimistically create shadow decls when they're not hidden
  5491. /// by existing declarations, or
  5492. /// (2) don't create any shadow decls (or at least don't make them
  5493. /// visible) until we've fully parsed/instantiated the class.
  5494. /// The problem with (1) is that we might have to retroactively remove
  5495. /// a shadow decl, which requires several O(n) operations because the
  5496. /// decl structures are (very reasonably) not designed for removal.
  5497. /// (2) avoids this but is very fiddly and phase-dependent.
  5498. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  5499. if (Shadow->getDeclName().getNameKind() ==
  5500. DeclarationName::CXXConversionFunctionName)
  5501. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  5502. // Remove it from the DeclContext...
  5503. Shadow->getDeclContext()->removeDecl(Shadow);
  5504. // ...and the scope, if applicable...
  5505. if (S) {
  5506. S->RemoveDecl(Shadow);
  5507. IdResolver.RemoveDecl(Shadow);
  5508. }
  5509. // ...and the using decl.
  5510. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  5511. // TODO: complain somehow if Shadow was used. It shouldn't
  5512. // be possible for this to happen, because...?
  5513. }
  5514. /// Builds a using declaration.
  5515. ///
  5516. /// \param IsInstantiation - Whether this call arises from an
  5517. /// instantiation of an unresolved using declaration. We treat
  5518. /// the lookup differently for these declarations.
  5519. NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
  5520. SourceLocation UsingLoc,
  5521. CXXScopeSpec &SS,
  5522. const DeclarationNameInfo &NameInfo,
  5523. AttributeList *AttrList,
  5524. bool IsInstantiation,
  5525. bool IsTypeName,
  5526. SourceLocation TypenameLoc) {
  5527. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  5528. SourceLocation IdentLoc = NameInfo.getLoc();
  5529. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  5530. // FIXME: We ignore attributes for now.
  5531. if (SS.isEmpty()) {
  5532. Diag(IdentLoc, diag::err_using_requires_qualname);
  5533. return 0;
  5534. }
  5535. // Do the redeclaration lookup in the current scope.
  5536. LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
  5537. ForRedeclaration);
  5538. Previous.setHideTags(false);
  5539. if (S) {
  5540. LookupName(Previous, S);
  5541. // It is really dumb that we have to do this.
  5542. LookupResult::Filter F = Previous.makeFilter();
  5543. while (F.hasNext()) {
  5544. NamedDecl *D = F.next();
  5545. if (!isDeclInScope(D, CurContext, S))
  5546. F.erase();
  5547. }
  5548. F.done();
  5549. } else {
  5550. assert(IsInstantiation && "no scope in non-instantiation");
  5551. assert(CurContext->isRecord() && "scope not record in instantiation");
  5552. LookupQualifiedName(Previous, CurContext);
  5553. }
  5554. // Check for invalid redeclarations.
  5555. if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
  5556. return 0;
  5557. // Check for bad qualifiers.
  5558. if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
  5559. return 0;
  5560. DeclContext *LookupContext = computeDeclContext(SS);
  5561. NamedDecl *D;
  5562. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  5563. if (!LookupContext) {
  5564. if (IsTypeName) {
  5565. // FIXME: not all declaration name kinds are legal here
  5566. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  5567. UsingLoc, TypenameLoc,
  5568. QualifierLoc,
  5569. IdentLoc, NameInfo.getName());
  5570. } else {
  5571. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  5572. QualifierLoc, NameInfo);
  5573. }
  5574. } else {
  5575. D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
  5576. NameInfo, IsTypeName);
  5577. }
  5578. D->setAccess(AS);
  5579. CurContext->addDecl(D);
  5580. if (!LookupContext) return D;
  5581. UsingDecl *UD = cast<UsingDecl>(D);
  5582. if (RequireCompleteDeclContext(SS, LookupContext)) {
  5583. UD->setInvalidDecl();
  5584. return UD;
  5585. }
  5586. // Constructor inheriting using decls get special treatment.
  5587. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
  5588. if (CheckInheritedConstructorUsingDecl(UD))
  5589. UD->setInvalidDecl();
  5590. return UD;
  5591. }
  5592. // Otherwise, look up the target name.
  5593. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  5594. // Unlike most lookups, we don't always want to hide tag
  5595. // declarations: tag names are visible through the using declaration
  5596. // even if hidden by ordinary names, *except* in a dependent context
  5597. // where it's important for the sanity of two-phase lookup.
  5598. if (!IsInstantiation)
  5599. R.setHideTags(false);
  5600. LookupQualifiedName(R, LookupContext);
  5601. if (R.empty()) {
  5602. Diag(IdentLoc, diag::err_no_member)
  5603. << NameInfo.getName() << LookupContext << SS.getRange();
  5604. UD->setInvalidDecl();
  5605. return UD;
  5606. }
  5607. if (R.isAmbiguous()) {
  5608. UD->setInvalidDecl();
  5609. return UD;
  5610. }
  5611. if (IsTypeName) {
  5612. // If we asked for a typename and got a non-type decl, error out.
  5613. if (!R.getAsSingle<TypeDecl>()) {
  5614. Diag(IdentLoc, diag::err_using_typename_non_type);
  5615. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  5616. Diag((*I)->getUnderlyingDecl()->getLocation(),
  5617. diag::note_using_decl_target);
  5618. UD->setInvalidDecl();
  5619. return UD;
  5620. }
  5621. } else {
  5622. // If we asked for a non-typename and we got a type, error out,
  5623. // but only if this is an instantiation of an unresolved using
  5624. // decl. Otherwise just silently find the type name.
  5625. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  5626. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  5627. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  5628. UD->setInvalidDecl();
  5629. return UD;
  5630. }
  5631. }
  5632. // C++0x N2914 [namespace.udecl]p6:
  5633. // A using-declaration shall not name a namespace.
  5634. if (R.getAsSingle<NamespaceDecl>()) {
  5635. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  5636. << SS.getRange();
  5637. UD->setInvalidDecl();
  5638. return UD;
  5639. }
  5640. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5641. if (!CheckUsingShadowDecl(UD, *I, Previous))
  5642. BuildUsingShadowDecl(S, UD, *I);
  5643. }
  5644. return UD;
  5645. }
  5646. /// Additional checks for a using declaration referring to a constructor name.
  5647. bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
  5648. if (UD->isTypeName()) {
  5649. // FIXME: Cannot specify typename when specifying constructor
  5650. return true;
  5651. }
  5652. const Type *SourceType = UD->getQualifier()->getAsType();
  5653. assert(SourceType &&
  5654. "Using decl naming constructor doesn't have type in scope spec.");
  5655. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  5656. // Check whether the named type is a direct base class.
  5657. CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
  5658. CXXRecordDecl::base_class_iterator BaseIt, BaseE;
  5659. for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
  5660. BaseIt != BaseE; ++BaseIt) {
  5661. CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
  5662. if (CanonicalSourceType == BaseType)
  5663. break;
  5664. }
  5665. if (BaseIt == BaseE) {
  5666. // Did not find SourceType in the bases.
  5667. Diag(UD->getUsingLocation(),
  5668. diag::err_using_decl_constructor_not_in_direct_base)
  5669. << UD->getNameInfo().getSourceRange()
  5670. << QualType(SourceType, 0) << TargetClass;
  5671. return true;
  5672. }
  5673. BaseIt->setInheritConstructors();
  5674. return false;
  5675. }
  5676. /// Checks that the given using declaration is not an invalid
  5677. /// redeclaration. Note that this is checking only for the using decl
  5678. /// itself, not for any ill-formedness among the UsingShadowDecls.
  5679. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  5680. bool isTypeName,
  5681. const CXXScopeSpec &SS,
  5682. SourceLocation NameLoc,
  5683. const LookupResult &Prev) {
  5684. // C++03 [namespace.udecl]p8:
  5685. // C++0x [namespace.udecl]p10:
  5686. // A using-declaration is a declaration and can therefore be used
  5687. // repeatedly where (and only where) multiple declarations are
  5688. // allowed.
  5689. //
  5690. // That's in non-member contexts.
  5691. if (!CurContext->getRedeclContext()->isRecord())
  5692. return false;
  5693. NestedNameSpecifier *Qual
  5694. = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
  5695. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  5696. NamedDecl *D = *I;
  5697. bool DTypename;
  5698. NestedNameSpecifier *DQual;
  5699. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  5700. DTypename = UD->isTypeName();
  5701. DQual = UD->getQualifier();
  5702. } else if (UnresolvedUsingValueDecl *UD
  5703. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  5704. DTypename = false;
  5705. DQual = UD->getQualifier();
  5706. } else if (UnresolvedUsingTypenameDecl *UD
  5707. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  5708. DTypename = true;
  5709. DQual = UD->getQualifier();
  5710. } else continue;
  5711. // using decls differ if one says 'typename' and the other doesn't.
  5712. // FIXME: non-dependent using decls?
  5713. if (isTypeName != DTypename) continue;
  5714. // using decls differ if they name different scopes (but note that
  5715. // template instantiation can cause this check to trigger when it
  5716. // didn't before instantiation).
  5717. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  5718. Context.getCanonicalNestedNameSpecifier(DQual))
  5719. continue;
  5720. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  5721. Diag(D->getLocation(), diag::note_using_decl) << 1;
  5722. return true;
  5723. }
  5724. return false;
  5725. }
  5726. /// Checks that the given nested-name qualifier used in a using decl
  5727. /// in the current context is appropriately related to the current
  5728. /// scope. If an error is found, diagnoses it and returns true.
  5729. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  5730. const CXXScopeSpec &SS,
  5731. SourceLocation NameLoc) {
  5732. DeclContext *NamedContext = computeDeclContext(SS);
  5733. if (!CurContext->isRecord()) {
  5734. // C++03 [namespace.udecl]p3:
  5735. // C++0x [namespace.udecl]p8:
  5736. // A using-declaration for a class member shall be a member-declaration.
  5737. // If we weren't able to compute a valid scope, it must be a
  5738. // dependent class scope.
  5739. if (!NamedContext || NamedContext->isRecord()) {
  5740. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  5741. << SS.getRange();
  5742. return true;
  5743. }
  5744. // Otherwise, everything is known to be fine.
  5745. return false;
  5746. }
  5747. // The current scope is a record.
  5748. // If the named context is dependent, we can't decide much.
  5749. if (!NamedContext) {
  5750. // FIXME: in C++0x, we can diagnose if we can prove that the
  5751. // nested-name-specifier does not refer to a base class, which is
  5752. // still possible in some cases.
  5753. // Otherwise we have to conservatively report that things might be
  5754. // okay.
  5755. return false;
  5756. }
  5757. if (!NamedContext->isRecord()) {
  5758. // Ideally this would point at the last name in the specifier,
  5759. // but we don't have that level of source info.
  5760. Diag(SS.getRange().getBegin(),
  5761. diag::err_using_decl_nested_name_specifier_is_not_class)
  5762. << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
  5763. return true;
  5764. }
  5765. if (!NamedContext->isDependentContext() &&
  5766. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  5767. return true;
  5768. if (getLangOptions().CPlusPlus0x) {
  5769. // C++0x [namespace.udecl]p3:
  5770. // In a using-declaration used as a member-declaration, the
  5771. // nested-name-specifier shall name a base class of the class
  5772. // being defined.
  5773. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  5774. cast<CXXRecordDecl>(NamedContext))) {
  5775. if (CurContext == NamedContext) {
  5776. Diag(NameLoc,
  5777. diag::err_using_decl_nested_name_specifier_is_current_class)
  5778. << SS.getRange();
  5779. return true;
  5780. }
  5781. Diag(SS.getRange().getBegin(),
  5782. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  5783. << (NestedNameSpecifier*) SS.getScopeRep()
  5784. << cast<CXXRecordDecl>(CurContext)
  5785. << SS.getRange();
  5786. return true;
  5787. }
  5788. return false;
  5789. }
  5790. // C++03 [namespace.udecl]p4:
  5791. // A using-declaration used as a member-declaration shall refer
  5792. // to a member of a base class of the class being defined [etc.].
  5793. // Salient point: SS doesn't have to name a base class as long as
  5794. // lookup only finds members from base classes. Therefore we can
  5795. // diagnose here only if we can prove that that can't happen,
  5796. // i.e. if the class hierarchies provably don't intersect.
  5797. // TODO: it would be nice if "definitely valid" results were cached
  5798. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  5799. // need to be repeated.
  5800. struct UserData {
  5801. llvm::DenseSet<const CXXRecordDecl*> Bases;
  5802. static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
  5803. UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
  5804. Data->Bases.insert(Base);
  5805. return true;
  5806. }
  5807. bool hasDependentBases(const CXXRecordDecl *Class) {
  5808. return !Class->forallBases(collect, this);
  5809. }
  5810. /// Returns true if the base is dependent or is one of the
  5811. /// accumulated base classes.
  5812. static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
  5813. UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
  5814. return !Data->Bases.count(Base);
  5815. }
  5816. bool mightShareBases(const CXXRecordDecl *Class) {
  5817. return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
  5818. }
  5819. };
  5820. UserData Data;
  5821. // Returns false if we find a dependent base.
  5822. if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
  5823. return false;
  5824. // Returns false if the class has a dependent base or if it or one
  5825. // of its bases is present in the base set of the current context.
  5826. if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
  5827. return false;
  5828. Diag(SS.getRange().getBegin(),
  5829. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  5830. << (NestedNameSpecifier*) SS.getScopeRep()
  5831. << cast<CXXRecordDecl>(CurContext)
  5832. << SS.getRange();
  5833. return true;
  5834. }
  5835. Decl *Sema::ActOnAliasDeclaration(Scope *S,
  5836. AccessSpecifier AS,
  5837. MultiTemplateParamsArg TemplateParamLists,
  5838. SourceLocation UsingLoc,
  5839. UnqualifiedId &Name,
  5840. TypeResult Type) {
  5841. // Skip up to the relevant declaration scope.
  5842. while (S->getFlags() & Scope::TemplateParamScope)
  5843. S = S->getParent();
  5844. assert((S->getFlags() & Scope::DeclScope) &&
  5845. "got alias-declaration outside of declaration scope");
  5846. if (Type.isInvalid())
  5847. return 0;
  5848. bool Invalid = false;
  5849. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  5850. TypeSourceInfo *TInfo = 0;
  5851. GetTypeFromParser(Type.get(), &TInfo);
  5852. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  5853. return 0;
  5854. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  5855. UPPC_DeclarationType)) {
  5856. Invalid = true;
  5857. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  5858. TInfo->getTypeLoc().getBeginLoc());
  5859. }
  5860. LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
  5861. LookupName(Previous, S);
  5862. // Warn about shadowing the name of a template parameter.
  5863. if (Previous.isSingleResult() &&
  5864. Previous.getFoundDecl()->isTemplateParameter()) {
  5865. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  5866. Previous.clear();
  5867. }
  5868. assert(Name.Kind == UnqualifiedId::IK_Identifier &&
  5869. "name in alias declaration must be an identifier");
  5870. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  5871. Name.StartLocation,
  5872. Name.Identifier, TInfo);
  5873. NewTD->setAccess(AS);
  5874. if (Invalid)
  5875. NewTD->setInvalidDecl();
  5876. CheckTypedefForVariablyModifiedType(S, NewTD);
  5877. Invalid |= NewTD->isInvalidDecl();
  5878. bool Redeclaration = false;
  5879. NamedDecl *NewND;
  5880. if (TemplateParamLists.size()) {
  5881. TypeAliasTemplateDecl *OldDecl = 0;
  5882. TemplateParameterList *OldTemplateParams = 0;
  5883. if (TemplateParamLists.size() != 1) {
  5884. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  5885. << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
  5886. TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
  5887. }
  5888. TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
  5889. // Only consider previous declarations in the same scope.
  5890. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  5891. /*ExplicitInstantiationOrSpecialization*/false);
  5892. if (!Previous.empty()) {
  5893. Redeclaration = true;
  5894. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  5895. if (!OldDecl && !Invalid) {
  5896. Diag(UsingLoc, diag::err_redefinition_different_kind)
  5897. << Name.Identifier;
  5898. NamedDecl *OldD = Previous.getRepresentativeDecl();
  5899. if (OldD->getLocation().isValid())
  5900. Diag(OldD->getLocation(), diag::note_previous_definition);
  5901. Invalid = true;
  5902. }
  5903. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  5904. if (TemplateParameterListsAreEqual(TemplateParams,
  5905. OldDecl->getTemplateParameters(),
  5906. /*Complain=*/true,
  5907. TPL_TemplateMatch))
  5908. OldTemplateParams = OldDecl->getTemplateParameters();
  5909. else
  5910. Invalid = true;
  5911. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  5912. if (!Invalid &&
  5913. !Context.hasSameType(OldTD->getUnderlyingType(),
  5914. NewTD->getUnderlyingType())) {
  5915. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  5916. // but we can't reasonably accept it.
  5917. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  5918. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  5919. if (OldTD->getLocation().isValid())
  5920. Diag(OldTD->getLocation(), diag::note_previous_definition);
  5921. Invalid = true;
  5922. }
  5923. }
  5924. }
  5925. // Merge any previous default template arguments into our parameters,
  5926. // and check the parameter list.
  5927. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  5928. TPC_TypeAliasTemplate))
  5929. return 0;
  5930. TypeAliasTemplateDecl *NewDecl =
  5931. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  5932. Name.Identifier, TemplateParams,
  5933. NewTD);
  5934. NewDecl->setAccess(AS);
  5935. if (Invalid)
  5936. NewDecl->setInvalidDecl();
  5937. else if (OldDecl)
  5938. NewDecl->setPreviousDeclaration(OldDecl);
  5939. NewND = NewDecl;
  5940. } else {
  5941. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  5942. NewND = NewTD;
  5943. }
  5944. if (!Redeclaration)
  5945. PushOnScopeChains(NewND, S);
  5946. return NewND;
  5947. }
  5948. Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
  5949. SourceLocation NamespaceLoc,
  5950. SourceLocation AliasLoc,
  5951. IdentifierInfo *Alias,
  5952. CXXScopeSpec &SS,
  5953. SourceLocation IdentLoc,
  5954. IdentifierInfo *Ident) {
  5955. // Lookup the namespace name.
  5956. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  5957. LookupParsedName(R, S, &SS);
  5958. // Check if we have a previous declaration with the same name.
  5959. NamedDecl *PrevDecl
  5960. = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
  5961. ForRedeclaration);
  5962. if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
  5963. PrevDecl = 0;
  5964. if (PrevDecl) {
  5965. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  5966. // We already have an alias with the same name that points to the same
  5967. // namespace, so don't create a new one.
  5968. // FIXME: At some point, we'll want to create the (redundant)
  5969. // declaration to maintain better source information.
  5970. if (!R.isAmbiguous() && !R.empty() &&
  5971. AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
  5972. return 0;
  5973. }
  5974. unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
  5975. diag::err_redefinition_different_kind;
  5976. Diag(AliasLoc, DiagID) << Alias;
  5977. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  5978. return 0;
  5979. }
  5980. if (R.isAmbiguous())
  5981. return 0;
  5982. if (R.empty()) {
  5983. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  5984. Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
  5985. return 0;
  5986. }
  5987. }
  5988. NamespaceAliasDecl *AliasDecl =
  5989. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  5990. Alias, SS.getWithLocInContext(Context),
  5991. IdentLoc, R.getFoundDecl());
  5992. PushOnScopeChains(AliasDecl, S);
  5993. return AliasDecl;
  5994. }
  5995. namespace {
  5996. /// \brief Scoped object used to handle the state changes required in Sema
  5997. /// to implicitly define the body of a C++ member function;
  5998. class ImplicitlyDefinedFunctionScope {
  5999. Sema &S;
  6000. Sema::ContextRAII SavedContext;
  6001. public:
  6002. ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
  6003. : S(S), SavedContext(S, Method)
  6004. {
  6005. S.PushFunctionScope();
  6006. S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
  6007. }
  6008. ~ImplicitlyDefinedFunctionScope() {
  6009. S.PopExpressionEvaluationContext();
  6010. S.PopFunctionScopeInfo();
  6011. }
  6012. };
  6013. }
  6014. Sema::ImplicitExceptionSpecification
  6015. Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
  6016. // C++ [except.spec]p14:
  6017. // An implicitly declared special member function (Clause 12) shall have an
  6018. // exception-specification. [...]
  6019. ImplicitExceptionSpecification ExceptSpec(Context);
  6020. if (ClassDecl->isInvalidDecl())
  6021. return ExceptSpec;
  6022. // Direct base-class constructors.
  6023. for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
  6024. BEnd = ClassDecl->bases_end();
  6025. B != BEnd; ++B) {
  6026. if (B->isVirtual()) // Handled below.
  6027. continue;
  6028. if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
  6029. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  6030. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  6031. // If this is a deleted function, add it anyway. This might be conformant
  6032. // with the standard. This might not. I'm not sure. It might not matter.
  6033. if (Constructor)
  6034. ExceptSpec.CalledDecl(Constructor);
  6035. }
  6036. }
  6037. // Virtual base-class constructors.
  6038. for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
  6039. BEnd = ClassDecl->vbases_end();
  6040. B != BEnd; ++B) {
  6041. if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
  6042. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  6043. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  6044. // If this is a deleted function, add it anyway. This might be conformant
  6045. // with the standard. This might not. I'm not sure. It might not matter.
  6046. if (Constructor)
  6047. ExceptSpec.CalledDecl(Constructor);
  6048. }
  6049. }
  6050. // Field constructors.
  6051. for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
  6052. FEnd = ClassDecl->field_end();
  6053. F != FEnd; ++F) {
  6054. if (F->hasInClassInitializer()) {
  6055. if (Expr *E = F->getInClassInitializer())
  6056. ExceptSpec.CalledExpr(E);
  6057. else if (!F->isInvalidDecl())
  6058. ExceptSpec.SetDelayed();
  6059. } else if (const RecordType *RecordTy
  6060. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  6061. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  6062. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  6063. // If this is a deleted function, add it anyway. This might be conformant
  6064. // with the standard. This might not. I'm not sure. It might not matter.
  6065. // In particular, the problem is that this function never gets called. It
  6066. // might just be ill-formed because this function attempts to refer to
  6067. // a deleted function here.
  6068. if (Constructor)
  6069. ExceptSpec.CalledDecl(Constructor);
  6070. }
  6071. }
  6072. return ExceptSpec;
  6073. }
  6074. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  6075. CXXRecordDecl *ClassDecl) {
  6076. // C++ [class.ctor]p5:
  6077. // A default constructor for a class X is a constructor of class X
  6078. // that can be called without an argument. If there is no
  6079. // user-declared constructor for class X, a default constructor is
  6080. // implicitly declared. An implicitly-declared default constructor
  6081. // is an inline public member of its class.
  6082. assert(!ClassDecl->hasUserDeclaredConstructor() &&
  6083. "Should not build implicit default constructor!");
  6084. ImplicitExceptionSpecification Spec =
  6085. ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
  6086. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  6087. // Create the actual constructor declaration.
  6088. CanQualType ClassType
  6089. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  6090. SourceLocation ClassLoc = ClassDecl->getLocation();
  6091. DeclarationName Name
  6092. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  6093. DeclarationNameInfo NameInfo(Name, ClassLoc);
  6094. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  6095. Context, ClassDecl, ClassLoc, NameInfo,
  6096. Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
  6097. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  6098. /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
  6099. getLangOptions().CPlusPlus0x);
  6100. DefaultCon->setAccess(AS_public);
  6101. DefaultCon->setDefaulted();
  6102. DefaultCon->setImplicit();
  6103. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  6104. // Note that we have declared this constructor.
  6105. ++ASTContext::NumImplicitDefaultConstructorsDeclared;
  6106. if (Scope *S = getScopeForContext(ClassDecl))
  6107. PushOnScopeChains(DefaultCon, S, false);
  6108. ClassDecl->addDecl(DefaultCon);
  6109. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  6110. DefaultCon->setDeletedAsWritten();
  6111. return DefaultCon;
  6112. }
  6113. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  6114. CXXConstructorDecl *Constructor) {
  6115. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  6116. !Constructor->doesThisDeclarationHaveABody() &&
  6117. !Constructor->isDeleted()) &&
  6118. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  6119. CXXRecordDecl *ClassDecl = Constructor->getParent();
  6120. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  6121. ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
  6122. DiagnosticErrorTrap Trap(Diags);
  6123. if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
  6124. Trap.hasErrorOccurred()) {
  6125. Diag(CurrentLocation, diag::note_member_synthesized_at)
  6126. << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
  6127. Constructor->setInvalidDecl();
  6128. return;
  6129. }
  6130. SourceLocation Loc = Constructor->getLocation();
  6131. Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
  6132. Constructor->setUsed();
  6133. MarkVTableUsed(CurrentLocation, ClassDecl);
  6134. if (ASTMutationListener *L = getASTMutationListener()) {
  6135. L->CompletedImplicitDefinition(Constructor);
  6136. }
  6137. }
  6138. /// Get any existing defaulted default constructor for the given class. Do not
  6139. /// implicitly define one if it does not exist.
  6140. static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
  6141. CXXRecordDecl *D) {
  6142. ASTContext &Context = Self.Context;
  6143. QualType ClassType = Context.getTypeDeclType(D);
  6144. DeclarationName ConstructorName
  6145. = Context.DeclarationNames.getCXXConstructorName(
  6146. Context.getCanonicalType(ClassType.getUnqualifiedType()));
  6147. DeclContext::lookup_const_iterator Con, ConEnd;
  6148. for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
  6149. Con != ConEnd; ++Con) {
  6150. // A function template cannot be defaulted.
  6151. if (isa<FunctionTemplateDecl>(*Con))
  6152. continue;
  6153. CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
  6154. if (Constructor->isDefaultConstructor())
  6155. return Constructor->isDefaulted() ? Constructor : 0;
  6156. }
  6157. return 0;
  6158. }
  6159. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  6160. if (!D) return;
  6161. AdjustDeclIfTemplate(D);
  6162. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
  6163. CXXConstructorDecl *CtorDecl
  6164. = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
  6165. if (!CtorDecl) return;
  6166. // Compute the exception specification for the default constructor.
  6167. const FunctionProtoType *CtorTy =
  6168. CtorDecl->getType()->castAs<FunctionProtoType>();
  6169. if (CtorTy->getExceptionSpecType() == EST_Delayed) {
  6170. ImplicitExceptionSpecification Spec =
  6171. ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
  6172. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  6173. assert(EPI.ExceptionSpecType != EST_Delayed);
  6174. CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
  6175. }
  6176. // If the default constructor is explicitly defaulted, checking the exception
  6177. // specification is deferred until now.
  6178. if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
  6179. !ClassDecl->isDependentType())
  6180. CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
  6181. }
  6182. void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
  6183. // We start with an initial pass over the base classes to collect those that
  6184. // inherit constructors from. If there are none, we can forgo all further
  6185. // processing.
  6186. typedef SmallVector<const RecordType *, 4> BasesVector;
  6187. BasesVector BasesToInheritFrom;
  6188. for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
  6189. BaseE = ClassDecl->bases_end();
  6190. BaseIt != BaseE; ++BaseIt) {
  6191. if (BaseIt->getInheritConstructors()) {
  6192. QualType Base = BaseIt->getType();
  6193. if (Base->isDependentType()) {
  6194. // If we inherit constructors from anything that is dependent, just
  6195. // abort processing altogether. We'll get another chance for the
  6196. // instantiations.
  6197. return;
  6198. }
  6199. BasesToInheritFrom.push_back(Base->castAs<RecordType>());
  6200. }
  6201. }
  6202. if (BasesToInheritFrom.empty())
  6203. return;
  6204. // Now collect the constructors that we already have in the current class.
  6205. // Those take precedence over inherited constructors.
  6206. // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
  6207. // unless there is a user-declared constructor with the same signature in
  6208. // the class where the using-declaration appears.
  6209. llvm::SmallSet<const Type *, 8> ExistingConstructors;
  6210. for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
  6211. CtorE = ClassDecl->ctor_end();
  6212. CtorIt != CtorE; ++CtorIt) {
  6213. ExistingConstructors.insert(
  6214. Context.getCanonicalType(CtorIt->getType()).getTypePtr());
  6215. }
  6216. Scope *S = getScopeForContext(ClassDecl);
  6217. DeclarationName CreatedCtorName =
  6218. Context.DeclarationNames.getCXXConstructorName(
  6219. ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
  6220. // Now comes the true work.
  6221. // First, we keep a map from constructor types to the base that introduced
  6222. // them. Needed for finding conflicting constructors. We also keep the
  6223. // actually inserted declarations in there, for pretty diagnostics.
  6224. typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
  6225. typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
  6226. ConstructorToSourceMap InheritedConstructors;
  6227. for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
  6228. BaseE = BasesToInheritFrom.end();
  6229. BaseIt != BaseE; ++BaseIt) {
  6230. const RecordType *Base = *BaseIt;
  6231. CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
  6232. CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
  6233. for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
  6234. CtorE = BaseDecl->ctor_end();
  6235. CtorIt != CtorE; ++CtorIt) {
  6236. // Find the using declaration for inheriting this base's constructors.
  6237. DeclarationName Name =
  6238. Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
  6239. UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
  6240. LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
  6241. SourceLocation UsingLoc = UD ? UD->getLocation() :
  6242. ClassDecl->getLocation();
  6243. // C++0x [class.inhctor]p1: The candidate set of inherited constructors
  6244. // from the class X named in the using-declaration consists of actual
  6245. // constructors and notional constructors that result from the
  6246. // transformation of defaulted parameters as follows:
  6247. // - all non-template default constructors of X, and
  6248. // - for each non-template constructor of X that has at least one
  6249. // parameter with a default argument, the set of constructors that
  6250. // results from omitting any ellipsis parameter specification and
  6251. // successively omitting parameters with a default argument from the
  6252. // end of the parameter-type-list.
  6253. CXXConstructorDecl *BaseCtor = *CtorIt;
  6254. bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
  6255. const FunctionProtoType *BaseCtorType =
  6256. BaseCtor->getType()->getAs<FunctionProtoType>();
  6257. for (unsigned params = BaseCtor->getMinRequiredArguments(),
  6258. maxParams = BaseCtor->getNumParams();
  6259. params <= maxParams; ++params) {
  6260. // Skip default constructors. They're never inherited.
  6261. if (params == 0)
  6262. continue;
  6263. // Skip copy and move constructors for the same reason.
  6264. if (CanBeCopyOrMove && params == 1)
  6265. continue;
  6266. // Build up a function type for this particular constructor.
  6267. // FIXME: The working paper does not consider that the exception spec
  6268. // for the inheriting constructor might be larger than that of the
  6269. // source. This code doesn't yet, either. When it does, this code will
  6270. // need to be delayed until after exception specifications and in-class
  6271. // member initializers are attached.
  6272. const Type *NewCtorType;
  6273. if (params == maxParams)
  6274. NewCtorType = BaseCtorType;
  6275. else {
  6276. SmallVector<QualType, 16> Args;
  6277. for (unsigned i = 0; i < params; ++i) {
  6278. Args.push_back(BaseCtorType->getArgType(i));
  6279. }
  6280. FunctionProtoType::ExtProtoInfo ExtInfo =
  6281. BaseCtorType->getExtProtoInfo();
  6282. ExtInfo.Variadic = false;
  6283. NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
  6284. Args.data(), params, ExtInfo)
  6285. .getTypePtr();
  6286. }
  6287. const Type *CanonicalNewCtorType =
  6288. Context.getCanonicalType(NewCtorType);
  6289. // Now that we have the type, first check if the class already has a
  6290. // constructor with this signature.
  6291. if (ExistingConstructors.count(CanonicalNewCtorType))
  6292. continue;
  6293. // Then we check if we have already declared an inherited constructor
  6294. // with this signature.
  6295. std::pair<ConstructorToSourceMap::iterator, bool> result =
  6296. InheritedConstructors.insert(std::make_pair(
  6297. CanonicalNewCtorType,
  6298. std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
  6299. if (!result.second) {
  6300. // Already in the map. If it came from a different class, that's an
  6301. // error. Not if it's from the same.
  6302. CanQualType PreviousBase = result.first->second.first;
  6303. if (CanonicalBase != PreviousBase) {
  6304. const CXXConstructorDecl *PrevCtor = result.first->second.second;
  6305. const CXXConstructorDecl *PrevBaseCtor =
  6306. PrevCtor->getInheritedConstructor();
  6307. assert(PrevBaseCtor && "Conflicting constructor was not inherited");
  6308. Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
  6309. Diag(BaseCtor->getLocation(),
  6310. diag::note_using_decl_constructor_conflict_current_ctor);
  6311. Diag(PrevBaseCtor->getLocation(),
  6312. diag::note_using_decl_constructor_conflict_previous_ctor);
  6313. Diag(PrevCtor->getLocation(),
  6314. diag::note_using_decl_constructor_conflict_previous_using);
  6315. }
  6316. continue;
  6317. }
  6318. // OK, we're there, now add the constructor.
  6319. // C++0x [class.inhctor]p8: [...] that would be performed by a
  6320. // user-written inline constructor [...]
  6321. DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
  6322. CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
  6323. Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
  6324. /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
  6325. /*ImplicitlyDeclared=*/true,
  6326. // FIXME: Due to a defect in the standard, we treat inherited
  6327. // constructors as constexpr even if that makes them ill-formed.
  6328. /*Constexpr=*/BaseCtor->isConstexpr());
  6329. NewCtor->setAccess(BaseCtor->getAccess());
  6330. // Build up the parameter decls and add them.
  6331. SmallVector<ParmVarDecl *, 16> ParamDecls;
  6332. for (unsigned i = 0; i < params; ++i) {
  6333. ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
  6334. UsingLoc, UsingLoc,
  6335. /*IdentifierInfo=*/0,
  6336. BaseCtorType->getArgType(i),
  6337. /*TInfo=*/0, SC_None,
  6338. SC_None, /*DefaultArg=*/0));
  6339. }
  6340. NewCtor->setParams(ParamDecls);
  6341. NewCtor->setInheritedConstructor(BaseCtor);
  6342. PushOnScopeChains(NewCtor, S, false);
  6343. ClassDecl->addDecl(NewCtor);
  6344. result.first->second.second = NewCtor;
  6345. }
  6346. }
  6347. }
  6348. }
  6349. Sema::ImplicitExceptionSpecification
  6350. Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
  6351. // C++ [except.spec]p14:
  6352. // An implicitly declared special member function (Clause 12) shall have
  6353. // an exception-specification.
  6354. ImplicitExceptionSpecification ExceptSpec(Context);
  6355. if (ClassDecl->isInvalidDecl())
  6356. return ExceptSpec;
  6357. // Direct base-class destructors.
  6358. for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
  6359. BEnd = ClassDecl->bases_end();
  6360. B != BEnd; ++B) {
  6361. if (B->isVirtual()) // Handled below.
  6362. continue;
  6363. if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
  6364. ExceptSpec.CalledDecl(
  6365. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  6366. }
  6367. // Virtual base-class destructors.
  6368. for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
  6369. BEnd = ClassDecl->vbases_end();
  6370. B != BEnd; ++B) {
  6371. if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
  6372. ExceptSpec.CalledDecl(
  6373. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  6374. }
  6375. // Field destructors.
  6376. for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
  6377. FEnd = ClassDecl->field_end();
  6378. F != FEnd; ++F) {
  6379. if (const RecordType *RecordTy
  6380. = Context.getBaseElementType(F->getType())->getAs<RecordType>())
  6381. ExceptSpec.CalledDecl(
  6382. LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
  6383. }
  6384. return ExceptSpec;
  6385. }
  6386. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  6387. // C++ [class.dtor]p2:
  6388. // If a class has no user-declared destructor, a destructor is
  6389. // declared implicitly. An implicitly-declared destructor is an
  6390. // inline public member of its class.
  6391. ImplicitExceptionSpecification Spec =
  6392. ComputeDefaultedDtorExceptionSpec(ClassDecl);
  6393. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  6394. // Create the actual destructor declaration.
  6395. QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
  6396. CanQualType ClassType
  6397. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  6398. SourceLocation ClassLoc = ClassDecl->getLocation();
  6399. DeclarationName Name
  6400. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  6401. DeclarationNameInfo NameInfo(Name, ClassLoc);
  6402. CXXDestructorDecl *Destructor
  6403. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
  6404. /*isInline=*/true,
  6405. /*isImplicitlyDeclared=*/true);
  6406. Destructor->setAccess(AS_public);
  6407. Destructor->setDefaulted();
  6408. Destructor->setImplicit();
  6409. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  6410. // Note that we have declared this destructor.
  6411. ++ASTContext::NumImplicitDestructorsDeclared;
  6412. // Introduce this destructor into its scope.
  6413. if (Scope *S = getScopeForContext(ClassDecl))
  6414. PushOnScopeChains(Destructor, S, false);
  6415. ClassDecl->addDecl(Destructor);
  6416. // This could be uniqued if it ever proves significant.
  6417. Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
  6418. if (ShouldDeleteDestructor(Destructor))
  6419. Destructor->setDeletedAsWritten();
  6420. AddOverriddenMethods(ClassDecl, Destructor);
  6421. return Destructor;
  6422. }
  6423. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  6424. CXXDestructorDecl *Destructor) {
  6425. assert((Destructor->isDefaulted() &&
  6426. !Destructor->doesThisDeclarationHaveABody()) &&
  6427. "DefineImplicitDestructor - call it for implicit default dtor");
  6428. CXXRecordDecl *ClassDecl = Destructor->getParent();
  6429. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  6430. if (Destructor->isInvalidDecl())
  6431. return;
  6432. ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
  6433. DiagnosticErrorTrap Trap(Diags);
  6434. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  6435. Destructor->getParent());
  6436. if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
  6437. Diag(CurrentLocation, diag::note_member_synthesized_at)
  6438. << CXXDestructor << Context.getTagDeclType(ClassDecl);
  6439. Destructor->setInvalidDecl();
  6440. return;
  6441. }
  6442. SourceLocation Loc = Destructor->getLocation();
  6443. Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
  6444. Destructor->setImplicitlyDefined(true);
  6445. Destructor->setUsed();
  6446. MarkVTableUsed(CurrentLocation, ClassDecl);
  6447. if (ASTMutationListener *L = getASTMutationListener()) {
  6448. L->CompletedImplicitDefinition(Destructor);
  6449. }
  6450. }
  6451. void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
  6452. CXXDestructorDecl *destructor) {
  6453. // C++11 [class.dtor]p3:
  6454. // A declaration of a destructor that does not have an exception-
  6455. // specification is implicitly considered to have the same exception-
  6456. // specification as an implicit declaration.
  6457. const FunctionProtoType *dtorType = destructor->getType()->
  6458. getAs<FunctionProtoType>();
  6459. if (dtorType->hasExceptionSpec())
  6460. return;
  6461. ImplicitExceptionSpecification exceptSpec =
  6462. ComputeDefaultedDtorExceptionSpec(classDecl);
  6463. // Replace the destructor's type, building off the existing one. Fortunately,
  6464. // the only thing of interest in the destructor type is its extended info.
  6465. // The return and arguments are fixed.
  6466. FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
  6467. epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
  6468. epi.NumExceptions = exceptSpec.size();
  6469. epi.Exceptions = exceptSpec.data();
  6470. QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
  6471. destructor->setType(ty);
  6472. // FIXME: If the destructor has a body that could throw, and the newly created
  6473. // spec doesn't allow exceptions, we should emit a warning, because this
  6474. // change in behavior can break conforming C++03 programs at runtime.
  6475. // However, we don't have a body yet, so it needs to be done somewhere else.
  6476. }
  6477. /// \brief Builds a statement that copies/moves the given entity from \p From to
  6478. /// \c To.
  6479. ///
  6480. /// This routine is used to copy/move the members of a class with an
  6481. /// implicitly-declared copy/move assignment operator. When the entities being
  6482. /// copied are arrays, this routine builds for loops to copy them.
  6483. ///
  6484. /// \param S The Sema object used for type-checking.
  6485. ///
  6486. /// \param Loc The location where the implicit copy/move is being generated.
  6487. ///
  6488. /// \param T The type of the expressions being copied/moved. Both expressions
  6489. /// must have this type.
  6490. ///
  6491. /// \param To The expression we are copying/moving to.
  6492. ///
  6493. /// \param From The expression we are copying/moving from.
  6494. ///
  6495. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  6496. /// Otherwise, it's a non-static member subobject.
  6497. ///
  6498. /// \param Copying Whether we're copying or moving.
  6499. ///
  6500. /// \param Depth Internal parameter recording the depth of the recursion.
  6501. ///
  6502. /// \returns A statement or a loop that copies the expressions.
  6503. static StmtResult
  6504. BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  6505. Expr *To, Expr *From,
  6506. bool CopyingBaseSubobject, bool Copying,
  6507. unsigned Depth = 0) {
  6508. // C++0x [class.copy]p28:
  6509. // Each subobject is assigned in the manner appropriate to its type:
  6510. //
  6511. // - if the subobject is of class type, as if by a call to operator= with
  6512. // the subobject as the object expression and the corresponding
  6513. // subobject of x as a single function argument (as if by explicit
  6514. // qualification; that is, ignoring any possible virtual overriding
  6515. // functions in more derived classes);
  6516. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  6517. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  6518. // Look for operator=.
  6519. DeclarationName Name
  6520. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  6521. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  6522. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  6523. // Filter out any result that isn't a copy/move-assignment operator.
  6524. LookupResult::Filter F = OpLookup.makeFilter();
  6525. while (F.hasNext()) {
  6526. NamedDecl *D = F.next();
  6527. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  6528. if (Copying ? Method->isCopyAssignmentOperator() :
  6529. Method->isMoveAssignmentOperator())
  6530. continue;
  6531. F.erase();
  6532. }
  6533. F.done();
  6534. // Suppress the protected check (C++ [class.protected]) for each of the
  6535. // assignment operators we found. This strange dance is required when
  6536. // we're assigning via a base classes's copy-assignment operator. To
  6537. // ensure that we're getting the right base class subobject (without
  6538. // ambiguities), we need to cast "this" to that subobject type; to
  6539. // ensure that we don't go through the virtual call mechanism, we need
  6540. // to qualify the operator= name with the base class (see below). However,
  6541. // this means that if the base class has a protected copy assignment
  6542. // operator, the protected member access check will fail. So, we
  6543. // rewrite "protected" access to "public" access in this case, since we
  6544. // know by construction that we're calling from a derived class.
  6545. if (CopyingBaseSubobject) {
  6546. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  6547. L != LEnd; ++L) {
  6548. if (L.getAccess() == AS_protected)
  6549. L.setAccess(AS_public);
  6550. }
  6551. }
  6552. // Create the nested-name-specifier that will be used to qualify the
  6553. // reference to operator=; this is required to suppress the virtual
  6554. // call mechanism.
  6555. CXXScopeSpec SS;
  6556. SS.MakeTrivial(S.Context,
  6557. NestedNameSpecifier::Create(S.Context, 0, false,
  6558. T.getTypePtr()),
  6559. Loc);
  6560. // Create the reference to operator=.
  6561. ExprResult OpEqualRef
  6562. = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
  6563. /*TemplateKWLoc=*/SourceLocation(),
  6564. /*FirstQualifierInScope=*/0,
  6565. OpLookup,
  6566. /*TemplateArgs=*/0,
  6567. /*SuppressQualifierCheck=*/true);
  6568. if (OpEqualRef.isInvalid())
  6569. return StmtError();
  6570. // Build the call to the assignment operator.
  6571. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
  6572. OpEqualRef.takeAs<Expr>(),
  6573. Loc, &From, 1, Loc);
  6574. if (Call.isInvalid())
  6575. return StmtError();
  6576. return S.Owned(Call.takeAs<Stmt>());
  6577. }
  6578. // - if the subobject is of scalar type, the built-in assignment
  6579. // operator is used.
  6580. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  6581. if (!ArrayTy) {
  6582. ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
  6583. if (Assignment.isInvalid())
  6584. return StmtError();
  6585. return S.Owned(Assignment.takeAs<Stmt>());
  6586. }
  6587. // - if the subobject is an array, each element is assigned, in the
  6588. // manner appropriate to the element type;
  6589. // Construct a loop over the array bounds, e.g.,
  6590. //
  6591. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  6592. //
  6593. // that will copy each of the array elements.
  6594. QualType SizeType = S.Context.getSizeType();
  6595. // Create the iteration variable.
  6596. IdentifierInfo *IterationVarName = 0;
  6597. {
  6598. SmallString<8> Str;
  6599. llvm::raw_svector_ostream OS(Str);
  6600. OS << "__i" << Depth;
  6601. IterationVarName = &S.Context.Idents.get(OS.str());
  6602. }
  6603. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  6604. IterationVarName, SizeType,
  6605. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  6606. SC_None, SC_None);
  6607. // Initialize the iteration variable to zero.
  6608. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  6609. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  6610. // Create a reference to the iteration variable; we'll use this several
  6611. // times throughout.
  6612. Expr *IterationVarRef
  6613. = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
  6614. assert(IterationVarRef && "Reference to invented variable cannot fail!");
  6615. Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
  6616. assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
  6617. // Create the DeclStmt that holds the iteration variable.
  6618. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  6619. // Create the comparison against the array bound.
  6620. llvm::APInt Upper
  6621. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  6622. Expr *Comparison
  6623. = new (S.Context) BinaryOperator(IterationVarRefRVal,
  6624. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  6625. BO_NE, S.Context.BoolTy,
  6626. VK_RValue, OK_Ordinary, Loc);
  6627. // Create the pre-increment of the iteration variable.
  6628. Expr *Increment
  6629. = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
  6630. VK_LValue, OK_Ordinary, Loc);
  6631. // Subscript the "from" and "to" expressions with the iteration variable.
  6632. From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
  6633. IterationVarRefRVal,
  6634. Loc));
  6635. To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
  6636. IterationVarRefRVal,
  6637. Loc));
  6638. if (!Copying) // Cast to rvalue
  6639. From = CastForMoving(S, From);
  6640. // Build the copy/move for an individual element of the array.
  6641. StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
  6642. To, From, CopyingBaseSubobject,
  6643. Copying, Depth + 1);
  6644. if (Copy.isInvalid())
  6645. return StmtError();
  6646. // Construct the loop that copies all elements of this array.
  6647. return S.ActOnForStmt(Loc, Loc, InitStmt,
  6648. S.MakeFullExpr(Comparison),
  6649. 0, S.MakeFullExpr(Increment),
  6650. Loc, Copy.take());
  6651. }
  6652. std::pair<Sema::ImplicitExceptionSpecification, bool>
  6653. Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
  6654. CXXRecordDecl *ClassDecl) {
  6655. if (ClassDecl->isInvalidDecl())
  6656. return std::make_pair(ImplicitExceptionSpecification(Context), false);
  6657. // C++ [class.copy]p10:
  6658. // If the class definition does not explicitly declare a copy
  6659. // assignment operator, one is declared implicitly.
  6660. // The implicitly-defined copy assignment operator for a class X
  6661. // will have the form
  6662. //
  6663. // X& X::operator=(const X&)
  6664. //
  6665. // if
  6666. bool HasConstCopyAssignment = true;
  6667. // -- each direct base class B of X has a copy assignment operator
  6668. // whose parameter is of type const B&, const volatile B& or B,
  6669. // and
  6670. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  6671. BaseEnd = ClassDecl->bases_end();
  6672. HasConstCopyAssignment && Base != BaseEnd; ++Base) {
  6673. // We'll handle this below
  6674. if (LangOpts.CPlusPlus0x && Base->isVirtual())
  6675. continue;
  6676. assert(!Base->getType()->isDependentType() &&
  6677. "Cannot generate implicit members for class with dependent bases.");
  6678. CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
  6679. LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
  6680. &HasConstCopyAssignment);
  6681. }
  6682. // In C++11, the above citation has "or virtual" added
  6683. if (LangOpts.CPlusPlus0x) {
  6684. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
  6685. BaseEnd = ClassDecl->vbases_end();
  6686. HasConstCopyAssignment && Base != BaseEnd; ++Base) {
  6687. assert(!Base->getType()->isDependentType() &&
  6688. "Cannot generate implicit members for class with dependent bases.");
  6689. CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
  6690. LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
  6691. &HasConstCopyAssignment);
  6692. }
  6693. }
  6694. // -- for all the nonstatic data members of X that are of a class
  6695. // type M (or array thereof), each such class type has a copy
  6696. // assignment operator whose parameter is of type const M&,
  6697. // const volatile M& or M.
  6698. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  6699. FieldEnd = ClassDecl->field_end();
  6700. HasConstCopyAssignment && Field != FieldEnd;
  6701. ++Field) {
  6702. QualType FieldType = Context.getBaseElementType((*Field)->getType());
  6703. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  6704. LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
  6705. &HasConstCopyAssignment);
  6706. }
  6707. }
  6708. // Otherwise, the implicitly declared copy assignment operator will
  6709. // have the form
  6710. //
  6711. // X& X::operator=(X&)
  6712. // C++ [except.spec]p14:
  6713. // An implicitly declared special member function (Clause 12) shall have an
  6714. // exception-specification. [...]
  6715. // It is unspecified whether or not an implicit copy assignment operator
  6716. // attempts to deduplicate calls to assignment operators of virtual bases are
  6717. // made. As such, this exception specification is effectively unspecified.
  6718. // Based on a similar decision made for constness in C++0x, we're erring on
  6719. // the side of assuming such calls to be made regardless of whether they
  6720. // actually happen.
  6721. ImplicitExceptionSpecification ExceptSpec(Context);
  6722. unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
  6723. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  6724. BaseEnd = ClassDecl->bases_end();
  6725. Base != BaseEnd; ++Base) {
  6726. if (Base->isVirtual())
  6727. continue;
  6728. CXXRecordDecl *BaseClassDecl
  6729. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  6730. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  6731. ArgQuals, false, 0))
  6732. ExceptSpec.CalledDecl(CopyAssign);
  6733. }
  6734. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
  6735. BaseEnd = ClassDecl->vbases_end();
  6736. Base != BaseEnd; ++Base) {
  6737. CXXRecordDecl *BaseClassDecl
  6738. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  6739. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  6740. ArgQuals, false, 0))
  6741. ExceptSpec.CalledDecl(CopyAssign);
  6742. }
  6743. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  6744. FieldEnd = ClassDecl->field_end();
  6745. Field != FieldEnd;
  6746. ++Field) {
  6747. QualType FieldType = Context.getBaseElementType((*Field)->getType());
  6748. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  6749. if (CXXMethodDecl *CopyAssign =
  6750. LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
  6751. ExceptSpec.CalledDecl(CopyAssign);
  6752. }
  6753. }
  6754. return std::make_pair(ExceptSpec, HasConstCopyAssignment);
  6755. }
  6756. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  6757. // Note: The following rules are largely analoguous to the copy
  6758. // constructor rules. Note that virtual bases are not taken into account
  6759. // for determining the argument type of the operator. Note also that
  6760. // operators taking an object instead of a reference are allowed.
  6761. ImplicitExceptionSpecification Spec(Context);
  6762. bool Const;
  6763. llvm::tie(Spec, Const) =
  6764. ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
  6765. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  6766. QualType RetType = Context.getLValueReferenceType(ArgType);
  6767. if (Const)
  6768. ArgType = ArgType.withConst();
  6769. ArgType = Context.getLValueReferenceType(ArgType);
  6770. // An implicitly-declared copy assignment operator is an inline public
  6771. // member of its class.
  6772. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  6773. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  6774. SourceLocation ClassLoc = ClassDecl->getLocation();
  6775. DeclarationNameInfo NameInfo(Name, ClassLoc);
  6776. CXXMethodDecl *CopyAssignment
  6777. = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  6778. Context.getFunctionType(RetType, &ArgType, 1, EPI),
  6779. /*TInfo=*/0, /*isStatic=*/false,
  6780. /*StorageClassAsWritten=*/SC_None,
  6781. /*isInline=*/true, /*isConstexpr=*/false,
  6782. SourceLocation());
  6783. CopyAssignment->setAccess(AS_public);
  6784. CopyAssignment->setDefaulted();
  6785. CopyAssignment->setImplicit();
  6786. CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
  6787. // Add the parameter to the operator.
  6788. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  6789. ClassLoc, ClassLoc, /*Id=*/0,
  6790. ArgType, /*TInfo=*/0,
  6791. SC_None,
  6792. SC_None, 0);
  6793. CopyAssignment->setParams(FromParam);
  6794. // Note that we have added this copy-assignment operator.
  6795. ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  6796. if (Scope *S = getScopeForContext(ClassDecl))
  6797. PushOnScopeChains(CopyAssignment, S, false);
  6798. ClassDecl->addDecl(CopyAssignment);
  6799. // C++0x [class.copy]p19:
  6800. // .... If the class definition does not explicitly declare a copy
  6801. // assignment operator, there is no user-declared move constructor, and
  6802. // there is no user-declared move assignment operator, a copy assignment
  6803. // operator is implicitly declared as defaulted.
  6804. if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
  6805. !getLangOptions().MicrosoftMode) ||
  6806. ClassDecl->hasUserDeclaredMoveAssignment() ||
  6807. ShouldDeleteCopyAssignmentOperator(CopyAssignment))
  6808. CopyAssignment->setDeletedAsWritten();
  6809. AddOverriddenMethods(ClassDecl, CopyAssignment);
  6810. return CopyAssignment;
  6811. }
  6812. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  6813. CXXMethodDecl *CopyAssignOperator) {
  6814. assert((CopyAssignOperator->isDefaulted() &&
  6815. CopyAssignOperator->isOverloadedOperator() &&
  6816. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  6817. !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
  6818. "DefineImplicitCopyAssignment called for wrong function");
  6819. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  6820. if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
  6821. CopyAssignOperator->setInvalidDecl();
  6822. return;
  6823. }
  6824. CopyAssignOperator->setUsed();
  6825. ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
  6826. DiagnosticErrorTrap Trap(Diags);
  6827. // C++0x [class.copy]p30:
  6828. // The implicitly-defined or explicitly-defaulted copy assignment operator
  6829. // for a non-union class X performs memberwise copy assignment of its
  6830. // subobjects. The direct base classes of X are assigned first, in the
  6831. // order of their declaration in the base-specifier-list, and then the
  6832. // immediate non-static data members of X are assigned, in the order in
  6833. // which they were declared in the class definition.
  6834. // The statements that form the synthesized function body.
  6835. ASTOwningVector<Stmt*> Statements(*this);
  6836. // The parameter for the "other" object, which we are copying from.
  6837. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  6838. Qualifiers OtherQuals = Other->getType().getQualifiers();
  6839. QualType OtherRefType = Other->getType();
  6840. if (const LValueReferenceType *OtherRef
  6841. = OtherRefType->getAs<LValueReferenceType>()) {
  6842. OtherRefType = OtherRef->getPointeeType();
  6843. OtherQuals = OtherRefType.getQualifiers();
  6844. }
  6845. // Our location for everything implicitly-generated.
  6846. SourceLocation Loc = CopyAssignOperator->getLocation();
  6847. // Construct a reference to the "other" object. We'll be using this
  6848. // throughout the generated ASTs.
  6849. Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
  6850. assert(OtherRef && "Reference to parameter cannot fail!");
  6851. // Construct the "this" pointer. We'll be using this throughout the generated
  6852. // ASTs.
  6853. Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
  6854. assert(This && "Reference to this cannot fail!");
  6855. // Assign base classes.
  6856. bool Invalid = false;
  6857. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  6858. E = ClassDecl->bases_end(); Base != E; ++Base) {
  6859. // Form the assignment:
  6860. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  6861. QualType BaseType = Base->getType().getUnqualifiedType();
  6862. if (!BaseType->isRecordType()) {
  6863. Invalid = true;
  6864. continue;
  6865. }
  6866. CXXCastPath BasePath;
  6867. BasePath.push_back(Base);
  6868. // Construct the "from" expression, which is an implicit cast to the
  6869. // appropriately-qualified base type.
  6870. Expr *From = OtherRef;
  6871. From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
  6872. CK_UncheckedDerivedToBase,
  6873. VK_LValue, &BasePath).take();
  6874. // Dereference "this".
  6875. ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  6876. // Implicitly cast "this" to the appropriately-qualified base type.
  6877. To = ImpCastExprToType(To.take(),
  6878. Context.getCVRQualifiedType(BaseType,
  6879. CopyAssignOperator->getTypeQualifiers()),
  6880. CK_UncheckedDerivedToBase,
  6881. VK_LValue, &BasePath);
  6882. // Build the copy.
  6883. StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
  6884. To.get(), From,
  6885. /*CopyingBaseSubobject=*/true,
  6886. /*Copying=*/true);
  6887. if (Copy.isInvalid()) {
  6888. Diag(CurrentLocation, diag::note_member_synthesized_at)
  6889. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  6890. CopyAssignOperator->setInvalidDecl();
  6891. return;
  6892. }
  6893. // Success! Record the copy.
  6894. Statements.push_back(Copy.takeAs<Expr>());
  6895. }
  6896. // \brief Reference to the __builtin_memcpy function.
  6897. Expr *BuiltinMemCpyRef = 0;
  6898. // \brief Reference to the __builtin_objc_memmove_collectable function.
  6899. Expr *CollectableMemCpyRef = 0;
  6900. // Assign non-static members.
  6901. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  6902. FieldEnd = ClassDecl->field_end();
  6903. Field != FieldEnd; ++Field) {
  6904. if (Field->isUnnamedBitfield())
  6905. continue;
  6906. // Check for members of reference type; we can't copy those.
  6907. if (Field->getType()->isReferenceType()) {
  6908. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  6909. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  6910. Diag(Field->getLocation(), diag::note_declared_at);
  6911. Diag(CurrentLocation, diag::note_member_synthesized_at)
  6912. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  6913. Invalid = true;
  6914. continue;
  6915. }
  6916. // Check for members of const-qualified, non-class type.
  6917. QualType BaseType = Context.getBaseElementType(Field->getType());
  6918. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  6919. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  6920. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  6921. Diag(Field->getLocation(), diag::note_declared_at);
  6922. Diag(CurrentLocation, diag::note_member_synthesized_at)
  6923. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  6924. Invalid = true;
  6925. continue;
  6926. }
  6927. // Suppress assigning zero-width bitfields.
  6928. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  6929. continue;
  6930. QualType FieldType = Field->getType().getNonReferenceType();
  6931. if (FieldType->isIncompleteArrayType()) {
  6932. assert(ClassDecl->hasFlexibleArrayMember() &&
  6933. "Incomplete array type is not valid");
  6934. continue;
  6935. }
  6936. // Build references to the field in the object we're copying from and to.
  6937. CXXScopeSpec SS; // Intentionally empty
  6938. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  6939. LookupMemberName);
  6940. MemberLookup.addDecl(*Field);
  6941. MemberLookup.resolveKind();
  6942. ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
  6943. Loc, /*IsArrow=*/false,
  6944. SS, SourceLocation(), 0,
  6945. MemberLookup, 0);
  6946. ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
  6947. Loc, /*IsArrow=*/true,
  6948. SS, SourceLocation(), 0,
  6949. MemberLookup, 0);
  6950. assert(!From.isInvalid() && "Implicit field reference cannot fail");
  6951. assert(!To.isInvalid() && "Implicit field reference cannot fail");
  6952. // If the field should be copied with __builtin_memcpy rather than via
  6953. // explicit assignments, do so. This optimization only applies for arrays
  6954. // of scalars and arrays of class type with trivial copy-assignment
  6955. // operators.
  6956. if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
  6957. && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
  6958. // Compute the size of the memory buffer to be copied.
  6959. QualType SizeType = Context.getSizeType();
  6960. llvm::APInt Size(Context.getTypeSize(SizeType),
  6961. Context.getTypeSizeInChars(BaseType).getQuantity());
  6962. for (const ConstantArrayType *Array
  6963. = Context.getAsConstantArrayType(FieldType);
  6964. Array;
  6965. Array = Context.getAsConstantArrayType(Array->getElementType())) {
  6966. llvm::APInt ArraySize
  6967. = Array->getSize().zextOrTrunc(Size.getBitWidth());
  6968. Size *= ArraySize;
  6969. }
  6970. // Take the address of the field references for "from" and "to".
  6971. From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
  6972. To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
  6973. bool NeedsCollectableMemCpy =
  6974. (BaseType->isRecordType() &&
  6975. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
  6976. if (NeedsCollectableMemCpy) {
  6977. if (!CollectableMemCpyRef) {
  6978. // Create a reference to the __builtin_objc_memmove_collectable function.
  6979. LookupResult R(*this,
  6980. &Context.Idents.get("__builtin_objc_memmove_collectable"),
  6981. Loc, LookupOrdinaryName);
  6982. LookupName(R, TUScope, true);
  6983. FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
  6984. if (!CollectableMemCpy) {
  6985. // Something went horribly wrong earlier, and we will have
  6986. // complained about it.
  6987. Invalid = true;
  6988. continue;
  6989. }
  6990. CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
  6991. CollectableMemCpy->getType(),
  6992. VK_LValue, Loc, 0).take();
  6993. assert(CollectableMemCpyRef && "Builtin reference cannot fail");
  6994. }
  6995. }
  6996. // Create a reference to the __builtin_memcpy builtin function.
  6997. else if (!BuiltinMemCpyRef) {
  6998. LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
  6999. LookupOrdinaryName);
  7000. LookupName(R, TUScope, true);
  7001. FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
  7002. if (!BuiltinMemCpy) {
  7003. // Something went horribly wrong earlier, and we will have complained
  7004. // about it.
  7005. Invalid = true;
  7006. continue;
  7007. }
  7008. BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
  7009. BuiltinMemCpy->getType(),
  7010. VK_LValue, Loc, 0).take();
  7011. assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
  7012. }
  7013. ASTOwningVector<Expr*> CallArgs(*this);
  7014. CallArgs.push_back(To.takeAs<Expr>());
  7015. CallArgs.push_back(From.takeAs<Expr>());
  7016. CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
  7017. ExprResult Call = ExprError();
  7018. if (NeedsCollectableMemCpy)
  7019. Call = ActOnCallExpr(/*Scope=*/0,
  7020. CollectableMemCpyRef,
  7021. Loc, move_arg(CallArgs),
  7022. Loc);
  7023. else
  7024. Call = ActOnCallExpr(/*Scope=*/0,
  7025. BuiltinMemCpyRef,
  7026. Loc, move_arg(CallArgs),
  7027. Loc);
  7028. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  7029. Statements.push_back(Call.takeAs<Expr>());
  7030. continue;
  7031. }
  7032. // Build the copy of this field.
  7033. StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
  7034. To.get(), From.get(),
  7035. /*CopyingBaseSubobject=*/false,
  7036. /*Copying=*/true);
  7037. if (Copy.isInvalid()) {
  7038. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7039. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  7040. CopyAssignOperator->setInvalidDecl();
  7041. return;
  7042. }
  7043. // Success! Record the copy.
  7044. Statements.push_back(Copy.takeAs<Stmt>());
  7045. }
  7046. if (!Invalid) {
  7047. // Add a "return *this;"
  7048. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  7049. StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
  7050. if (Return.isInvalid())
  7051. Invalid = true;
  7052. else {
  7053. Statements.push_back(Return.takeAs<Stmt>());
  7054. if (Trap.hasErrorOccurred()) {
  7055. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7056. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  7057. Invalid = true;
  7058. }
  7059. }
  7060. }
  7061. if (Invalid) {
  7062. CopyAssignOperator->setInvalidDecl();
  7063. return;
  7064. }
  7065. StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
  7066. /*isStmtExpr=*/false);
  7067. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  7068. CopyAssignOperator->setBody(Body.takeAs<Stmt>());
  7069. if (ASTMutationListener *L = getASTMutationListener()) {
  7070. L->CompletedImplicitDefinition(CopyAssignOperator);
  7071. }
  7072. }
  7073. Sema::ImplicitExceptionSpecification
  7074. Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
  7075. ImplicitExceptionSpecification ExceptSpec(Context);
  7076. if (ClassDecl->isInvalidDecl())
  7077. return ExceptSpec;
  7078. // C++0x [except.spec]p14:
  7079. // An implicitly declared special member function (Clause 12) shall have an
  7080. // exception-specification. [...]
  7081. // It is unspecified whether or not an implicit move assignment operator
  7082. // attempts to deduplicate calls to assignment operators of virtual bases are
  7083. // made. As such, this exception specification is effectively unspecified.
  7084. // Based on a similar decision made for constness in C++0x, we're erring on
  7085. // the side of assuming such calls to be made regardless of whether they
  7086. // actually happen.
  7087. // Note that a move constructor is not implicitly declared when there are
  7088. // virtual bases, but it can still be user-declared and explicitly defaulted.
  7089. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  7090. BaseEnd = ClassDecl->bases_end();
  7091. Base != BaseEnd; ++Base) {
  7092. if (Base->isVirtual())
  7093. continue;
  7094. CXXRecordDecl *BaseClassDecl
  7095. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  7096. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  7097. false, 0))
  7098. ExceptSpec.CalledDecl(MoveAssign);
  7099. }
  7100. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
  7101. BaseEnd = ClassDecl->vbases_end();
  7102. Base != BaseEnd; ++Base) {
  7103. CXXRecordDecl *BaseClassDecl
  7104. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  7105. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  7106. false, 0))
  7107. ExceptSpec.CalledDecl(MoveAssign);
  7108. }
  7109. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  7110. FieldEnd = ClassDecl->field_end();
  7111. Field != FieldEnd;
  7112. ++Field) {
  7113. QualType FieldType = Context.getBaseElementType((*Field)->getType());
  7114. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  7115. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
  7116. false, 0))
  7117. ExceptSpec.CalledDecl(MoveAssign);
  7118. }
  7119. }
  7120. return ExceptSpec;
  7121. }
  7122. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  7123. // Note: The following rules are largely analoguous to the move
  7124. // constructor rules.
  7125. ImplicitExceptionSpecification Spec(
  7126. ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
  7127. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  7128. QualType RetType = Context.getLValueReferenceType(ArgType);
  7129. ArgType = Context.getRValueReferenceType(ArgType);
  7130. // An implicitly-declared move assignment operator is an inline public
  7131. // member of its class.
  7132. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  7133. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  7134. SourceLocation ClassLoc = ClassDecl->getLocation();
  7135. DeclarationNameInfo NameInfo(Name, ClassLoc);
  7136. CXXMethodDecl *MoveAssignment
  7137. = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  7138. Context.getFunctionType(RetType, &ArgType, 1, EPI),
  7139. /*TInfo=*/0, /*isStatic=*/false,
  7140. /*StorageClassAsWritten=*/SC_None,
  7141. /*isInline=*/true,
  7142. /*isConstexpr=*/false,
  7143. SourceLocation());
  7144. MoveAssignment->setAccess(AS_public);
  7145. MoveAssignment->setDefaulted();
  7146. MoveAssignment->setImplicit();
  7147. MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
  7148. // Add the parameter to the operator.
  7149. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  7150. ClassLoc, ClassLoc, /*Id=*/0,
  7151. ArgType, /*TInfo=*/0,
  7152. SC_None,
  7153. SC_None, 0);
  7154. MoveAssignment->setParams(FromParam);
  7155. // Note that we have added this copy-assignment operator.
  7156. ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  7157. // C++0x [class.copy]p9:
  7158. // If the definition of a class X does not explicitly declare a move
  7159. // assignment operator, one will be implicitly declared as defaulted if and
  7160. // only if:
  7161. // [...]
  7162. // - the move assignment operator would not be implicitly defined as
  7163. // deleted.
  7164. if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
  7165. // Cache this result so that we don't try to generate this over and over
  7166. // on every lookup, leaking memory and wasting time.
  7167. ClassDecl->setFailedImplicitMoveAssignment();
  7168. return 0;
  7169. }
  7170. if (Scope *S = getScopeForContext(ClassDecl))
  7171. PushOnScopeChains(MoveAssignment, S, false);
  7172. ClassDecl->addDecl(MoveAssignment);
  7173. AddOverriddenMethods(ClassDecl, MoveAssignment);
  7174. return MoveAssignment;
  7175. }
  7176. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  7177. CXXMethodDecl *MoveAssignOperator) {
  7178. assert((MoveAssignOperator->isDefaulted() &&
  7179. MoveAssignOperator->isOverloadedOperator() &&
  7180. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  7181. !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
  7182. "DefineImplicitMoveAssignment called for wrong function");
  7183. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  7184. if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
  7185. MoveAssignOperator->setInvalidDecl();
  7186. return;
  7187. }
  7188. MoveAssignOperator->setUsed();
  7189. ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
  7190. DiagnosticErrorTrap Trap(Diags);
  7191. // C++0x [class.copy]p28:
  7192. // The implicitly-defined or move assignment operator for a non-union class
  7193. // X performs memberwise move assignment of its subobjects. The direct base
  7194. // classes of X are assigned first, in the order of their declaration in the
  7195. // base-specifier-list, and then the immediate non-static data members of X
  7196. // are assigned, in the order in which they were declared in the class
  7197. // definition.
  7198. // The statements that form the synthesized function body.
  7199. ASTOwningVector<Stmt*> Statements(*this);
  7200. // The parameter for the "other" object, which we are move from.
  7201. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  7202. QualType OtherRefType = Other->getType()->
  7203. getAs<RValueReferenceType>()->getPointeeType();
  7204. assert(OtherRefType.getQualifiers() == 0 &&
  7205. "Bad argument type of defaulted move assignment");
  7206. // Our location for everything implicitly-generated.
  7207. SourceLocation Loc = MoveAssignOperator->getLocation();
  7208. // Construct a reference to the "other" object. We'll be using this
  7209. // throughout the generated ASTs.
  7210. Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
  7211. assert(OtherRef && "Reference to parameter cannot fail!");
  7212. // Cast to rvalue.
  7213. OtherRef = CastForMoving(*this, OtherRef);
  7214. // Construct the "this" pointer. We'll be using this throughout the generated
  7215. // ASTs.
  7216. Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
  7217. assert(This && "Reference to this cannot fail!");
  7218. // Assign base classes.
  7219. bool Invalid = false;
  7220. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  7221. E = ClassDecl->bases_end(); Base != E; ++Base) {
  7222. // Form the assignment:
  7223. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  7224. QualType BaseType = Base->getType().getUnqualifiedType();
  7225. if (!BaseType->isRecordType()) {
  7226. Invalid = true;
  7227. continue;
  7228. }
  7229. CXXCastPath BasePath;
  7230. BasePath.push_back(Base);
  7231. // Construct the "from" expression, which is an implicit cast to the
  7232. // appropriately-qualified base type.
  7233. Expr *From = OtherRef;
  7234. From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
  7235. VK_XValue, &BasePath).take();
  7236. // Dereference "this".
  7237. ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  7238. // Implicitly cast "this" to the appropriately-qualified base type.
  7239. To = ImpCastExprToType(To.take(),
  7240. Context.getCVRQualifiedType(BaseType,
  7241. MoveAssignOperator->getTypeQualifiers()),
  7242. CK_UncheckedDerivedToBase,
  7243. VK_LValue, &BasePath);
  7244. // Build the move.
  7245. StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
  7246. To.get(), From,
  7247. /*CopyingBaseSubobject=*/true,
  7248. /*Copying=*/false);
  7249. if (Move.isInvalid()) {
  7250. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7251. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  7252. MoveAssignOperator->setInvalidDecl();
  7253. return;
  7254. }
  7255. // Success! Record the move.
  7256. Statements.push_back(Move.takeAs<Expr>());
  7257. }
  7258. // \brief Reference to the __builtin_memcpy function.
  7259. Expr *BuiltinMemCpyRef = 0;
  7260. // \brief Reference to the __builtin_objc_memmove_collectable function.
  7261. Expr *CollectableMemCpyRef = 0;
  7262. // Assign non-static members.
  7263. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  7264. FieldEnd = ClassDecl->field_end();
  7265. Field != FieldEnd; ++Field) {
  7266. if (Field->isUnnamedBitfield())
  7267. continue;
  7268. // Check for members of reference type; we can't move those.
  7269. if (Field->getType()->isReferenceType()) {
  7270. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  7271. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  7272. Diag(Field->getLocation(), diag::note_declared_at);
  7273. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7274. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  7275. Invalid = true;
  7276. continue;
  7277. }
  7278. // Check for members of const-qualified, non-class type.
  7279. QualType BaseType = Context.getBaseElementType(Field->getType());
  7280. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  7281. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  7282. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  7283. Diag(Field->getLocation(), diag::note_declared_at);
  7284. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7285. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  7286. Invalid = true;
  7287. continue;
  7288. }
  7289. // Suppress assigning zero-width bitfields.
  7290. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  7291. continue;
  7292. QualType FieldType = Field->getType().getNonReferenceType();
  7293. if (FieldType->isIncompleteArrayType()) {
  7294. assert(ClassDecl->hasFlexibleArrayMember() &&
  7295. "Incomplete array type is not valid");
  7296. continue;
  7297. }
  7298. // Build references to the field in the object we're copying from and to.
  7299. CXXScopeSpec SS; // Intentionally empty
  7300. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  7301. LookupMemberName);
  7302. MemberLookup.addDecl(*Field);
  7303. MemberLookup.resolveKind();
  7304. ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
  7305. Loc, /*IsArrow=*/false,
  7306. SS, SourceLocation(), 0,
  7307. MemberLookup, 0);
  7308. ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
  7309. Loc, /*IsArrow=*/true,
  7310. SS, SourceLocation(), 0,
  7311. MemberLookup, 0);
  7312. assert(!From.isInvalid() && "Implicit field reference cannot fail");
  7313. assert(!To.isInvalid() && "Implicit field reference cannot fail");
  7314. assert(!From.get()->isLValue() && // could be xvalue or prvalue
  7315. "Member reference with rvalue base must be rvalue except for reference "
  7316. "members, which aren't allowed for move assignment.");
  7317. // If the field should be copied with __builtin_memcpy rather than via
  7318. // explicit assignments, do so. This optimization only applies for arrays
  7319. // of scalars and arrays of class type with trivial move-assignment
  7320. // operators.
  7321. if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
  7322. && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
  7323. // Compute the size of the memory buffer to be copied.
  7324. QualType SizeType = Context.getSizeType();
  7325. llvm::APInt Size(Context.getTypeSize(SizeType),
  7326. Context.getTypeSizeInChars(BaseType).getQuantity());
  7327. for (const ConstantArrayType *Array
  7328. = Context.getAsConstantArrayType(FieldType);
  7329. Array;
  7330. Array = Context.getAsConstantArrayType(Array->getElementType())) {
  7331. llvm::APInt ArraySize
  7332. = Array->getSize().zextOrTrunc(Size.getBitWidth());
  7333. Size *= ArraySize;
  7334. }
  7335. // Take the address of the field references for "from" and "to". We
  7336. // directly construct UnaryOperators here because semantic analysis
  7337. // does not permit us to take the address of an xvalue.
  7338. From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
  7339. Context.getPointerType(From.get()->getType()),
  7340. VK_RValue, OK_Ordinary, Loc);
  7341. To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
  7342. Context.getPointerType(To.get()->getType()),
  7343. VK_RValue, OK_Ordinary, Loc);
  7344. bool NeedsCollectableMemCpy =
  7345. (BaseType->isRecordType() &&
  7346. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
  7347. if (NeedsCollectableMemCpy) {
  7348. if (!CollectableMemCpyRef) {
  7349. // Create a reference to the __builtin_objc_memmove_collectable function.
  7350. LookupResult R(*this,
  7351. &Context.Idents.get("__builtin_objc_memmove_collectable"),
  7352. Loc, LookupOrdinaryName);
  7353. LookupName(R, TUScope, true);
  7354. FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
  7355. if (!CollectableMemCpy) {
  7356. // Something went horribly wrong earlier, and we will have
  7357. // complained about it.
  7358. Invalid = true;
  7359. continue;
  7360. }
  7361. CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
  7362. CollectableMemCpy->getType(),
  7363. VK_LValue, Loc, 0).take();
  7364. assert(CollectableMemCpyRef && "Builtin reference cannot fail");
  7365. }
  7366. }
  7367. // Create a reference to the __builtin_memcpy builtin function.
  7368. else if (!BuiltinMemCpyRef) {
  7369. LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
  7370. LookupOrdinaryName);
  7371. LookupName(R, TUScope, true);
  7372. FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
  7373. if (!BuiltinMemCpy) {
  7374. // Something went horribly wrong earlier, and we will have complained
  7375. // about it.
  7376. Invalid = true;
  7377. continue;
  7378. }
  7379. BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
  7380. BuiltinMemCpy->getType(),
  7381. VK_LValue, Loc, 0).take();
  7382. assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
  7383. }
  7384. ASTOwningVector<Expr*> CallArgs(*this);
  7385. CallArgs.push_back(To.takeAs<Expr>());
  7386. CallArgs.push_back(From.takeAs<Expr>());
  7387. CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
  7388. ExprResult Call = ExprError();
  7389. if (NeedsCollectableMemCpy)
  7390. Call = ActOnCallExpr(/*Scope=*/0,
  7391. CollectableMemCpyRef,
  7392. Loc, move_arg(CallArgs),
  7393. Loc);
  7394. else
  7395. Call = ActOnCallExpr(/*Scope=*/0,
  7396. BuiltinMemCpyRef,
  7397. Loc, move_arg(CallArgs),
  7398. Loc);
  7399. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  7400. Statements.push_back(Call.takeAs<Expr>());
  7401. continue;
  7402. }
  7403. // Build the move of this field.
  7404. StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
  7405. To.get(), From.get(),
  7406. /*CopyingBaseSubobject=*/false,
  7407. /*Copying=*/false);
  7408. if (Move.isInvalid()) {
  7409. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7410. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  7411. MoveAssignOperator->setInvalidDecl();
  7412. return;
  7413. }
  7414. // Success! Record the copy.
  7415. Statements.push_back(Move.takeAs<Stmt>());
  7416. }
  7417. if (!Invalid) {
  7418. // Add a "return *this;"
  7419. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
  7420. StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
  7421. if (Return.isInvalid())
  7422. Invalid = true;
  7423. else {
  7424. Statements.push_back(Return.takeAs<Stmt>());
  7425. if (Trap.hasErrorOccurred()) {
  7426. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7427. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  7428. Invalid = true;
  7429. }
  7430. }
  7431. }
  7432. if (Invalid) {
  7433. MoveAssignOperator->setInvalidDecl();
  7434. return;
  7435. }
  7436. StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
  7437. /*isStmtExpr=*/false);
  7438. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  7439. MoveAssignOperator->setBody(Body.takeAs<Stmt>());
  7440. if (ASTMutationListener *L = getASTMutationListener()) {
  7441. L->CompletedImplicitDefinition(MoveAssignOperator);
  7442. }
  7443. }
  7444. std::pair<Sema::ImplicitExceptionSpecification, bool>
  7445. Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
  7446. if (ClassDecl->isInvalidDecl())
  7447. return std::make_pair(ImplicitExceptionSpecification(Context), false);
  7448. // C++ [class.copy]p5:
  7449. // The implicitly-declared copy constructor for a class X will
  7450. // have the form
  7451. //
  7452. // X::X(const X&)
  7453. //
  7454. // if
  7455. // FIXME: It ought to be possible to store this on the record.
  7456. bool HasConstCopyConstructor = true;
  7457. // -- each direct or virtual base class B of X has a copy
  7458. // constructor whose first parameter is of type const B& or
  7459. // const volatile B&, and
  7460. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  7461. BaseEnd = ClassDecl->bases_end();
  7462. HasConstCopyConstructor && Base != BaseEnd;
  7463. ++Base) {
  7464. // Virtual bases are handled below.
  7465. if (Base->isVirtual())
  7466. continue;
  7467. CXXRecordDecl *BaseClassDecl
  7468. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  7469. LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
  7470. &HasConstCopyConstructor);
  7471. }
  7472. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
  7473. BaseEnd = ClassDecl->vbases_end();
  7474. HasConstCopyConstructor && Base != BaseEnd;
  7475. ++Base) {
  7476. CXXRecordDecl *BaseClassDecl
  7477. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  7478. LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
  7479. &HasConstCopyConstructor);
  7480. }
  7481. // -- for all the nonstatic data members of X that are of a
  7482. // class type M (or array thereof), each such class type
  7483. // has a copy constructor whose first parameter is of type
  7484. // const M& or const volatile M&.
  7485. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  7486. FieldEnd = ClassDecl->field_end();
  7487. HasConstCopyConstructor && Field != FieldEnd;
  7488. ++Field) {
  7489. QualType FieldType = Context.getBaseElementType((*Field)->getType());
  7490. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  7491. LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
  7492. &HasConstCopyConstructor);
  7493. }
  7494. }
  7495. // Otherwise, the implicitly declared copy constructor will have
  7496. // the form
  7497. //
  7498. // X::X(X&)
  7499. // C++ [except.spec]p14:
  7500. // An implicitly declared special member function (Clause 12) shall have an
  7501. // exception-specification. [...]
  7502. ImplicitExceptionSpecification ExceptSpec(Context);
  7503. unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
  7504. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
  7505. BaseEnd = ClassDecl->bases_end();
  7506. Base != BaseEnd;
  7507. ++Base) {
  7508. // Virtual bases are handled below.
  7509. if (Base->isVirtual())
  7510. continue;
  7511. CXXRecordDecl *BaseClassDecl
  7512. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  7513. if (CXXConstructorDecl *CopyConstructor =
  7514. LookupCopyingConstructor(BaseClassDecl, Quals))
  7515. ExceptSpec.CalledDecl(CopyConstructor);
  7516. }
  7517. for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
  7518. BaseEnd = ClassDecl->vbases_end();
  7519. Base != BaseEnd;
  7520. ++Base) {
  7521. CXXRecordDecl *BaseClassDecl
  7522. = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  7523. if (CXXConstructorDecl *CopyConstructor =
  7524. LookupCopyingConstructor(BaseClassDecl, Quals))
  7525. ExceptSpec.CalledDecl(CopyConstructor);
  7526. }
  7527. for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
  7528. FieldEnd = ClassDecl->field_end();
  7529. Field != FieldEnd;
  7530. ++Field) {
  7531. QualType FieldType = Context.getBaseElementType((*Field)->getType());
  7532. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  7533. if (CXXConstructorDecl *CopyConstructor =
  7534. LookupCopyingConstructor(FieldClassDecl, Quals))
  7535. ExceptSpec.CalledDecl(CopyConstructor);
  7536. }
  7537. }
  7538. return std::make_pair(ExceptSpec, HasConstCopyConstructor);
  7539. }
  7540. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  7541. CXXRecordDecl *ClassDecl) {
  7542. // C++ [class.copy]p4:
  7543. // If the class definition does not explicitly declare a copy
  7544. // constructor, one is declared implicitly.
  7545. ImplicitExceptionSpecification Spec(Context);
  7546. bool Const;
  7547. llvm::tie(Spec, Const) =
  7548. ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
  7549. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  7550. QualType ArgType = ClassType;
  7551. if (Const)
  7552. ArgType = ArgType.withConst();
  7553. ArgType = Context.getLValueReferenceType(ArgType);
  7554. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  7555. DeclarationName Name
  7556. = Context.DeclarationNames.getCXXConstructorName(
  7557. Context.getCanonicalType(ClassType));
  7558. SourceLocation ClassLoc = ClassDecl->getLocation();
  7559. DeclarationNameInfo NameInfo(Name, ClassLoc);
  7560. // An implicitly-declared copy constructor is an inline public
  7561. // member of its class.
  7562. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  7563. Context, ClassDecl, ClassLoc, NameInfo,
  7564. Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
  7565. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  7566. /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
  7567. getLangOptions().CPlusPlus0x);
  7568. CopyConstructor->setAccess(AS_public);
  7569. CopyConstructor->setDefaulted();
  7570. CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
  7571. // Note that we have declared this constructor.
  7572. ++ASTContext::NumImplicitCopyConstructorsDeclared;
  7573. // Add the parameter to the constructor.
  7574. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  7575. ClassLoc, ClassLoc,
  7576. /*IdentifierInfo=*/0,
  7577. ArgType, /*TInfo=*/0,
  7578. SC_None,
  7579. SC_None, 0);
  7580. CopyConstructor->setParams(FromParam);
  7581. if (Scope *S = getScopeForContext(ClassDecl))
  7582. PushOnScopeChains(CopyConstructor, S, false);
  7583. ClassDecl->addDecl(CopyConstructor);
  7584. // C++11 [class.copy]p8:
  7585. // ... If the class definition does not explicitly declare a copy
  7586. // constructor, there is no user-declared move constructor, and there is no
  7587. // user-declared move assignment operator, a copy constructor is implicitly
  7588. // declared as defaulted.
  7589. if (ClassDecl->hasUserDeclaredMoveConstructor() ||
  7590. (ClassDecl->hasUserDeclaredMoveAssignment() &&
  7591. !getLangOptions().MicrosoftMode) ||
  7592. ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
  7593. CopyConstructor->setDeletedAsWritten();
  7594. return CopyConstructor;
  7595. }
  7596. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  7597. CXXConstructorDecl *CopyConstructor) {
  7598. assert((CopyConstructor->isDefaulted() &&
  7599. CopyConstructor->isCopyConstructor() &&
  7600. !CopyConstructor->doesThisDeclarationHaveABody()) &&
  7601. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  7602. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  7603. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  7604. ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
  7605. DiagnosticErrorTrap Trap(Diags);
  7606. if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
  7607. Trap.hasErrorOccurred()) {
  7608. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7609. << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
  7610. CopyConstructor->setInvalidDecl();
  7611. } else {
  7612. CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
  7613. CopyConstructor->getLocation(),
  7614. MultiStmtArg(*this, 0, 0),
  7615. /*isStmtExpr=*/false)
  7616. .takeAs<Stmt>());
  7617. CopyConstructor->setImplicitlyDefined(true);
  7618. }
  7619. CopyConstructor->setUsed();
  7620. if (ASTMutationListener *L = getASTMutationListener()) {
  7621. L->CompletedImplicitDefinition(CopyConstructor);
  7622. }
  7623. }
  7624. Sema::ImplicitExceptionSpecification
  7625. Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
  7626. // C++ [except.spec]p14:
  7627. // An implicitly declared special member function (Clause 12) shall have an
  7628. // exception-specification. [...]
  7629. ImplicitExceptionSpecification ExceptSpec(Context);
  7630. if (ClassDecl->isInvalidDecl())
  7631. return ExceptSpec;
  7632. // Direct base-class constructors.
  7633. for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
  7634. BEnd = ClassDecl->bases_end();
  7635. B != BEnd; ++B) {
  7636. if (B->isVirtual()) // Handled below.
  7637. continue;
  7638. if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
  7639. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7640. CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
  7641. // If this is a deleted function, add it anyway. This might be conformant
  7642. // with the standard. This might not. I'm not sure. It might not matter.
  7643. if (Constructor)
  7644. ExceptSpec.CalledDecl(Constructor);
  7645. }
  7646. }
  7647. // Virtual base-class constructors.
  7648. for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
  7649. BEnd = ClassDecl->vbases_end();
  7650. B != BEnd; ++B) {
  7651. if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
  7652. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7653. CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
  7654. // If this is a deleted function, add it anyway. This might be conformant
  7655. // with the standard. This might not. I'm not sure. It might not matter.
  7656. if (Constructor)
  7657. ExceptSpec.CalledDecl(Constructor);
  7658. }
  7659. }
  7660. // Field constructors.
  7661. for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
  7662. FEnd = ClassDecl->field_end();
  7663. F != FEnd; ++F) {
  7664. if (const RecordType *RecordTy
  7665. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  7666. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  7667. CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
  7668. // If this is a deleted function, add it anyway. This might be conformant
  7669. // with the standard. This might not. I'm not sure. It might not matter.
  7670. // In particular, the problem is that this function never gets called. It
  7671. // might just be ill-formed because this function attempts to refer to
  7672. // a deleted function here.
  7673. if (Constructor)
  7674. ExceptSpec.CalledDecl(Constructor);
  7675. }
  7676. }
  7677. return ExceptSpec;
  7678. }
  7679. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  7680. CXXRecordDecl *ClassDecl) {
  7681. ImplicitExceptionSpecification Spec(
  7682. ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
  7683. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  7684. QualType ArgType = Context.getRValueReferenceType(ClassType);
  7685. FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
  7686. DeclarationName Name
  7687. = Context.DeclarationNames.getCXXConstructorName(
  7688. Context.getCanonicalType(ClassType));
  7689. SourceLocation ClassLoc = ClassDecl->getLocation();
  7690. DeclarationNameInfo NameInfo(Name, ClassLoc);
  7691. // C++0x [class.copy]p11:
  7692. // An implicitly-declared copy/move constructor is an inline public
  7693. // member of its class.
  7694. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  7695. Context, ClassDecl, ClassLoc, NameInfo,
  7696. Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
  7697. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  7698. /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
  7699. getLangOptions().CPlusPlus0x);
  7700. MoveConstructor->setAccess(AS_public);
  7701. MoveConstructor->setDefaulted();
  7702. MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
  7703. // Add the parameter to the constructor.
  7704. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  7705. ClassLoc, ClassLoc,
  7706. /*IdentifierInfo=*/0,
  7707. ArgType, /*TInfo=*/0,
  7708. SC_None,
  7709. SC_None, 0);
  7710. MoveConstructor->setParams(FromParam);
  7711. // C++0x [class.copy]p9:
  7712. // If the definition of a class X does not explicitly declare a move
  7713. // constructor, one will be implicitly declared as defaulted if and only if:
  7714. // [...]
  7715. // - the move constructor would not be implicitly defined as deleted.
  7716. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  7717. // Cache this result so that we don't try to generate this over and over
  7718. // on every lookup, leaking memory and wasting time.
  7719. ClassDecl->setFailedImplicitMoveConstructor();
  7720. return 0;
  7721. }
  7722. // Note that we have declared this constructor.
  7723. ++ASTContext::NumImplicitMoveConstructorsDeclared;
  7724. if (Scope *S = getScopeForContext(ClassDecl))
  7725. PushOnScopeChains(MoveConstructor, S, false);
  7726. ClassDecl->addDecl(MoveConstructor);
  7727. return MoveConstructor;
  7728. }
  7729. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  7730. CXXConstructorDecl *MoveConstructor) {
  7731. assert((MoveConstructor->isDefaulted() &&
  7732. MoveConstructor->isMoveConstructor() &&
  7733. !MoveConstructor->doesThisDeclarationHaveABody()) &&
  7734. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  7735. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  7736. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  7737. ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
  7738. DiagnosticErrorTrap Trap(Diags);
  7739. if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
  7740. Trap.hasErrorOccurred()) {
  7741. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7742. << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
  7743. MoveConstructor->setInvalidDecl();
  7744. } else {
  7745. MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
  7746. MoveConstructor->getLocation(),
  7747. MultiStmtArg(*this, 0, 0),
  7748. /*isStmtExpr=*/false)
  7749. .takeAs<Stmt>());
  7750. MoveConstructor->setImplicitlyDefined(true);
  7751. }
  7752. MoveConstructor->setUsed();
  7753. if (ASTMutationListener *L = getASTMutationListener()) {
  7754. L->CompletedImplicitDefinition(MoveConstructor);
  7755. }
  7756. }
  7757. ExprResult
  7758. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  7759. CXXConstructorDecl *Constructor,
  7760. MultiExprArg ExprArgs,
  7761. bool HadMultipleCandidates,
  7762. bool RequiresZeroInit,
  7763. unsigned ConstructKind,
  7764. SourceRange ParenRange) {
  7765. bool Elidable = false;
  7766. // C++0x [class.copy]p34:
  7767. // When certain criteria are met, an implementation is allowed to
  7768. // omit the copy/move construction of a class object, even if the
  7769. // copy/move constructor and/or destructor for the object have
  7770. // side effects. [...]
  7771. // - when a temporary class object that has not been bound to a
  7772. // reference (12.2) would be copied/moved to a class object
  7773. // with the same cv-unqualified type, the copy/move operation
  7774. // can be omitted by constructing the temporary object
  7775. // directly into the target of the omitted copy/move
  7776. if (ConstructKind == CXXConstructExpr::CK_Complete &&
  7777. Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
  7778. Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
  7779. Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
  7780. }
  7781. return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
  7782. Elidable, move(ExprArgs), HadMultipleCandidates,
  7783. RequiresZeroInit, ConstructKind, ParenRange);
  7784. }
  7785. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  7786. /// including handling of its default argument expressions.
  7787. ExprResult
  7788. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  7789. CXXConstructorDecl *Constructor, bool Elidable,
  7790. MultiExprArg ExprArgs,
  7791. bool HadMultipleCandidates,
  7792. bool RequiresZeroInit,
  7793. unsigned ConstructKind,
  7794. SourceRange ParenRange) {
  7795. unsigned NumExprs = ExprArgs.size();
  7796. Expr **Exprs = (Expr **)ExprArgs.release();
  7797. for (specific_attr_iterator<NonNullAttr>
  7798. i = Constructor->specific_attr_begin<NonNullAttr>(),
  7799. e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
  7800. const NonNullAttr *NonNull = *i;
  7801. CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
  7802. }
  7803. MarkFunctionReferenced(ConstructLoc, Constructor);
  7804. return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
  7805. Constructor, Elidable, Exprs, NumExprs,
  7806. HadMultipleCandidates, RequiresZeroInit,
  7807. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  7808. ParenRange));
  7809. }
  7810. bool Sema::InitializeVarWithConstructor(VarDecl *VD,
  7811. CXXConstructorDecl *Constructor,
  7812. MultiExprArg Exprs,
  7813. bool HadMultipleCandidates) {
  7814. // FIXME: Provide the correct paren SourceRange when available.
  7815. ExprResult TempResult =
  7816. BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
  7817. move(Exprs), HadMultipleCandidates, false,
  7818. CXXConstructExpr::CK_Complete, SourceRange());
  7819. if (TempResult.isInvalid())
  7820. return true;
  7821. Expr *Temp = TempResult.takeAs<Expr>();
  7822. CheckImplicitConversions(Temp, VD->getLocation());
  7823. MarkFunctionReferenced(VD->getLocation(), Constructor);
  7824. Temp = MaybeCreateExprWithCleanups(Temp);
  7825. VD->setInit(Temp);
  7826. return false;
  7827. }
  7828. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  7829. if (VD->isInvalidDecl()) return;
  7830. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  7831. if (ClassDecl->isInvalidDecl()) return;
  7832. if (ClassDecl->hasTrivialDestructor()) return;
  7833. if (ClassDecl->isDependentContext()) return;
  7834. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  7835. MarkFunctionReferenced(VD->getLocation(), Destructor);
  7836. CheckDestructorAccess(VD->getLocation(), Destructor,
  7837. PDiag(diag::err_access_dtor_var)
  7838. << VD->getDeclName()
  7839. << VD->getType());
  7840. if (!VD->hasGlobalStorage()) return;
  7841. // Emit warning for non-trivial dtor in global scope (a real global,
  7842. // class-static, function-static).
  7843. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  7844. // TODO: this should be re-enabled for static locals by !CXAAtExit
  7845. if (!VD->isStaticLocal())
  7846. Diag(VD->getLocation(), diag::warn_global_destructor);
  7847. }
  7848. /// AddCXXDirectInitializerToDecl - This action is called immediately after
  7849. /// ActOnDeclarator, when a C++ direct initializer is present.
  7850. /// e.g: "int x(1);"
  7851. void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
  7852. SourceLocation LParenLoc,
  7853. MultiExprArg Exprs,
  7854. SourceLocation RParenLoc,
  7855. bool TypeMayContainAuto) {
  7856. // If there is no declaration, there was an error parsing it. Just ignore
  7857. // the initializer.
  7858. if (RealDecl == 0)
  7859. return;
  7860. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  7861. if (!VDecl) {
  7862. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  7863. RealDecl->setInvalidDecl();
  7864. return;
  7865. }
  7866. // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  7867. if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
  7868. if (Exprs.size() == 0) {
  7869. // It isn't possible to write this directly, but it is possible to
  7870. // end up in this situation with "auto x(some_pack...);"
  7871. Diag(LParenLoc, diag::err_auto_var_init_no_expression)
  7872. << VDecl->getDeclName() << VDecl->getType()
  7873. << VDecl->getSourceRange();
  7874. RealDecl->setInvalidDecl();
  7875. return;
  7876. }
  7877. if (Exprs.size() > 1) {
  7878. Diag(Exprs.get()[1]->getSourceRange().getBegin(),
  7879. diag::err_auto_var_init_multiple_expressions)
  7880. << VDecl->getDeclName() << VDecl->getType()
  7881. << VDecl->getSourceRange();
  7882. RealDecl->setInvalidDecl();
  7883. return;
  7884. }
  7885. Expr *Init = Exprs.get()[0];
  7886. TypeSourceInfo *DeducedType = 0;
  7887. if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
  7888. DAR_Failed)
  7889. DiagnoseAutoDeductionFailure(VDecl, Init);
  7890. if (!DeducedType) {
  7891. RealDecl->setInvalidDecl();
  7892. return;
  7893. }
  7894. VDecl->setTypeSourceInfo(DeducedType);
  7895. VDecl->setType(DeducedType->getType());
  7896. // In ARC, infer lifetime.
  7897. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  7898. VDecl->setInvalidDecl();
  7899. // If this is a redeclaration, check that the type we just deduced matches
  7900. // the previously declared type.
  7901. if (VarDecl *Old = VDecl->getPreviousDecl())
  7902. MergeVarDeclTypes(VDecl, Old);
  7903. }
  7904. // We will represent direct-initialization similarly to copy-initialization:
  7905. // int x(1); -as-> int x = 1;
  7906. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  7907. //
  7908. // Clients that want to distinguish between the two forms, can check for
  7909. // direct initializer using VarDecl::hasCXXDirectInitializer().
  7910. // A major benefit is that clients that don't particularly care about which
  7911. // exactly form was it (like the CodeGen) can handle both cases without
  7912. // special case code.
  7913. // C++ 8.5p11:
  7914. // The form of initialization (using parentheses or '=') is generally
  7915. // insignificant, but does matter when the entity being initialized has a
  7916. // class type.
  7917. if (!VDecl->getType()->isDependentType() &&
  7918. !VDecl->getType()->isIncompleteArrayType() &&
  7919. RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
  7920. diag::err_typecheck_decl_incomplete_type)) {
  7921. VDecl->setInvalidDecl();
  7922. return;
  7923. }
  7924. // The variable can not have an abstract class type.
  7925. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  7926. diag::err_abstract_type_in_decl,
  7927. AbstractVariableType))
  7928. VDecl->setInvalidDecl();
  7929. const VarDecl *Def;
  7930. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  7931. Diag(VDecl->getLocation(), diag::err_redefinition)
  7932. << VDecl->getDeclName();
  7933. Diag(Def->getLocation(), diag::note_previous_definition);
  7934. VDecl->setInvalidDecl();
  7935. return;
  7936. }
  7937. // C++ [class.static.data]p4
  7938. // If a static data member is of const integral or const
  7939. // enumeration type, its declaration in the class definition can
  7940. // specify a constant-initializer which shall be an integral
  7941. // constant expression (5.19). In that case, the member can appear
  7942. // in integral constant expressions. The member shall still be
  7943. // defined in a namespace scope if it is used in the program and the
  7944. // namespace scope definition shall not contain an initializer.
  7945. //
  7946. // We already performed a redefinition check above, but for static
  7947. // data members we also need to check whether there was an in-class
  7948. // declaration with an initializer.
  7949. const VarDecl* PrevInit = 0;
  7950. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  7951. Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
  7952. Diag(PrevInit->getLocation(), diag::note_previous_definition);
  7953. return;
  7954. }
  7955. bool IsDependent = false;
  7956. for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
  7957. if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
  7958. VDecl->setInvalidDecl();
  7959. return;
  7960. }
  7961. if (Exprs.get()[I]->isTypeDependent())
  7962. IsDependent = true;
  7963. }
  7964. // If either the declaration has a dependent type or if any of the
  7965. // expressions is type-dependent, we represent the initialization
  7966. // via a ParenListExpr for later use during template instantiation.
  7967. if (VDecl->getType()->isDependentType() || IsDependent) {
  7968. // Let clients know that initialization was done with a direct initializer.
  7969. VDecl->setCXXDirectInitializer(true);
  7970. // Store the initialization expressions as a ParenListExpr.
  7971. unsigned NumExprs = Exprs.size();
  7972. VDecl->setInit(new (Context) ParenListExpr(
  7973. Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
  7974. VDecl->getType().getNonReferenceType()));
  7975. return;
  7976. }
  7977. // Capture the variable that is being initialized and the style of
  7978. // initialization.
  7979. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  7980. // FIXME: Poor source location information.
  7981. InitializationKind Kind
  7982. = InitializationKind::CreateDirect(VDecl->getLocation(),
  7983. LParenLoc, RParenLoc);
  7984. QualType T = VDecl->getType();
  7985. InitializationSequence InitSeq(*this, Entity, Kind,
  7986. Exprs.get(), Exprs.size());
  7987. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
  7988. if (Result.isInvalid()) {
  7989. VDecl->setInvalidDecl();
  7990. return;
  7991. } else if (T != VDecl->getType()) {
  7992. VDecl->setType(T);
  7993. Result.get()->setType(T);
  7994. }
  7995. Expr *Init = Result.get();
  7996. CheckImplicitConversions(Init, LParenLoc);
  7997. Init = MaybeCreateExprWithCleanups(Init);
  7998. VDecl->setInit(Init);
  7999. VDecl->setCXXDirectInitializer(true);
  8000. CheckCompleteVariableDeclaration(VDecl);
  8001. }
  8002. /// \brief Given a constructor and the set of arguments provided for the
  8003. /// constructor, convert the arguments and add any required default arguments
  8004. /// to form a proper call to this constructor.
  8005. ///
  8006. /// \returns true if an error occurred, false otherwise.
  8007. bool
  8008. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  8009. MultiExprArg ArgsPtr,
  8010. SourceLocation Loc,
  8011. ASTOwningVector<Expr*> &ConvertedArgs) {
  8012. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  8013. unsigned NumArgs = ArgsPtr.size();
  8014. Expr **Args = (Expr **)ArgsPtr.get();
  8015. const FunctionProtoType *Proto
  8016. = Constructor->getType()->getAs<FunctionProtoType>();
  8017. assert(Proto && "Constructor without a prototype?");
  8018. unsigned NumArgsInProto = Proto->getNumArgs();
  8019. // If too few arguments are available, we'll fill in the rest with defaults.
  8020. if (NumArgs < NumArgsInProto)
  8021. ConvertedArgs.reserve(NumArgsInProto);
  8022. else
  8023. ConvertedArgs.reserve(NumArgs);
  8024. VariadicCallType CallType =
  8025. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  8026. SmallVector<Expr *, 8> AllArgs;
  8027. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  8028. Proto, 0, Args, NumArgs, AllArgs,
  8029. CallType);
  8030. for (unsigned i =0, size = AllArgs.size(); i < size; i++)
  8031. ConvertedArgs.push_back(AllArgs[i]);
  8032. return Invalid;
  8033. }
  8034. static inline bool
  8035. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  8036. const FunctionDecl *FnDecl) {
  8037. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  8038. if (isa<NamespaceDecl>(DC)) {
  8039. return SemaRef.Diag(FnDecl->getLocation(),
  8040. diag::err_operator_new_delete_declared_in_namespace)
  8041. << FnDecl->getDeclName();
  8042. }
  8043. if (isa<TranslationUnitDecl>(DC) &&
  8044. FnDecl->getStorageClass() == SC_Static) {
  8045. return SemaRef.Diag(FnDecl->getLocation(),
  8046. diag::err_operator_new_delete_declared_static)
  8047. << FnDecl->getDeclName();
  8048. }
  8049. return false;
  8050. }
  8051. static inline bool
  8052. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  8053. CanQualType ExpectedResultType,
  8054. CanQualType ExpectedFirstParamType,
  8055. unsigned DependentParamTypeDiag,
  8056. unsigned InvalidParamTypeDiag) {
  8057. QualType ResultType =
  8058. FnDecl->getType()->getAs<FunctionType>()->getResultType();
  8059. // Check that the result type is not dependent.
  8060. if (ResultType->isDependentType())
  8061. return SemaRef.Diag(FnDecl->getLocation(),
  8062. diag::err_operator_new_delete_dependent_result_type)
  8063. << FnDecl->getDeclName() << ExpectedResultType;
  8064. // Check that the result type is what we expect.
  8065. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  8066. return SemaRef.Diag(FnDecl->getLocation(),
  8067. diag::err_operator_new_delete_invalid_result_type)
  8068. << FnDecl->getDeclName() << ExpectedResultType;
  8069. // A function template must have at least 2 parameters.
  8070. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  8071. return SemaRef.Diag(FnDecl->getLocation(),
  8072. diag::err_operator_new_delete_template_too_few_parameters)
  8073. << FnDecl->getDeclName();
  8074. // The function decl must have at least 1 parameter.
  8075. if (FnDecl->getNumParams() == 0)
  8076. return SemaRef.Diag(FnDecl->getLocation(),
  8077. diag::err_operator_new_delete_too_few_parameters)
  8078. << FnDecl->getDeclName();
  8079. // Check the the first parameter type is not dependent.
  8080. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  8081. if (FirstParamType->isDependentType())
  8082. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  8083. << FnDecl->getDeclName() << ExpectedFirstParamType;
  8084. // Check that the first parameter type is what we expect.
  8085. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  8086. ExpectedFirstParamType)
  8087. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  8088. << FnDecl->getDeclName() << ExpectedFirstParamType;
  8089. return false;
  8090. }
  8091. static bool
  8092. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  8093. // C++ [basic.stc.dynamic.allocation]p1:
  8094. // A program is ill-formed if an allocation function is declared in a
  8095. // namespace scope other than global scope or declared static in global
  8096. // scope.
  8097. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  8098. return true;
  8099. CanQualType SizeTy =
  8100. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  8101. // C++ [basic.stc.dynamic.allocation]p1:
  8102. // The return type shall be void*. The first parameter shall have type
  8103. // std::size_t.
  8104. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  8105. SizeTy,
  8106. diag::err_operator_new_dependent_param_type,
  8107. diag::err_operator_new_param_type))
  8108. return true;
  8109. // C++ [basic.stc.dynamic.allocation]p1:
  8110. // The first parameter shall not have an associated default argument.
  8111. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  8112. return SemaRef.Diag(FnDecl->getLocation(),
  8113. diag::err_operator_new_default_arg)
  8114. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  8115. return false;
  8116. }
  8117. static bool
  8118. CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  8119. // C++ [basic.stc.dynamic.deallocation]p1:
  8120. // A program is ill-formed if deallocation functions are declared in a
  8121. // namespace scope other than global scope or declared static in global
  8122. // scope.
  8123. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  8124. return true;
  8125. // C++ [basic.stc.dynamic.deallocation]p2:
  8126. // Each deallocation function shall return void and its first parameter
  8127. // shall be void*.
  8128. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
  8129. SemaRef.Context.VoidPtrTy,
  8130. diag::err_operator_delete_dependent_param_type,
  8131. diag::err_operator_delete_param_type))
  8132. return true;
  8133. return false;
  8134. }
  8135. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  8136. /// of this overloaded operator is well-formed. If so, returns false;
  8137. /// otherwise, emits appropriate diagnostics and returns true.
  8138. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  8139. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  8140. "Expected an overloaded operator declaration");
  8141. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  8142. // C++ [over.oper]p5:
  8143. // The allocation and deallocation functions, operator new,
  8144. // operator new[], operator delete and operator delete[], are
  8145. // described completely in 3.7.3. The attributes and restrictions
  8146. // found in the rest of this subclause do not apply to them unless
  8147. // explicitly stated in 3.7.3.
  8148. if (Op == OO_Delete || Op == OO_Array_Delete)
  8149. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  8150. if (Op == OO_New || Op == OO_Array_New)
  8151. return CheckOperatorNewDeclaration(*this, FnDecl);
  8152. // C++ [over.oper]p6:
  8153. // An operator function shall either be a non-static member
  8154. // function or be a non-member function and have at least one
  8155. // parameter whose type is a class, a reference to a class, an
  8156. // enumeration, or a reference to an enumeration.
  8157. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  8158. if (MethodDecl->isStatic())
  8159. return Diag(FnDecl->getLocation(),
  8160. diag::err_operator_overload_static) << FnDecl->getDeclName();
  8161. } else {
  8162. bool ClassOrEnumParam = false;
  8163. for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
  8164. ParamEnd = FnDecl->param_end();
  8165. Param != ParamEnd; ++Param) {
  8166. QualType ParamType = (*Param)->getType().getNonReferenceType();
  8167. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  8168. ParamType->isEnumeralType()) {
  8169. ClassOrEnumParam = true;
  8170. break;
  8171. }
  8172. }
  8173. if (!ClassOrEnumParam)
  8174. return Diag(FnDecl->getLocation(),
  8175. diag::err_operator_overload_needs_class_or_enum)
  8176. << FnDecl->getDeclName();
  8177. }
  8178. // C++ [over.oper]p8:
  8179. // An operator function cannot have default arguments (8.3.6),
  8180. // except where explicitly stated below.
  8181. //
  8182. // Only the function-call operator allows default arguments
  8183. // (C++ [over.call]p1).
  8184. if (Op != OO_Call) {
  8185. for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
  8186. Param != FnDecl->param_end(); ++Param) {
  8187. if ((*Param)->hasDefaultArg())
  8188. return Diag((*Param)->getLocation(),
  8189. diag::err_operator_overload_default_arg)
  8190. << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
  8191. }
  8192. }
  8193. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  8194. { false, false, false }
  8195. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  8196. , { Unary, Binary, MemberOnly }
  8197. #include "clang/Basic/OperatorKinds.def"
  8198. };
  8199. bool CanBeUnaryOperator = OperatorUses[Op][0];
  8200. bool CanBeBinaryOperator = OperatorUses[Op][1];
  8201. bool MustBeMemberOperator = OperatorUses[Op][2];
  8202. // C++ [over.oper]p8:
  8203. // [...] Operator functions cannot have more or fewer parameters
  8204. // than the number required for the corresponding operator, as
  8205. // described in the rest of this subclause.
  8206. unsigned NumParams = FnDecl->getNumParams()
  8207. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  8208. if (Op != OO_Call &&
  8209. ((NumParams == 1 && !CanBeUnaryOperator) ||
  8210. (NumParams == 2 && !CanBeBinaryOperator) ||
  8211. (NumParams < 1) || (NumParams > 2))) {
  8212. // We have the wrong number of parameters.
  8213. unsigned ErrorKind;
  8214. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  8215. ErrorKind = 2; // 2 -> unary or binary.
  8216. } else if (CanBeUnaryOperator) {
  8217. ErrorKind = 0; // 0 -> unary
  8218. } else {
  8219. assert(CanBeBinaryOperator &&
  8220. "All non-call overloaded operators are unary or binary!");
  8221. ErrorKind = 1; // 1 -> binary
  8222. }
  8223. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  8224. << FnDecl->getDeclName() << NumParams << ErrorKind;
  8225. }
  8226. // Overloaded operators other than operator() cannot be variadic.
  8227. if (Op != OO_Call &&
  8228. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  8229. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  8230. << FnDecl->getDeclName();
  8231. }
  8232. // Some operators must be non-static member functions.
  8233. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  8234. return Diag(FnDecl->getLocation(),
  8235. diag::err_operator_overload_must_be_member)
  8236. << FnDecl->getDeclName();
  8237. }
  8238. // C++ [over.inc]p1:
  8239. // The user-defined function called operator++ implements the
  8240. // prefix and postfix ++ operator. If this function is a member
  8241. // function with no parameters, or a non-member function with one
  8242. // parameter of class or enumeration type, it defines the prefix
  8243. // increment operator ++ for objects of that type. If the function
  8244. // is a member function with one parameter (which shall be of type
  8245. // int) or a non-member function with two parameters (the second
  8246. // of which shall be of type int), it defines the postfix
  8247. // increment operator ++ for objects of that type.
  8248. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  8249. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  8250. bool ParamIsInt = false;
  8251. if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
  8252. ParamIsInt = BT->getKind() == BuiltinType::Int;
  8253. if (!ParamIsInt)
  8254. return Diag(LastParam->getLocation(),
  8255. diag::err_operator_overload_post_incdec_must_be_int)
  8256. << LastParam->getType() << (Op == OO_MinusMinus);
  8257. }
  8258. return false;
  8259. }
  8260. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  8261. /// of this literal operator function is well-formed. If so, returns
  8262. /// false; otherwise, emits appropriate diagnostics and returns true.
  8263. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  8264. DeclContext *DC = FnDecl->getDeclContext();
  8265. Decl::Kind Kind = DC->getDeclKind();
  8266. if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
  8267. Kind != Decl::LinkageSpec) {
  8268. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  8269. << FnDecl->getDeclName();
  8270. return true;
  8271. }
  8272. bool Valid = false;
  8273. // template <char...> type operator "" name() is the only valid template
  8274. // signature, and the only valid signature with no parameters.
  8275. if (FnDecl->param_size() == 0) {
  8276. if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
  8277. // Must have only one template parameter
  8278. TemplateParameterList *Params = TpDecl->getTemplateParameters();
  8279. if (Params->size() == 1) {
  8280. NonTypeTemplateParmDecl *PmDecl =
  8281. cast<NonTypeTemplateParmDecl>(Params->getParam(0));
  8282. // The template parameter must be a char parameter pack.
  8283. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  8284. Context.hasSameType(PmDecl->getType(), Context.CharTy))
  8285. Valid = true;
  8286. }
  8287. }
  8288. } else {
  8289. // Check the first parameter
  8290. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  8291. QualType T = (*Param)->getType();
  8292. // unsigned long long int, long double, and any character type are allowed
  8293. // as the only parameters.
  8294. if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
  8295. Context.hasSameType(T, Context.LongDoubleTy) ||
  8296. Context.hasSameType(T, Context.CharTy) ||
  8297. Context.hasSameType(T, Context.WCharTy) ||
  8298. Context.hasSameType(T, Context.Char16Ty) ||
  8299. Context.hasSameType(T, Context.Char32Ty)) {
  8300. if (++Param == FnDecl->param_end())
  8301. Valid = true;
  8302. goto FinishedParams;
  8303. }
  8304. // Otherwise it must be a pointer to const; let's strip those qualifiers.
  8305. const PointerType *PT = T->getAs<PointerType>();
  8306. if (!PT)
  8307. goto FinishedParams;
  8308. T = PT->getPointeeType();
  8309. if (!T.isConstQualified())
  8310. goto FinishedParams;
  8311. T = T.getUnqualifiedType();
  8312. // Move on to the second parameter;
  8313. ++Param;
  8314. // If there is no second parameter, the first must be a const char *
  8315. if (Param == FnDecl->param_end()) {
  8316. if (Context.hasSameType(T, Context.CharTy))
  8317. Valid = true;
  8318. goto FinishedParams;
  8319. }
  8320. // const char *, const wchar_t*, const char16_t*, and const char32_t*
  8321. // are allowed as the first parameter to a two-parameter function
  8322. if (!(Context.hasSameType(T, Context.CharTy) ||
  8323. Context.hasSameType(T, Context.WCharTy) ||
  8324. Context.hasSameType(T, Context.Char16Ty) ||
  8325. Context.hasSameType(T, Context.Char32Ty)))
  8326. goto FinishedParams;
  8327. // The second and final parameter must be an std::size_t
  8328. T = (*Param)->getType().getUnqualifiedType();
  8329. if (Context.hasSameType(T, Context.getSizeType()) &&
  8330. ++Param == FnDecl->param_end())
  8331. Valid = true;
  8332. }
  8333. // FIXME: This diagnostic is absolutely terrible.
  8334. FinishedParams:
  8335. if (!Valid) {
  8336. Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
  8337. << FnDecl->getDeclName();
  8338. return true;
  8339. }
  8340. StringRef LiteralName
  8341. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  8342. if (LiteralName[0] != '_') {
  8343. // C++0x [usrlit.suffix]p1:
  8344. // Literal suffix identifiers that do not start with an underscore are
  8345. // reserved for future standardization.
  8346. bool IsHexFloat = true;
  8347. if (LiteralName.size() > 1 &&
  8348. (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
  8349. for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
  8350. if (!isdigit(LiteralName[I])) {
  8351. IsHexFloat = false;
  8352. break;
  8353. }
  8354. }
  8355. }
  8356. if (IsHexFloat)
  8357. Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
  8358. << LiteralName;
  8359. else
  8360. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
  8361. }
  8362. return false;
  8363. }
  8364. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  8365. /// linkage specification, including the language and (if present)
  8366. /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
  8367. /// the location of the language string literal, which is provided
  8368. /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
  8369. /// the '{' brace. Otherwise, this linkage specification does not
  8370. /// have any braces.
  8371. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  8372. SourceLocation LangLoc,
  8373. StringRef Lang,
  8374. SourceLocation LBraceLoc) {
  8375. LinkageSpecDecl::LanguageIDs Language;
  8376. if (Lang == "\"C\"")
  8377. Language = LinkageSpecDecl::lang_c;
  8378. else if (Lang == "\"C++\"")
  8379. Language = LinkageSpecDecl::lang_cxx;
  8380. else {
  8381. Diag(LangLoc, diag::err_bad_language);
  8382. return 0;
  8383. }
  8384. // FIXME: Add all the various semantics of linkage specifications
  8385. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
  8386. ExternLoc, LangLoc, Language);
  8387. CurContext->addDecl(D);
  8388. PushDeclContext(S, D);
  8389. return D;
  8390. }
  8391. /// ActOnFinishLinkageSpecification - Complete the definition of
  8392. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  8393. /// valid, it's the position of the closing '}' brace in a linkage
  8394. /// specification that uses braces.
  8395. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  8396. Decl *LinkageSpec,
  8397. SourceLocation RBraceLoc) {
  8398. if (LinkageSpec) {
  8399. if (RBraceLoc.isValid()) {
  8400. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  8401. LSDecl->setRBraceLoc(RBraceLoc);
  8402. }
  8403. PopDeclContext();
  8404. }
  8405. return LinkageSpec;
  8406. }
  8407. /// \brief Perform semantic analysis for the variable declaration that
  8408. /// occurs within a C++ catch clause, returning the newly-created
  8409. /// variable.
  8410. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  8411. TypeSourceInfo *TInfo,
  8412. SourceLocation StartLoc,
  8413. SourceLocation Loc,
  8414. IdentifierInfo *Name) {
  8415. bool Invalid = false;
  8416. QualType ExDeclType = TInfo->getType();
  8417. // Arrays and functions decay.
  8418. if (ExDeclType->isArrayType())
  8419. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  8420. else if (ExDeclType->isFunctionType())
  8421. ExDeclType = Context.getPointerType(ExDeclType);
  8422. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  8423. // The exception-declaration shall not denote a pointer or reference to an
  8424. // incomplete type, other than [cv] void*.
  8425. // N2844 forbids rvalue references.
  8426. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  8427. Diag(Loc, diag::err_catch_rvalue_ref);
  8428. Invalid = true;
  8429. }
  8430. QualType BaseType = ExDeclType;
  8431. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  8432. unsigned DK = diag::err_catch_incomplete;
  8433. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  8434. BaseType = Ptr->getPointeeType();
  8435. Mode = 1;
  8436. DK = diag::err_catch_incomplete_ptr;
  8437. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  8438. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  8439. BaseType = Ref->getPointeeType();
  8440. Mode = 2;
  8441. DK = diag::err_catch_incomplete_ref;
  8442. }
  8443. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  8444. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  8445. Invalid = true;
  8446. if (!Invalid && !ExDeclType->isDependentType() &&
  8447. RequireNonAbstractType(Loc, ExDeclType,
  8448. diag::err_abstract_type_in_decl,
  8449. AbstractVariableType))
  8450. Invalid = true;
  8451. // Only the non-fragile NeXT runtime currently supports C++ catches
  8452. // of ObjC types, and no runtime supports catching ObjC types by value.
  8453. if (!Invalid && getLangOptions().ObjC1) {
  8454. QualType T = ExDeclType;
  8455. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  8456. T = RT->getPointeeType();
  8457. if (T->isObjCObjectType()) {
  8458. Diag(Loc, diag::err_objc_object_catch);
  8459. Invalid = true;
  8460. } else if (T->isObjCObjectPointerType()) {
  8461. if (!getLangOptions().ObjCNonFragileABI)
  8462. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  8463. }
  8464. }
  8465. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  8466. ExDeclType, TInfo, SC_None, SC_None);
  8467. ExDecl->setExceptionVariable(true);
  8468. // In ARC, infer 'retaining' for variables of retainable type.
  8469. if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  8470. Invalid = true;
  8471. if (!Invalid && !ExDeclType->isDependentType()) {
  8472. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  8473. // C++ [except.handle]p16:
  8474. // The object declared in an exception-declaration or, if the
  8475. // exception-declaration does not specify a name, a temporary (12.2) is
  8476. // copy-initialized (8.5) from the exception object. [...]
  8477. // The object is destroyed when the handler exits, after the destruction
  8478. // of any automatic objects initialized within the handler.
  8479. //
  8480. // We just pretend to initialize the object with itself, then make sure
  8481. // it can be destroyed later.
  8482. QualType initType = ExDeclType;
  8483. InitializedEntity entity =
  8484. InitializedEntity::InitializeVariable(ExDecl);
  8485. InitializationKind initKind =
  8486. InitializationKind::CreateCopy(Loc, SourceLocation());
  8487. Expr *opaqueValue =
  8488. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  8489. InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
  8490. ExprResult result = sequence.Perform(*this, entity, initKind,
  8491. MultiExprArg(&opaqueValue, 1));
  8492. if (result.isInvalid())
  8493. Invalid = true;
  8494. else {
  8495. // If the constructor used was non-trivial, set this as the
  8496. // "initializer".
  8497. CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
  8498. if (!construct->getConstructor()->isTrivial()) {
  8499. Expr *init = MaybeCreateExprWithCleanups(construct);
  8500. ExDecl->setInit(init);
  8501. }
  8502. // And make sure it's destructable.
  8503. FinalizeVarWithDestructor(ExDecl, recordType);
  8504. }
  8505. }
  8506. }
  8507. if (Invalid)
  8508. ExDecl->setInvalidDecl();
  8509. return ExDecl;
  8510. }
  8511. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  8512. /// handler.
  8513. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  8514. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8515. bool Invalid = D.isInvalidType();
  8516. // Check for unexpanded parameter packs.
  8517. if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  8518. UPPC_ExceptionType)) {
  8519. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  8520. D.getIdentifierLoc());
  8521. Invalid = true;
  8522. }
  8523. IdentifierInfo *II = D.getIdentifier();
  8524. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  8525. LookupOrdinaryName,
  8526. ForRedeclaration)) {
  8527. // The scope should be freshly made just for us. There is just no way
  8528. // it contains any previous declaration.
  8529. assert(!S->isDeclScope(PrevDecl));
  8530. if (PrevDecl->isTemplateParameter()) {
  8531. // Maybe we will complain about the shadowed template parameter.
  8532. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  8533. PrevDecl = 0;
  8534. }
  8535. }
  8536. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  8537. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  8538. << D.getCXXScopeSpec().getRange();
  8539. Invalid = true;
  8540. }
  8541. VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
  8542. D.getSourceRange().getBegin(),
  8543. D.getIdentifierLoc(),
  8544. D.getIdentifier());
  8545. if (Invalid)
  8546. ExDecl->setInvalidDecl();
  8547. // Add the exception declaration into this scope.
  8548. if (II)
  8549. PushOnScopeChains(ExDecl, S);
  8550. else
  8551. CurContext->addDecl(ExDecl);
  8552. ProcessDeclAttributes(S, ExDecl, D);
  8553. return ExDecl;
  8554. }
  8555. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  8556. Expr *AssertExpr,
  8557. Expr *AssertMessageExpr_,
  8558. SourceLocation RParenLoc) {
  8559. StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
  8560. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
  8561. // In a static_assert-declaration, the constant-expression shall be a
  8562. // constant expression that can be contextually converted to bool.
  8563. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  8564. if (Converted.isInvalid())
  8565. return 0;
  8566. llvm::APSInt Cond;
  8567. if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
  8568. PDiag(diag::err_static_assert_expression_is_not_constant),
  8569. /*AllowFold=*/false).isInvalid())
  8570. return 0;
  8571. if (!Cond)
  8572. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  8573. << AssertMessage->getString() << AssertExpr->getSourceRange();
  8574. }
  8575. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  8576. return 0;
  8577. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  8578. AssertExpr, AssertMessage, RParenLoc);
  8579. CurContext->addDecl(Decl);
  8580. return Decl;
  8581. }
  8582. /// \brief Perform semantic analysis of the given friend type declaration.
  8583. ///
  8584. /// \returns A friend declaration that.
  8585. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
  8586. SourceLocation FriendLoc,
  8587. TypeSourceInfo *TSInfo) {
  8588. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  8589. QualType T = TSInfo->getType();
  8590. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  8591. // C++03 [class.friend]p2:
  8592. // An elaborated-type-specifier shall be used in a friend declaration
  8593. // for a class.*
  8594. //
  8595. // * The class-key of the elaborated-type-specifier is required.
  8596. if (!ActiveTemplateInstantiations.empty()) {
  8597. // Do not complain about the form of friend template types during
  8598. // template instantiation; we will already have complained when the
  8599. // template was declared.
  8600. } else if (!T->isElaboratedTypeSpecifier()) {
  8601. // If we evaluated the type to a record type, suggest putting
  8602. // a tag in front.
  8603. if (const RecordType *RT = T->getAs<RecordType>()) {
  8604. RecordDecl *RD = RT->getDecl();
  8605. std::string InsertionText = std::string(" ") + RD->getKindName();
  8606. Diag(TypeRange.getBegin(),
  8607. getLangOptions().CPlusPlus0x ?
  8608. diag::warn_cxx98_compat_unelaborated_friend_type :
  8609. diag::ext_unelaborated_friend_type)
  8610. << (unsigned) RD->getTagKind()
  8611. << T
  8612. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
  8613. InsertionText);
  8614. } else {
  8615. Diag(FriendLoc,
  8616. getLangOptions().CPlusPlus0x ?
  8617. diag::warn_cxx98_compat_nonclass_type_friend :
  8618. diag::ext_nonclass_type_friend)
  8619. << T
  8620. << SourceRange(FriendLoc, TypeRange.getEnd());
  8621. }
  8622. } else if (T->getAs<EnumType>()) {
  8623. Diag(FriendLoc,
  8624. getLangOptions().CPlusPlus0x ?
  8625. diag::warn_cxx98_compat_enum_friend :
  8626. diag::ext_enum_friend)
  8627. << T
  8628. << SourceRange(FriendLoc, TypeRange.getEnd());
  8629. }
  8630. // C++0x [class.friend]p3:
  8631. // If the type specifier in a friend declaration designates a (possibly
  8632. // cv-qualified) class type, that class is declared as a friend; otherwise,
  8633. // the friend declaration is ignored.
  8634. // FIXME: C++0x has some syntactic restrictions on friend type declarations
  8635. // in [class.friend]p3 that we do not implement.
  8636. return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
  8637. }
  8638. /// Handle a friend tag declaration where the scope specifier was
  8639. /// templated.
  8640. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  8641. unsigned TagSpec, SourceLocation TagLoc,
  8642. CXXScopeSpec &SS,
  8643. IdentifierInfo *Name, SourceLocation NameLoc,
  8644. AttributeList *Attr,
  8645. MultiTemplateParamsArg TempParamLists) {
  8646. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  8647. bool isExplicitSpecialization = false;
  8648. bool Invalid = false;
  8649. if (TemplateParameterList *TemplateParams
  8650. = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
  8651. TempParamLists.get(),
  8652. TempParamLists.size(),
  8653. /*friend*/ true,
  8654. isExplicitSpecialization,
  8655. Invalid)) {
  8656. if (TemplateParams->size() > 0) {
  8657. // This is a declaration of a class template.
  8658. if (Invalid)
  8659. return 0;
  8660. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
  8661. SS, Name, NameLoc, Attr,
  8662. TemplateParams, AS_public,
  8663. /*ModulePrivateLoc=*/SourceLocation(),
  8664. TempParamLists.size() - 1,
  8665. (TemplateParameterList**) TempParamLists.release()).take();
  8666. } else {
  8667. // The "template<>" header is extraneous.
  8668. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  8669. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  8670. isExplicitSpecialization = true;
  8671. }
  8672. }
  8673. if (Invalid) return 0;
  8674. bool isAllExplicitSpecializations = true;
  8675. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  8676. if (TempParamLists.get()[I]->size()) {
  8677. isAllExplicitSpecializations = false;
  8678. break;
  8679. }
  8680. }
  8681. // FIXME: don't ignore attributes.
  8682. // If it's explicit specializations all the way down, just forget
  8683. // about the template header and build an appropriate non-templated
  8684. // friend. TODO: for source fidelity, remember the headers.
  8685. if (isAllExplicitSpecializations) {
  8686. if (SS.isEmpty()) {
  8687. bool Owned = false;
  8688. bool IsDependent = false;
  8689. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  8690. Attr, AS_public,
  8691. /*ModulePrivateLoc=*/SourceLocation(),
  8692. MultiTemplateParamsArg(), Owned, IsDependent,
  8693. /*ScopedEnumKWLoc=*/SourceLocation(),
  8694. /*ScopedEnumUsesClassTag=*/false,
  8695. /*UnderlyingType=*/TypeResult());
  8696. }
  8697. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  8698. ElaboratedTypeKeyword Keyword
  8699. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  8700. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  8701. *Name, NameLoc);
  8702. if (T.isNull())
  8703. return 0;
  8704. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  8705. if (isa<DependentNameType>(T)) {
  8706. DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
  8707. TL.setKeywordLoc(TagLoc);
  8708. TL.setQualifierLoc(QualifierLoc);
  8709. TL.setNameLoc(NameLoc);
  8710. } else {
  8711. ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
  8712. TL.setKeywordLoc(TagLoc);
  8713. TL.setQualifierLoc(QualifierLoc);
  8714. cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
  8715. }
  8716. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  8717. TSI, FriendLoc);
  8718. Friend->setAccess(AS_public);
  8719. CurContext->addDecl(Friend);
  8720. return Friend;
  8721. }
  8722. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  8723. // Handle the case of a templated-scope friend class. e.g.
  8724. // template <class T> class A<T>::B;
  8725. // FIXME: we don't support these right now.
  8726. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  8727. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  8728. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  8729. DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
  8730. TL.setKeywordLoc(TagLoc);
  8731. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  8732. TL.setNameLoc(NameLoc);
  8733. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  8734. TSI, FriendLoc);
  8735. Friend->setAccess(AS_public);
  8736. Friend->setUnsupportedFriend(true);
  8737. CurContext->addDecl(Friend);
  8738. return Friend;
  8739. }
  8740. /// Handle a friend type declaration. This works in tandem with
  8741. /// ActOnTag.
  8742. ///
  8743. /// Notes on friend class templates:
  8744. ///
  8745. /// We generally treat friend class declarations as if they were
  8746. /// declaring a class. So, for example, the elaborated type specifier
  8747. /// in a friend declaration is required to obey the restrictions of a
  8748. /// class-head (i.e. no typedefs in the scope chain), template
  8749. /// parameters are required to match up with simple template-ids, &c.
  8750. /// However, unlike when declaring a template specialization, it's
  8751. /// okay to refer to a template specialization without an empty
  8752. /// template parameter declaration, e.g.
  8753. /// friend class A<T>::B<unsigned>;
  8754. /// We permit this as a special case; if there are any template
  8755. /// parameters present at all, require proper matching, i.e.
  8756. /// template <> template <class T> friend class A<int>::B;
  8757. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  8758. MultiTemplateParamsArg TempParams) {
  8759. SourceLocation Loc = DS.getSourceRange().getBegin();
  8760. assert(DS.isFriendSpecified());
  8761. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  8762. // Try to convert the decl specifier to a type. This works for
  8763. // friend templates because ActOnTag never produces a ClassTemplateDecl
  8764. // for a TUK_Friend.
  8765. Declarator TheDeclarator(DS, Declarator::MemberContext);
  8766. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  8767. QualType T = TSI->getType();
  8768. if (TheDeclarator.isInvalidType())
  8769. return 0;
  8770. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  8771. return 0;
  8772. // This is definitely an error in C++98. It's probably meant to
  8773. // be forbidden in C++0x, too, but the specification is just
  8774. // poorly written.
  8775. //
  8776. // The problem is with declarations like the following:
  8777. // template <T> friend A<T>::foo;
  8778. // where deciding whether a class C is a friend or not now hinges
  8779. // on whether there exists an instantiation of A that causes
  8780. // 'foo' to equal C. There are restrictions on class-heads
  8781. // (which we declare (by fiat) elaborated friend declarations to
  8782. // be) that makes this tractable.
  8783. //
  8784. // FIXME: handle "template <> friend class A<T>;", which
  8785. // is possibly well-formed? Who even knows?
  8786. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  8787. Diag(Loc, diag::err_tagless_friend_type_template)
  8788. << DS.getSourceRange();
  8789. return 0;
  8790. }
  8791. // C++98 [class.friend]p1: A friend of a class is a function
  8792. // or class that is not a member of the class . . .
  8793. // This is fixed in DR77, which just barely didn't make the C++03
  8794. // deadline. It's also a very silly restriction that seriously
  8795. // affects inner classes and which nobody else seems to implement;
  8796. // thus we never diagnose it, not even in -pedantic.
  8797. //
  8798. // But note that we could warn about it: it's always useless to
  8799. // friend one of your own members (it's not, however, worthless to
  8800. // friend a member of an arbitrary specialization of your template).
  8801. Decl *D;
  8802. if (unsigned NumTempParamLists = TempParams.size())
  8803. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  8804. NumTempParamLists,
  8805. TempParams.release(),
  8806. TSI,
  8807. DS.getFriendSpecLoc());
  8808. else
  8809. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  8810. if (!D)
  8811. return 0;
  8812. D->setAccess(AS_public);
  8813. CurContext->addDecl(D);
  8814. return D;
  8815. }
  8816. Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  8817. MultiTemplateParamsArg TemplateParams) {
  8818. const DeclSpec &DS = D.getDeclSpec();
  8819. assert(DS.isFriendSpecified());
  8820. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  8821. SourceLocation Loc = D.getIdentifierLoc();
  8822. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8823. // C++ [class.friend]p1
  8824. // A friend of a class is a function or class....
  8825. // Note that this sees through typedefs, which is intended.
  8826. // It *doesn't* see through dependent types, which is correct
  8827. // according to [temp.arg.type]p3:
  8828. // If a declaration acquires a function type through a
  8829. // type dependent on a template-parameter and this causes
  8830. // a declaration that does not use the syntactic form of a
  8831. // function declarator to have a function type, the program
  8832. // is ill-formed.
  8833. if (!TInfo->getType()->isFunctionType()) {
  8834. Diag(Loc, diag::err_unexpected_friend);
  8835. // It might be worthwhile to try to recover by creating an
  8836. // appropriate declaration.
  8837. return 0;
  8838. }
  8839. // C++ [namespace.memdef]p3
  8840. // - If a friend declaration in a non-local class first declares a
  8841. // class or function, the friend class or function is a member
  8842. // of the innermost enclosing namespace.
  8843. // - The name of the friend is not found by simple name lookup
  8844. // until a matching declaration is provided in that namespace
  8845. // scope (either before or after the class declaration granting
  8846. // friendship).
  8847. // - If a friend function is called, its name may be found by the
  8848. // name lookup that considers functions from namespaces and
  8849. // classes associated with the types of the function arguments.
  8850. // - When looking for a prior declaration of a class or a function
  8851. // declared as a friend, scopes outside the innermost enclosing
  8852. // namespace scope are not considered.
  8853. CXXScopeSpec &SS = D.getCXXScopeSpec();
  8854. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  8855. DeclarationName Name = NameInfo.getName();
  8856. assert(Name);
  8857. // Check for unexpanded parameter packs.
  8858. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  8859. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  8860. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  8861. return 0;
  8862. // The context we found the declaration in, or in which we should
  8863. // create the declaration.
  8864. DeclContext *DC;
  8865. Scope *DCScope = S;
  8866. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  8867. ForRedeclaration);
  8868. // FIXME: there are different rules in local classes
  8869. // There are four cases here.
  8870. // - There's no scope specifier, in which case we just go to the
  8871. // appropriate scope and look for a function or function template
  8872. // there as appropriate.
  8873. // Recover from invalid scope qualifiers as if they just weren't there.
  8874. if (SS.isInvalid() || !SS.isSet()) {
  8875. // C++0x [namespace.memdef]p3:
  8876. // If the name in a friend declaration is neither qualified nor
  8877. // a template-id and the declaration is a function or an
  8878. // elaborated-type-specifier, the lookup to determine whether
  8879. // the entity has been previously declared shall not consider
  8880. // any scopes outside the innermost enclosing namespace.
  8881. // C++0x [class.friend]p11:
  8882. // If a friend declaration appears in a local class and the name
  8883. // specified is an unqualified name, a prior declaration is
  8884. // looked up without considering scopes that are outside the
  8885. // innermost enclosing non-class scope. For a friend function
  8886. // declaration, if there is no prior declaration, the program is
  8887. // ill-formed.
  8888. bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
  8889. bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
  8890. // Find the appropriate context according to the above.
  8891. DC = CurContext;
  8892. while (true) {
  8893. // Skip class contexts. If someone can cite chapter and verse
  8894. // for this behavior, that would be nice --- it's what GCC and
  8895. // EDG do, and it seems like a reasonable intent, but the spec
  8896. // really only says that checks for unqualified existing
  8897. // declarations should stop at the nearest enclosing namespace,
  8898. // not that they should only consider the nearest enclosing
  8899. // namespace.
  8900. while (DC->isRecord())
  8901. DC = DC->getParent();
  8902. LookupQualifiedName(Previous, DC);
  8903. // TODO: decide what we think about using declarations.
  8904. if (isLocal || !Previous.empty())
  8905. break;
  8906. if (isTemplateId) {
  8907. if (isa<TranslationUnitDecl>(DC)) break;
  8908. } else {
  8909. if (DC->isFileContext()) break;
  8910. }
  8911. DC = DC->getParent();
  8912. }
  8913. // C++ [class.friend]p1: A friend of a class is a function or
  8914. // class that is not a member of the class . . .
  8915. // C++11 changes this for both friend types and functions.
  8916. // Most C++ 98 compilers do seem to give an error here, so
  8917. // we do, too.
  8918. if (!Previous.empty() && DC->Equals(CurContext))
  8919. Diag(DS.getFriendSpecLoc(),
  8920. getLangOptions().CPlusPlus0x ?
  8921. diag::warn_cxx98_compat_friend_is_member :
  8922. diag::err_friend_is_member);
  8923. DCScope = getScopeForDeclContext(S, DC);
  8924. // C++ [class.friend]p6:
  8925. // A function can be defined in a friend declaration of a class if and
  8926. // only if the class is a non-local class (9.8), the function name is
  8927. // unqualified, and the function has namespace scope.
  8928. if (isLocal && D.isFunctionDefinition()) {
  8929. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  8930. }
  8931. // - There's a non-dependent scope specifier, in which case we
  8932. // compute it and do a previous lookup there for a function
  8933. // or function template.
  8934. } else if (!SS.getScopeRep()->isDependent()) {
  8935. DC = computeDeclContext(SS);
  8936. if (!DC) return 0;
  8937. if (RequireCompleteDeclContext(SS, DC)) return 0;
  8938. LookupQualifiedName(Previous, DC);
  8939. // Ignore things found implicitly in the wrong scope.
  8940. // TODO: better diagnostics for this case. Suggesting the right
  8941. // qualified scope would be nice...
  8942. LookupResult::Filter F = Previous.makeFilter();
  8943. while (F.hasNext()) {
  8944. NamedDecl *D = F.next();
  8945. if (!DC->InEnclosingNamespaceSetOf(
  8946. D->getDeclContext()->getRedeclContext()))
  8947. F.erase();
  8948. }
  8949. F.done();
  8950. if (Previous.empty()) {
  8951. D.setInvalidType();
  8952. Diag(Loc, diag::err_qualified_friend_not_found)
  8953. << Name << TInfo->getType();
  8954. return 0;
  8955. }
  8956. // C++ [class.friend]p1: A friend of a class is a function or
  8957. // class that is not a member of the class . . .
  8958. if (DC->Equals(CurContext))
  8959. Diag(DS.getFriendSpecLoc(),
  8960. getLangOptions().CPlusPlus0x ?
  8961. diag::warn_cxx98_compat_friend_is_member :
  8962. diag::err_friend_is_member);
  8963. if (D.isFunctionDefinition()) {
  8964. // C++ [class.friend]p6:
  8965. // A function can be defined in a friend declaration of a class if and
  8966. // only if the class is a non-local class (9.8), the function name is
  8967. // unqualified, and the function has namespace scope.
  8968. SemaDiagnosticBuilder DB
  8969. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  8970. DB << SS.getScopeRep();
  8971. if (DC->isFileContext())
  8972. DB << FixItHint::CreateRemoval(SS.getRange());
  8973. SS.clear();
  8974. }
  8975. // - There's a scope specifier that does not match any template
  8976. // parameter lists, in which case we use some arbitrary context,
  8977. // create a method or method template, and wait for instantiation.
  8978. // - There's a scope specifier that does match some template
  8979. // parameter lists, which we don't handle right now.
  8980. } else {
  8981. if (D.isFunctionDefinition()) {
  8982. // C++ [class.friend]p6:
  8983. // A function can be defined in a friend declaration of a class if and
  8984. // only if the class is a non-local class (9.8), the function name is
  8985. // unqualified, and the function has namespace scope.
  8986. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  8987. << SS.getScopeRep();
  8988. }
  8989. DC = CurContext;
  8990. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  8991. }
  8992. if (!DC->isRecord()) {
  8993. // This implies that it has to be an operator or function.
  8994. if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
  8995. D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
  8996. D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
  8997. Diag(Loc, diag::err_introducing_special_friend) <<
  8998. (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
  8999. D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
  9000. return 0;
  9001. }
  9002. }
  9003. // FIXME: This is an egregious hack to cope with cases where the scope stack
  9004. // does not contain the declaration context, i.e., in an out-of-line
  9005. // definition of a class.
  9006. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  9007. if (!DCScope) {
  9008. FakeDCScope.setEntity(DC);
  9009. DCScope = &FakeDCScope;
  9010. }
  9011. bool AddToScope = true;
  9012. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  9013. move(TemplateParams), AddToScope);
  9014. if (!ND) return 0;
  9015. assert(ND->getDeclContext() == DC);
  9016. assert(ND->getLexicalDeclContext() == CurContext);
  9017. // Add the function declaration to the appropriate lookup tables,
  9018. // adjusting the redeclarations list as necessary. We don't
  9019. // want to do this yet if the friending class is dependent.
  9020. //
  9021. // Also update the scope-based lookup if the target context's
  9022. // lookup context is in lexical scope.
  9023. if (!CurContext->isDependentContext()) {
  9024. DC = DC->getRedeclContext();
  9025. DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
  9026. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  9027. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  9028. }
  9029. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  9030. D.getIdentifierLoc(), ND,
  9031. DS.getFriendSpecLoc());
  9032. FrD->setAccess(AS_public);
  9033. CurContext->addDecl(FrD);
  9034. if (ND->isInvalidDecl())
  9035. FrD->setInvalidDecl();
  9036. else {
  9037. FunctionDecl *FD;
  9038. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  9039. FD = FTD->getTemplatedDecl();
  9040. else
  9041. FD = cast<FunctionDecl>(ND);
  9042. // Mark templated-scope function declarations as unsupported.
  9043. if (FD->getNumTemplateParameterLists())
  9044. FrD->setUnsupportedFriend(true);
  9045. }
  9046. return ND;
  9047. }
  9048. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  9049. AdjustDeclIfTemplate(Dcl);
  9050. FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
  9051. if (!Fn) {
  9052. Diag(DelLoc, diag::err_deleted_non_function);
  9053. return;
  9054. }
  9055. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  9056. Diag(DelLoc, diag::err_deleted_decl_not_first);
  9057. Diag(Prev->getLocation(), diag::note_previous_declaration);
  9058. // If the declaration wasn't the first, we delete the function anyway for
  9059. // recovery.
  9060. }
  9061. Fn->setDeletedAsWritten();
  9062. }
  9063. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  9064. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
  9065. if (MD) {
  9066. if (MD->getParent()->isDependentType()) {
  9067. MD->setDefaulted();
  9068. MD->setExplicitlyDefaulted();
  9069. return;
  9070. }
  9071. CXXSpecialMember Member = getSpecialMember(MD);
  9072. if (Member == CXXInvalid) {
  9073. Diag(DefaultLoc, diag::err_default_special_members);
  9074. return;
  9075. }
  9076. MD->setDefaulted();
  9077. MD->setExplicitlyDefaulted();
  9078. // If this definition appears within the record, do the checking when
  9079. // the record is complete.
  9080. const FunctionDecl *Primary = MD;
  9081. if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
  9082. // Find the uninstantiated declaration that actually had the '= default'
  9083. // on it.
  9084. MD->getTemplateInstantiationPattern()->isDefined(Primary);
  9085. if (Primary == Primary->getCanonicalDecl())
  9086. return;
  9087. switch (Member) {
  9088. case CXXDefaultConstructor: {
  9089. CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
  9090. CheckExplicitlyDefaultedDefaultConstructor(CD);
  9091. if (!CD->isInvalidDecl())
  9092. DefineImplicitDefaultConstructor(DefaultLoc, CD);
  9093. break;
  9094. }
  9095. case CXXCopyConstructor: {
  9096. CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
  9097. CheckExplicitlyDefaultedCopyConstructor(CD);
  9098. if (!CD->isInvalidDecl())
  9099. DefineImplicitCopyConstructor(DefaultLoc, CD);
  9100. break;
  9101. }
  9102. case CXXCopyAssignment: {
  9103. CheckExplicitlyDefaultedCopyAssignment(MD);
  9104. if (!MD->isInvalidDecl())
  9105. DefineImplicitCopyAssignment(DefaultLoc, MD);
  9106. break;
  9107. }
  9108. case CXXDestructor: {
  9109. CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
  9110. CheckExplicitlyDefaultedDestructor(DD);
  9111. if (!DD->isInvalidDecl())
  9112. DefineImplicitDestructor(DefaultLoc, DD);
  9113. break;
  9114. }
  9115. case CXXMoveConstructor: {
  9116. CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
  9117. CheckExplicitlyDefaultedMoveConstructor(CD);
  9118. if (!CD->isInvalidDecl())
  9119. DefineImplicitMoveConstructor(DefaultLoc, CD);
  9120. break;
  9121. }
  9122. case CXXMoveAssignment: {
  9123. CheckExplicitlyDefaultedMoveAssignment(MD);
  9124. if (!MD->isInvalidDecl())
  9125. DefineImplicitMoveAssignment(DefaultLoc, MD);
  9126. break;
  9127. }
  9128. case CXXInvalid:
  9129. llvm_unreachable("Invalid special member.");
  9130. }
  9131. } else {
  9132. Diag(DefaultLoc, diag::err_default_special_members);
  9133. }
  9134. }
  9135. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  9136. for (Stmt::child_range CI = S->children(); CI; ++CI) {
  9137. Stmt *SubStmt = *CI;
  9138. if (!SubStmt)
  9139. continue;
  9140. if (isa<ReturnStmt>(SubStmt))
  9141. Self.Diag(SubStmt->getSourceRange().getBegin(),
  9142. diag::err_return_in_constructor_handler);
  9143. if (!isa<Expr>(SubStmt))
  9144. SearchForReturnInStmt(Self, SubStmt);
  9145. }
  9146. }
  9147. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  9148. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  9149. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  9150. SearchForReturnInStmt(*this, Handler);
  9151. }
  9152. }
  9153. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  9154. const CXXMethodDecl *Old) {
  9155. QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
  9156. QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
  9157. if (Context.hasSameType(NewTy, OldTy) ||
  9158. NewTy->isDependentType() || OldTy->isDependentType())
  9159. return false;
  9160. // Check if the return types are covariant
  9161. QualType NewClassTy, OldClassTy;
  9162. /// Both types must be pointers or references to classes.
  9163. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  9164. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  9165. NewClassTy = NewPT->getPointeeType();
  9166. OldClassTy = OldPT->getPointeeType();
  9167. }
  9168. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  9169. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  9170. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  9171. NewClassTy = NewRT->getPointeeType();
  9172. OldClassTy = OldRT->getPointeeType();
  9173. }
  9174. }
  9175. }
  9176. // The return types aren't either both pointers or references to a class type.
  9177. if (NewClassTy.isNull()) {
  9178. Diag(New->getLocation(),
  9179. diag::err_different_return_type_for_overriding_virtual_function)
  9180. << New->getDeclName() << NewTy << OldTy;
  9181. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  9182. return true;
  9183. }
  9184. // C++ [class.virtual]p6:
  9185. // If the return type of D::f differs from the return type of B::f, the
  9186. // class type in the return type of D::f shall be complete at the point of
  9187. // declaration of D::f or shall be the class type D.
  9188. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  9189. if (!RT->isBeingDefined() &&
  9190. RequireCompleteType(New->getLocation(), NewClassTy,
  9191. PDiag(diag::err_covariant_return_incomplete)
  9192. << New->getDeclName()))
  9193. return true;
  9194. }
  9195. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  9196. // Check if the new class derives from the old class.
  9197. if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
  9198. Diag(New->getLocation(),
  9199. diag::err_covariant_return_not_derived)
  9200. << New->getDeclName() << NewTy << OldTy;
  9201. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  9202. return true;
  9203. }
  9204. // Check if we the conversion from derived to base is valid.
  9205. if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
  9206. diag::err_covariant_return_inaccessible_base,
  9207. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  9208. // FIXME: Should this point to the return type?
  9209. New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
  9210. // FIXME: this note won't trigger for delayed access control
  9211. // diagnostics, and it's impossible to get an undelayed error
  9212. // here from access control during the original parse because
  9213. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  9214. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  9215. return true;
  9216. }
  9217. }
  9218. // The qualifiers of the return types must be the same.
  9219. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  9220. Diag(New->getLocation(),
  9221. diag::err_covariant_return_type_different_qualifications)
  9222. << New->getDeclName() << NewTy << OldTy;
  9223. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  9224. return true;
  9225. };
  9226. // The new class type must have the same or less qualifiers as the old type.
  9227. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  9228. Diag(New->getLocation(),
  9229. diag::err_covariant_return_type_class_type_more_qualified)
  9230. << New->getDeclName() << NewTy << OldTy;
  9231. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  9232. return true;
  9233. };
  9234. return false;
  9235. }
  9236. /// \brief Mark the given method pure.
  9237. ///
  9238. /// \param Method the method to be marked pure.
  9239. ///
  9240. /// \param InitRange the source range that covers the "0" initializer.
  9241. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  9242. SourceLocation EndLoc = InitRange.getEnd();
  9243. if (EndLoc.isValid())
  9244. Method->setRangeEnd(EndLoc);
  9245. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  9246. Method->setPure();
  9247. return false;
  9248. }
  9249. if (!Method->isInvalidDecl())
  9250. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  9251. << Method->getDeclName() << InitRange;
  9252. return true;
  9253. }
  9254. /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
  9255. /// an initializer for the out-of-line declaration 'Dcl'. The scope
  9256. /// is a fresh scope pushed for just this purpose.
  9257. ///
  9258. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  9259. /// static data member of class X, names should be looked up in the scope of
  9260. /// class X.
  9261. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  9262. // If there is no declaration, there was an error parsing it.
  9263. if (D == 0 || D->isInvalidDecl()) return;
  9264. // We should only get called for declarations with scope specifiers, like:
  9265. // int foo::bar;
  9266. assert(D->isOutOfLine());
  9267. EnterDeclaratorContext(S, D->getDeclContext());
  9268. }
  9269. /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
  9270. /// initializer for the out-of-line declaration 'D'.
  9271. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  9272. // If there is no declaration, there was an error parsing it.
  9273. if (D == 0 || D->isInvalidDecl()) return;
  9274. assert(D->isOutOfLine());
  9275. ExitDeclaratorContext(S);
  9276. }
  9277. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  9278. /// C++ if/switch/while/for statement.
  9279. /// e.g: "if (int x = f()) {...}"
  9280. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  9281. // C++ 6.4p2:
  9282. // The declarator shall not specify a function or an array.
  9283. // The type-specifier-seq shall not contain typedef and shall not declare a
  9284. // new class or enumeration.
  9285. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  9286. "Parser allowed 'typedef' as storage class of condition decl.");
  9287. Decl *Dcl = ActOnDeclarator(S, D);
  9288. if (!Dcl)
  9289. return true;
  9290. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  9291. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  9292. << D.getSourceRange();
  9293. return true;
  9294. }
  9295. return Dcl;
  9296. }
  9297. void Sema::LoadExternalVTableUses() {
  9298. if (!ExternalSource)
  9299. return;
  9300. SmallVector<ExternalVTableUse, 4> VTables;
  9301. ExternalSource->ReadUsedVTables(VTables);
  9302. SmallVector<VTableUse, 4> NewUses;
  9303. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  9304. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  9305. = VTablesUsed.find(VTables[I].Record);
  9306. // Even if a definition wasn't required before, it may be required now.
  9307. if (Pos != VTablesUsed.end()) {
  9308. if (!Pos->second && VTables[I].DefinitionRequired)
  9309. Pos->second = true;
  9310. continue;
  9311. }
  9312. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  9313. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  9314. }
  9315. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  9316. }
  9317. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  9318. bool DefinitionRequired) {
  9319. // Ignore any vtable uses in unevaluated operands or for classes that do
  9320. // not have a vtable.
  9321. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  9322. CurContext->isDependentContext() ||
  9323. ExprEvalContexts.back().Context == Unevaluated)
  9324. return;
  9325. // Try to insert this class into the map.
  9326. LoadExternalVTableUses();
  9327. Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  9328. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  9329. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  9330. if (!Pos.second) {
  9331. // If we already had an entry, check to see if we are promoting this vtable
  9332. // to required a definition. If so, we need to reappend to the VTableUses
  9333. // list, since we may have already processed the first entry.
  9334. if (DefinitionRequired && !Pos.first->second) {
  9335. Pos.first->second = true;
  9336. } else {
  9337. // Otherwise, we can early exit.
  9338. return;
  9339. }
  9340. }
  9341. // Local classes need to have their virtual members marked
  9342. // immediately. For all other classes, we mark their virtual members
  9343. // at the end of the translation unit.
  9344. if (Class->isLocalClass())
  9345. MarkVirtualMembersReferenced(Loc, Class);
  9346. else
  9347. VTableUses.push_back(std::make_pair(Class, Loc));
  9348. }
  9349. bool Sema::DefineUsedVTables() {
  9350. LoadExternalVTableUses();
  9351. if (VTableUses.empty())
  9352. return false;
  9353. // Note: The VTableUses vector could grow as a result of marking
  9354. // the members of a class as "used", so we check the size each
  9355. // time through the loop and prefer indices (with are stable) to
  9356. // iterators (which are not).
  9357. bool DefinedAnything = false;
  9358. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  9359. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  9360. if (!Class)
  9361. continue;
  9362. SourceLocation Loc = VTableUses[I].second;
  9363. // If this class has a key function, but that key function is
  9364. // defined in another translation unit, we don't need to emit the
  9365. // vtable even though we're using it.
  9366. const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
  9367. if (KeyFunction && !KeyFunction->hasBody()) {
  9368. switch (KeyFunction->getTemplateSpecializationKind()) {
  9369. case TSK_Undeclared:
  9370. case TSK_ExplicitSpecialization:
  9371. case TSK_ExplicitInstantiationDeclaration:
  9372. // The key function is in another translation unit.
  9373. continue;
  9374. case TSK_ExplicitInstantiationDefinition:
  9375. case TSK_ImplicitInstantiation:
  9376. // We will be instantiating the key function.
  9377. break;
  9378. }
  9379. } else if (!KeyFunction) {
  9380. // If we have a class with no key function that is the subject
  9381. // of an explicit instantiation declaration, suppress the
  9382. // vtable; it will live with the explicit instantiation
  9383. // definition.
  9384. bool IsExplicitInstantiationDeclaration
  9385. = Class->getTemplateSpecializationKind()
  9386. == TSK_ExplicitInstantiationDeclaration;
  9387. for (TagDecl::redecl_iterator R = Class->redecls_begin(),
  9388. REnd = Class->redecls_end();
  9389. R != REnd; ++R) {
  9390. TemplateSpecializationKind TSK
  9391. = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
  9392. if (TSK == TSK_ExplicitInstantiationDeclaration)
  9393. IsExplicitInstantiationDeclaration = true;
  9394. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  9395. IsExplicitInstantiationDeclaration = false;
  9396. break;
  9397. }
  9398. }
  9399. if (IsExplicitInstantiationDeclaration)
  9400. continue;
  9401. }
  9402. // Mark all of the virtual members of this class as referenced, so
  9403. // that we can build a vtable. Then, tell the AST consumer that a
  9404. // vtable for this class is required.
  9405. DefinedAnything = true;
  9406. MarkVirtualMembersReferenced(Loc, Class);
  9407. CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  9408. Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
  9409. // Optionally warn if we're emitting a weak vtable.
  9410. if (Class->getLinkage() == ExternalLinkage &&
  9411. Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
  9412. const FunctionDecl *KeyFunctionDef = 0;
  9413. if (!KeyFunction ||
  9414. (KeyFunction->hasBody(KeyFunctionDef) &&
  9415. KeyFunctionDef->isInlined()))
  9416. Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
  9417. TSK_ExplicitInstantiationDefinition
  9418. ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
  9419. << Class;
  9420. }
  9421. }
  9422. VTableUses.clear();
  9423. return DefinedAnything;
  9424. }
  9425. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  9426. const CXXRecordDecl *RD) {
  9427. for (CXXRecordDecl::method_iterator i = RD->method_begin(),
  9428. e = RD->method_end(); i != e; ++i) {
  9429. CXXMethodDecl *MD = *i;
  9430. // C++ [basic.def.odr]p2:
  9431. // [...] A virtual member function is used if it is not pure. [...]
  9432. if (MD->isVirtual() && !MD->isPure())
  9433. MarkFunctionReferenced(Loc, MD);
  9434. }
  9435. // Only classes that have virtual bases need a VTT.
  9436. if (RD->getNumVBases() == 0)
  9437. return;
  9438. for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
  9439. e = RD->bases_end(); i != e; ++i) {
  9440. const CXXRecordDecl *Base =
  9441. cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
  9442. if (Base->getNumVBases() == 0)
  9443. continue;
  9444. MarkVirtualMembersReferenced(Loc, Base);
  9445. }
  9446. }
  9447. /// SetIvarInitializers - This routine builds initialization ASTs for the
  9448. /// Objective-C implementation whose ivars need be initialized.
  9449. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  9450. if (!getLangOptions().CPlusPlus)
  9451. return;
  9452. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  9453. SmallVector<ObjCIvarDecl*, 8> ivars;
  9454. CollectIvarsToConstructOrDestruct(OID, ivars);
  9455. if (ivars.empty())
  9456. return;
  9457. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  9458. for (unsigned i = 0; i < ivars.size(); i++) {
  9459. FieldDecl *Field = ivars[i];
  9460. if (Field->isInvalidDecl())
  9461. continue;
  9462. CXXCtorInitializer *Member;
  9463. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  9464. InitializationKind InitKind =
  9465. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  9466. InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
  9467. ExprResult MemberInit =
  9468. InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
  9469. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  9470. // Note, MemberInit could actually come back empty if no initialization
  9471. // is required (e.g., because it would call a trivial default constructor)
  9472. if (!MemberInit.get() || MemberInit.isInvalid())
  9473. continue;
  9474. Member =
  9475. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  9476. SourceLocation(),
  9477. MemberInit.takeAs<Expr>(),
  9478. SourceLocation());
  9479. AllToInit.push_back(Member);
  9480. // Be sure that the destructor is accessible and is marked as referenced.
  9481. if (const RecordType *RecordTy
  9482. = Context.getBaseElementType(Field->getType())
  9483. ->getAs<RecordType>()) {
  9484. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  9485. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  9486. MarkFunctionReferenced(Field->getLocation(), Destructor);
  9487. CheckDestructorAccess(Field->getLocation(), Destructor,
  9488. PDiag(diag::err_access_dtor_ivar)
  9489. << Context.getBaseElementType(Field->getType()));
  9490. }
  9491. }
  9492. }
  9493. ObjCImplementation->setIvarInitializers(Context,
  9494. AllToInit.data(), AllToInit.size());
  9495. }
  9496. }
  9497. static
  9498. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  9499. llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
  9500. llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
  9501. llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
  9502. Sema &S) {
  9503. llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
  9504. CE = Current.end();
  9505. if (Ctor->isInvalidDecl())
  9506. return;
  9507. const FunctionDecl *FNTarget = 0;
  9508. CXXConstructorDecl *Target;
  9509. // We ignore the result here since if we don't have a body, Target will be
  9510. // null below.
  9511. (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
  9512. Target
  9513. = const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
  9514. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  9515. // Avoid dereferencing a null pointer here.
  9516. *TCanonical = Target ? Target->getCanonicalDecl() : 0;
  9517. if (!Current.insert(Canonical))
  9518. return;
  9519. // We know that beyond here, we aren't chaining into a cycle.
  9520. if (!Target || !Target->isDelegatingConstructor() ||
  9521. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  9522. for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
  9523. Valid.insert(*CI);
  9524. Current.clear();
  9525. // We've hit a cycle.
  9526. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  9527. Current.count(TCanonical)) {
  9528. // If we haven't diagnosed this cycle yet, do so now.
  9529. if (!Invalid.count(TCanonical)) {
  9530. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  9531. diag::warn_delegating_ctor_cycle)
  9532. << Ctor;
  9533. // Don't add a note for a function delegating directo to itself.
  9534. if (TCanonical != Canonical)
  9535. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  9536. CXXConstructorDecl *C = Target;
  9537. while (C->getCanonicalDecl() != Canonical) {
  9538. (void)C->getTargetConstructor()->hasBody(FNTarget);
  9539. assert(FNTarget && "Ctor cycle through bodiless function");
  9540. C
  9541. = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
  9542. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  9543. }
  9544. }
  9545. for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
  9546. Invalid.insert(*CI);
  9547. Current.clear();
  9548. } else {
  9549. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  9550. }
  9551. }
  9552. void Sema::CheckDelegatingCtorCycles() {
  9553. llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  9554. llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
  9555. CE = Current.end();
  9556. for (DelegatingCtorDeclsType::iterator
  9557. I = DelegatingCtorDecls.begin(ExternalSource),
  9558. E = DelegatingCtorDecls.end();
  9559. I != E; ++I) {
  9560. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  9561. }
  9562. for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
  9563. (*CI)->setInvalidDecl();
  9564. }
  9565. /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
  9566. Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
  9567. // Implicitly declared functions (e.g. copy constructors) are
  9568. // __host__ __device__
  9569. if (D->isImplicit())
  9570. return CFT_HostDevice;
  9571. if (D->hasAttr<CUDAGlobalAttr>())
  9572. return CFT_Global;
  9573. if (D->hasAttr<CUDADeviceAttr>()) {
  9574. if (D->hasAttr<CUDAHostAttr>())
  9575. return CFT_HostDevice;
  9576. else
  9577. return CFT_Device;
  9578. }
  9579. return CFT_Host;
  9580. }
  9581. bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
  9582. CUDAFunctionTarget CalleeTarget) {
  9583. // CUDA B.1.1 "The __device__ qualifier declares a function that is...
  9584. // Callable from the device only."
  9585. if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
  9586. return true;
  9587. // CUDA B.1.2 "The __global__ qualifier declares a function that is...
  9588. // Callable from the host only."
  9589. // CUDA B.1.3 "The __host__ qualifier declares a function that is...
  9590. // Callable from the host only."
  9591. if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
  9592. (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
  9593. return true;
  9594. if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
  9595. return true;
  9596. return false;
  9597. }