SemaDeclCXX.cpp 525 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840
  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/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/RecursiveASTVisitor.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/AST/TypeOrdering.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/LiteralSupport.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Sema/CXXFieldCollector.h"
  32. #include "clang/Sema/DeclSpec.h"
  33. #include "clang/Sema/Initialization.h"
  34. #include "clang/Sema/Lookup.h"
  35. #include "clang/Sema/ParsedTemplate.h"
  36. #include "clang/Sema/Scope.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "clang/Sema/Template.h"
  39. #include "llvm/ADT/STLExtras.h"
  40. #include "llvm/ADT/SmallString.h"
  41. #include <map>
  42. #include <set>
  43. #include "clang/Basic/Specifiers.h" // HLSL Change
  44. using namespace clang;
  45. //===----------------------------------------------------------------------===//
  46. // CheckDefaultArgumentVisitor
  47. //===----------------------------------------------------------------------===//
  48. namespace {
  49. /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
  50. /// the default argument of a parameter to determine whether it
  51. /// contains any ill-formed subexpressions. For example, this will
  52. /// diagnose the use of local variables or parameters within the
  53. /// default argument expression.
  54. class CheckDefaultArgumentVisitor
  55. : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
  56. Expr *DefaultArg;
  57. Sema *S;
  58. public:
  59. CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
  60. : DefaultArg(defarg), S(s) {}
  61. bool VisitExpr(Expr *Node);
  62. bool VisitDeclRefExpr(DeclRefExpr *DRE);
  63. bool VisitCXXThisExpr(CXXThisExpr *ThisE);
  64. bool VisitLambdaExpr(LambdaExpr *Lambda);
  65. bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
  66. };
  67. /// VisitExpr - Visit all of the children of this expression.
  68. bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
  69. bool IsInvalid = false;
  70. for (Stmt *SubStmt : Node->children())
  71. IsInvalid |= Visit(SubStmt);
  72. return IsInvalid;
  73. }
  74. /// VisitDeclRefExpr - Visit a reference to a declaration, to
  75. /// determine whether this declaration can be used in the default
  76. /// argument expression.
  77. bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
  78. NamedDecl *Decl = DRE->getDecl();
  79. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
  80. // C++ [dcl.fct.default]p9
  81. // Default arguments are evaluated each time the function is
  82. // called. The order of evaluation of function arguments is
  83. // unspecified. Consequently, parameters of a function shall not
  84. // be used in default argument expressions, even if they are not
  85. // evaluated. Parameters of a function declared before a default
  86. // argument expression are in scope and can hide namespace and
  87. // class member names.
  88. return S->Diag(DRE->getLocStart(),
  89. diag::err_param_default_argument_references_param)
  90. << Param->getDeclName() << DefaultArg->getSourceRange();
  91. } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
  92. // C++ [dcl.fct.default]p7
  93. // Local variables shall not be used in default argument
  94. // expressions.
  95. if (VDecl->isLocalVarDecl())
  96. return S->Diag(DRE->getLocStart(),
  97. diag::err_param_default_argument_references_local)
  98. << VDecl->getDeclName() << DefaultArg->getSourceRange();
  99. }
  100. return false;
  101. }
  102. /// VisitCXXThisExpr - Visit a C++ "this" expression.
  103. bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
  104. // C++ [dcl.fct.default]p8:
  105. // The keyword this shall not be used in a default argument of a
  106. // member function.
  107. return S->Diag(ThisE->getLocStart(),
  108. diag::err_param_default_argument_references_this)
  109. << ThisE->getSourceRange();
  110. }
  111. bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
  112. bool Invalid = false;
  113. for (PseudoObjectExpr::semantics_iterator
  114. i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
  115. Expr *E = *i;
  116. // Look through bindings.
  117. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  118. E = OVE->getSourceExpr();
  119. assert(E && "pseudo-object binding without source expression?");
  120. }
  121. Invalid |= Visit(E);
  122. }
  123. return Invalid;
  124. }
  125. bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
  126. // C++11 [expr.lambda.prim]p13:
  127. // A lambda-expression appearing in a default argument shall not
  128. // implicitly or explicitly capture any entity.
  129. if (Lambda->capture_begin() == Lambda->capture_end())
  130. return false;
  131. return S->Diag(Lambda->getLocStart(),
  132. diag::err_lambda_capture_default_arg);
  133. }
  134. }
  135. void
  136. Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
  137. const CXXMethodDecl *Method) {
  138. // If we have an MSAny spec already, don't bother.
  139. if (!Method || ComputedEST == EST_MSAny)
  140. return;
  141. const FunctionProtoType *Proto
  142. = Method->getType()->getAs<FunctionProtoType>();
  143. Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
  144. if (!Proto)
  145. return;
  146. ExceptionSpecificationType EST = Proto->getExceptionSpecType();
  147. // If this function can throw any exceptions, make a note of that.
  148. if (EST == EST_MSAny || EST == EST_None) {
  149. ClearExceptions();
  150. ComputedEST = EST;
  151. return;
  152. }
  153. // FIXME: If the call to this decl is using any of its default arguments, we
  154. // need to search them for potentially-throwing calls.
  155. // If this function has a basic noexcept, it doesn't affect the outcome.
  156. if (EST == EST_BasicNoexcept)
  157. return;
  158. // If we have a throw-all spec at this point, ignore the function.
  159. if (ComputedEST == EST_None)
  160. return;
  161. // If we're still at noexcept(true) and there's a nothrow() callee,
  162. // change to that specification.
  163. if (EST == EST_DynamicNone) {
  164. if (ComputedEST == EST_BasicNoexcept)
  165. ComputedEST = EST_DynamicNone;
  166. return;
  167. }
  168. // Check out noexcept specs.
  169. if (EST == EST_ComputedNoexcept) {
  170. FunctionProtoType::NoexceptResult NR =
  171. Proto->getNoexceptSpec(Self->Context);
  172. assert(NR != FunctionProtoType::NR_NoNoexcept &&
  173. "Must have noexcept result for EST_ComputedNoexcept.");
  174. assert(NR != FunctionProtoType::NR_Dependent &&
  175. "Should not generate implicit declarations for dependent cases, "
  176. "and don't know how to handle them anyway.");
  177. // noexcept(false) -> no spec on the new function
  178. if (NR == FunctionProtoType::NR_Throw) {
  179. ClearExceptions();
  180. ComputedEST = EST_None;
  181. }
  182. // noexcept(true) won't change anything either.
  183. return;
  184. }
  185. assert(EST == EST_Dynamic && "EST case not considered earlier.");
  186. assert(ComputedEST != EST_None &&
  187. "Shouldn't collect exceptions when throw-all is guaranteed.");
  188. ComputedEST = EST_Dynamic;
  189. // Record the exceptions in this function's exception specification.
  190. for (const auto &E : Proto->exceptions())
  191. if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
  192. Exceptions.push_back(E);
  193. }
  194. void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
  195. if (!E || ComputedEST == EST_MSAny)
  196. return;
  197. // FIXME:
  198. //
  199. // C++0x [except.spec]p14:
  200. // [An] implicit exception-specification specifies the type-id T if and
  201. // only if T is allowed by the exception-specification of a function directly
  202. // invoked by f's implicit definition; f shall allow all exceptions if any
  203. // function it directly invokes allows all exceptions, and f shall allow no
  204. // exceptions if every function it directly invokes allows no exceptions.
  205. //
  206. // Note in particular that if an implicit exception-specification is generated
  207. // for a function containing a throw-expression, that specification can still
  208. // be noexcept(true).
  209. //
  210. // Note also that 'directly invoked' is not defined in the standard, and there
  211. // is no indication that we should only consider potentially-evaluated calls.
  212. //
  213. // Ultimately we should implement the intent of the standard: the exception
  214. // specification should be the set of exceptions which can be thrown by the
  215. // implicit definition. For now, we assume that any non-nothrow expression can
  216. // throw any exception.
  217. if (Self->canThrow(E))
  218. ComputedEST = EST_None;
  219. }
  220. bool
  221. Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
  222. SourceLocation EqualLoc) {
  223. if (RequireCompleteType(Param->getLocation(), Param->getType(),
  224. diag::err_typecheck_decl_incomplete_type)) {
  225. Param->setInvalidDecl();
  226. return true;
  227. }
  228. // C++ [dcl.fct.default]p5
  229. // A default argument expression is implicitly converted (clause
  230. // 4) to the parameter type. The default argument expression has
  231. // the same semantic constraints as the initializer expression in
  232. // a declaration of a variable of the parameter type, using the
  233. // copy-initialization semantics (8.5).
  234. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  235. Param);
  236. InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
  237. EqualLoc);
  238. InitializationSequence InitSeq(*this, Entity, Kind, Arg);
  239. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
  240. if (Result.isInvalid())
  241. return true;
  242. Arg = Result.getAs<Expr>();
  243. CheckCompletedExpr(Arg, EqualLoc);
  244. Arg = MaybeCreateExprWithCleanups(Arg);
  245. // Okay: add the default argument to the parameter
  246. Param->setDefaultArg(Arg);
  247. // We have already instantiated this parameter; provide each of the
  248. // instantiations with the uninstantiated default argument.
  249. UnparsedDefaultArgInstantiationsMap::iterator InstPos
  250. = UnparsedDefaultArgInstantiations.find(Param);
  251. if (InstPos != UnparsedDefaultArgInstantiations.end()) {
  252. for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
  253. InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
  254. // We're done tracking this parameter's instantiations.
  255. UnparsedDefaultArgInstantiations.erase(InstPos);
  256. }
  257. return false;
  258. }
  259. /// ActOnParamDefaultArgument - Check whether the default argument
  260. /// provided for a function parameter is well-formed. If so, attach it
  261. /// to the parameter declaration.
  262. void
  263. Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
  264. Expr *DefaultArg) {
  265. if (!param || !DefaultArg)
  266. return;
  267. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  268. UnparsedDefaultArgLocs.erase(Param);
  269. // Default arguments are only permitted in C++
  270. if (!getLangOpts().CPlusPlus) {
  271. Diag(EqualLoc, diag::err_param_default_argument)
  272. << DefaultArg->getSourceRange();
  273. Param->setInvalidDecl();
  274. return;
  275. }
  276. // Check for unexpanded parameter packs.
  277. if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
  278. Param->setInvalidDecl();
  279. return;
  280. }
  281. // C++11 [dcl.fct.default]p3
  282. // A default argument expression [...] shall not be specified for a
  283. // parameter pack.
  284. if (Param->isParameterPack()) {
  285. Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
  286. << DefaultArg->getSourceRange();
  287. return;
  288. }
  289. // Check that the default argument is well-formed
  290. CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
  291. if (DefaultArgChecker.Visit(DefaultArg)) {
  292. Param->setInvalidDecl();
  293. return;
  294. }
  295. SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
  296. }
  297. /// ActOnParamUnparsedDefaultArgument - We've seen a default
  298. /// argument for a function parameter, but we can't parse it yet
  299. /// because we're inside a class definition. Note that this default
  300. /// argument will be parsed later.
  301. void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
  302. SourceLocation EqualLoc,
  303. SourceLocation ArgLoc) {
  304. if (!param)
  305. return;
  306. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  307. Param->setUnparsedDefaultArg();
  308. UnparsedDefaultArgLocs[Param] = ArgLoc;
  309. }
  310. /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
  311. /// the default argument for the parameter param failed.
  312. void Sema::ActOnParamDefaultArgumentError(Decl *param,
  313. SourceLocation EqualLoc) {
  314. if (!param)
  315. return;
  316. ParmVarDecl *Param = cast<ParmVarDecl>(param);
  317. Param->setInvalidDecl();
  318. UnparsedDefaultArgLocs.erase(Param);
  319. Param->setDefaultArg(new(Context)
  320. OpaqueValueExpr(EqualLoc,
  321. Param->getType().getNonReferenceType(),
  322. VK_RValue));
  323. }
  324. /// CheckExtraCXXDefaultArguments - Check for any extra default
  325. /// arguments in the declarator, which is not a function declaration
  326. /// or definition and therefore is not permitted to have default
  327. /// arguments. This routine should be invoked for every declarator
  328. /// that is not a function declaration or definition.
  329. void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
  330. // C++ [dcl.fct.default]p3
  331. // A default argument expression shall be specified only in the
  332. // parameter-declaration-clause of a function declaration or in a
  333. // template-parameter (14.1). It shall not be specified for a
  334. // parameter pack. If it is specified in a
  335. // parameter-declaration-clause, it shall not occur within a
  336. // declarator or abstract-declarator of a parameter-declaration.
  337. bool MightBeFunction = D.isFunctionDeclarationContext();
  338. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  339. DeclaratorChunk &chunk = D.getTypeObject(i);
  340. if (chunk.Kind == DeclaratorChunk::Function) {
  341. if (MightBeFunction) {
  342. // This is a function declaration. It can have default arguments, but
  343. // keep looking in case its return type is a function type with default
  344. // arguments.
  345. MightBeFunction = false;
  346. continue;
  347. }
  348. for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
  349. ++argIdx) {
  350. ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
  351. if (Param->hasUnparsedDefaultArg()) {
  352. CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
  353. SourceRange SR;
  354. if (Toks->size() > 1)
  355. SR = SourceRange((*Toks)[1].getLocation(),
  356. Toks->back().getLocation());
  357. else
  358. SR = UnparsedDefaultArgLocs[Param];
  359. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  360. << SR;
  361. delete Toks;
  362. chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
  363. } else if (Param->getDefaultArg()) {
  364. Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
  365. << Param->getDefaultArg()->getSourceRange();
  366. Param->setDefaultArg(nullptr);
  367. }
  368. }
  369. } else if (chunk.Kind != DeclaratorChunk::Paren) {
  370. MightBeFunction = false;
  371. }
  372. }
  373. }
  374. static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
  375. for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
  376. const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
  377. if (!PVD->hasDefaultArg())
  378. return false;
  379. if (!PVD->hasInheritedDefaultArg())
  380. return true;
  381. }
  382. return false;
  383. }
  384. /// MergeCXXFunctionDecl - Merge two declarations of the same C++
  385. /// function, once we already know that they have the same
  386. /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
  387. /// error, false otherwise.
  388. bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
  389. Scope *S) {
  390. bool Invalid = false;
  391. // The declaration context corresponding to the scope is the semantic
  392. // parent, unless this is a local function declaration, in which case
  393. // it is that surrounding function.
  394. DeclContext *ScopeDC = New->isLocalExternDecl()
  395. ? New->getLexicalDeclContext()
  396. : New->getDeclContext();
  397. // Find the previous declaration for the purpose of default arguments.
  398. FunctionDecl *PrevForDefaultArgs = Old;
  399. for (/**/; PrevForDefaultArgs;
  400. // Don't bother looking back past the latest decl if this is a local
  401. // extern declaration; nothing else could work.
  402. PrevForDefaultArgs = New->isLocalExternDecl()
  403. ? nullptr
  404. : PrevForDefaultArgs->getPreviousDecl()) {
  405. // Ignore hidden declarations.
  406. if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
  407. continue;
  408. if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
  409. !New->isCXXClassMember()) {
  410. // Ignore default arguments of old decl if they are not in
  411. // the same scope and this is not an out-of-line definition of
  412. // a member function.
  413. continue;
  414. }
  415. if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
  416. // If only one of these is a local function declaration, then they are
  417. // declared in different scopes, even though isDeclInScope may think
  418. // they're in the same scope. (If both are local, the scope check is
  419. // sufficent, and if neither is local, then they are in the same scope.)
  420. continue;
  421. }
  422. // We found our guy.
  423. break;
  424. }
  425. // C++ [dcl.fct.default]p4:
  426. // For non-template functions, default arguments can be added in
  427. // later declarations of a function in the same
  428. // scope. Declarations in different scopes have completely
  429. // distinct sets of default arguments. That is, declarations in
  430. // inner scopes do not acquire default arguments from
  431. // declarations in outer scopes, and vice versa. In a given
  432. // function declaration, all parameters subsequent to a
  433. // parameter with a default argument shall have default
  434. // arguments supplied in this or previous declarations. A
  435. // default argument shall not be redefined by a later
  436. // declaration (not even to the same value).
  437. //
  438. // C++ [dcl.fct.default]p6:
  439. // Except for member functions of class templates, the default arguments
  440. // in a member function definition that appears outside of the class
  441. // definition are added to the set of default arguments provided by the
  442. // member function declaration in the class definition.
  443. for (unsigned p = 0, NumParams = PrevForDefaultArgs
  444. ? PrevForDefaultArgs->getNumParams()
  445. : 0;
  446. p < NumParams; ++p) {
  447. ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
  448. ParmVarDecl *NewParam = New->getParamDecl(p);
  449. bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
  450. bool NewParamHasDfl = NewParam->hasDefaultArg();
  451. if (OldParamHasDfl && NewParamHasDfl) {
  452. unsigned DiagDefaultParamID =
  453. diag::err_param_default_argument_redefinition;
  454. // MSVC accepts that default parameters be redefined for member functions
  455. // of template class. The new default parameter's value is ignored.
  456. Invalid = true;
  457. if (getLangOpts().MicrosoftExt) {
  458. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
  459. if (MD && MD->getParent()->getDescribedClassTemplate()) {
  460. // Merge the old default argument into the new parameter.
  461. NewParam->setHasInheritedDefaultArg();
  462. if (OldParam->hasUninstantiatedDefaultArg())
  463. NewParam->setUninstantiatedDefaultArg(
  464. OldParam->getUninstantiatedDefaultArg());
  465. else
  466. NewParam->setDefaultArg(OldParam->getInit());
  467. DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
  468. Invalid = false;
  469. }
  470. }
  471. // FIXME: If we knew where the '=' was, we could easily provide a fix-it
  472. // hint here. Alternatively, we could walk the type-source information
  473. // for NewParam to find the last source location in the type... but it
  474. // isn't worth the effort right now. This is the kind of test case that
  475. // is hard to get right:
  476. // int f(int);
  477. // void g(int (*fp)(int) = f);
  478. // void g(int (*fp)(int) = &f);
  479. Diag(NewParam->getLocation(), DiagDefaultParamID)
  480. << NewParam->getDefaultArgRange();
  481. // Look for the function declaration where the default argument was
  482. // actually written, which may be a declaration prior to Old.
  483. for (auto Older = PrevForDefaultArgs;
  484. OldParam->hasInheritedDefaultArg(); /**/) {
  485. Older = Older->getPreviousDecl();
  486. OldParam = Older->getParamDecl(p);
  487. }
  488. Diag(OldParam->getLocation(), diag::note_previous_definition)
  489. << OldParam->getDefaultArgRange();
  490. } else if (OldParamHasDfl) {
  491. // Merge the old default argument into the new parameter.
  492. // It's important to use getInit() here; getDefaultArg()
  493. // strips off any top-level ExprWithCleanups.
  494. NewParam->setHasInheritedDefaultArg();
  495. if (OldParam->hasUnparsedDefaultArg())
  496. NewParam->setUnparsedDefaultArg();
  497. else if (OldParam->hasUninstantiatedDefaultArg())
  498. NewParam->setUninstantiatedDefaultArg(
  499. OldParam->getUninstantiatedDefaultArg());
  500. else
  501. NewParam->setDefaultArg(OldParam->getInit());
  502. } else if (NewParamHasDfl) {
  503. if (New->getDescribedFunctionTemplate()) {
  504. // Paragraph 4, quoted above, only applies to non-template functions.
  505. Diag(NewParam->getLocation(),
  506. diag::err_param_default_argument_template_redecl)
  507. << NewParam->getDefaultArgRange();
  508. Diag(PrevForDefaultArgs->getLocation(),
  509. diag::note_template_prev_declaration)
  510. << false;
  511. } else if (New->getTemplateSpecializationKind()
  512. != TSK_ImplicitInstantiation &&
  513. New->getTemplateSpecializationKind() != TSK_Undeclared) {
  514. // C++ [temp.expr.spec]p21:
  515. // Default function arguments shall not be specified in a declaration
  516. // or a definition for one of the following explicit specializations:
  517. // - the explicit specialization of a function template;
  518. // - the explicit specialization of a member function template;
  519. // - the explicit specialization of a member function of a class
  520. // template where the class template specialization to which the
  521. // member function specialization belongs is implicitly
  522. // instantiated.
  523. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
  524. << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
  525. << New->getDeclName()
  526. << NewParam->getDefaultArgRange();
  527. } else if (New->getDeclContext()->isDependentContext()) {
  528. // C++ [dcl.fct.default]p6 (DR217):
  529. // Default arguments for a member function of a class template shall
  530. // be specified on the initial declaration of the member function
  531. // within the class template.
  532. //
  533. // Reading the tea leaves a bit in DR217 and its reference to DR205
  534. // leads me to the conclusion that one cannot add default function
  535. // arguments for an out-of-line definition of a member function of a
  536. // dependent type.
  537. int WhichKind = 2;
  538. if (CXXRecordDecl *Record
  539. = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
  540. if (Record->getDescribedClassTemplate())
  541. WhichKind = 0;
  542. else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
  543. WhichKind = 1;
  544. else
  545. WhichKind = 2;
  546. }
  547. Diag(NewParam->getLocation(),
  548. diag::err_param_default_argument_member_template_redecl)
  549. << WhichKind
  550. << NewParam->getDefaultArgRange();
  551. }
  552. }
  553. }
  554. // DR1344: If a default argument is added outside a class definition and that
  555. // default argument makes the function a special member function, the program
  556. // is ill-formed. This can only happen for constructors.
  557. if (isa<CXXConstructorDecl>(New) &&
  558. New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
  559. CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
  560. OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
  561. if (NewSM != OldSM) {
  562. ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
  563. assert(NewParam->hasDefaultArg());
  564. Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
  565. << NewParam->getDefaultArgRange() << NewSM;
  566. Diag(Old->getLocation(), diag::note_previous_declaration);
  567. }
  568. }
  569. const FunctionDecl *Def;
  570. // C++11 [dcl.constexpr]p1: If any declaration of a function or function
  571. // template has a constexpr specifier then all its declarations shall
  572. // contain the constexpr specifier.
  573. if (New->isConstexpr() != Old->isConstexpr()) {
  574. Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
  575. << New << New->isConstexpr();
  576. Diag(Old->getLocation(), diag::note_previous_declaration);
  577. Invalid = true;
  578. } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
  579. Old->isDefined(Def)) {
  580. // C++11 [dcl.fcn.spec]p4:
  581. // If the definition of a function appears in a translation unit before its
  582. // first declaration as inline, the program is ill-formed.
  583. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  584. Diag(Def->getLocation(), diag::note_previous_definition);
  585. Invalid = true;
  586. }
  587. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
  588. // argument expression, that declaration shall be a definition and shall be
  589. // the only declaration of the function or function template in the
  590. // translation unit.
  591. if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
  592. functionDeclHasDefaultArgument(Old)) {
  593. Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  594. Diag(Old->getLocation(), diag::note_previous_declaration);
  595. Invalid = true;
  596. }
  597. if (CheckEquivalentExceptionSpec(Old, New))
  598. Invalid = true;
  599. return Invalid;
  600. }
  601. /// \brief Merge the exception specifications of two variable declarations.
  602. ///
  603. /// This is called when there's a redeclaration of a VarDecl. The function
  604. /// checks if the redeclaration might have an exception specification and
  605. /// validates compatibility and merges the specs if necessary.
  606. void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
  607. // Shortcut if exceptions are disabled.
  608. if (!getLangOpts().CXXExceptions)
  609. return;
  610. assert(Context.hasSameType(New->getType(), Old->getType()) &&
  611. "Should only be called if types are otherwise the same.");
  612. QualType NewType = New->getType();
  613. QualType OldType = Old->getType();
  614. // We're only interested in pointers and references to functions, as well
  615. // as pointers to member functions.
  616. if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
  617. NewType = R->getPointeeType();
  618. OldType = OldType->getAs<ReferenceType>()->getPointeeType();
  619. } else if (const PointerType *P = NewType->getAs<PointerType>()) {
  620. NewType = P->getPointeeType();
  621. OldType = OldType->getAs<PointerType>()->getPointeeType();
  622. } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
  623. NewType = M->getPointeeType();
  624. OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
  625. }
  626. if (!NewType->isFunctionProtoType())
  627. return;
  628. // There's lots of special cases for functions. For function pointers, system
  629. // libraries are hopefully not as broken so that we don't need these
  630. // workarounds.
  631. if (CheckEquivalentExceptionSpec(
  632. OldType->getAs<FunctionProtoType>(), Old->getLocation(),
  633. NewType->getAs<FunctionProtoType>(), New->getLocation())) {
  634. New->setInvalidDecl();
  635. }
  636. }
  637. /// CheckCXXDefaultArguments - Verify that the default arguments for a
  638. /// function declaration are well-formed according to C++
  639. /// [dcl.fct.default].
  640. void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
  641. unsigned NumParams = FD->getNumParams();
  642. unsigned p;
  643. // Find first parameter with a default argument
  644. for (p = 0; p < NumParams; ++p) {
  645. ParmVarDecl *Param = FD->getParamDecl(p);
  646. if (Param->hasDefaultArg())
  647. break;
  648. }
  649. // C++11 [dcl.fct.default]p4:
  650. // In a given function declaration, each parameter subsequent to a parameter
  651. // with a default argument shall have a default argument supplied in this or
  652. // a previous declaration or shall be a function parameter pack. A default
  653. // argument shall not be redefined by a later declaration (not even to the
  654. // same value).
  655. unsigned LastMissingDefaultArg = 0;
  656. for (; p < NumParams; ++p) {
  657. ParmVarDecl *Param = FD->getParamDecl(p);
  658. if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
  659. if (Param->isInvalidDecl())
  660. /* We already complained about this parameter. */;
  661. else if (Param->getIdentifier())
  662. Diag(Param->getLocation(),
  663. diag::err_param_default_argument_missing_name)
  664. << Param->getIdentifier();
  665. else
  666. Diag(Param->getLocation(),
  667. diag::err_param_default_argument_missing);
  668. LastMissingDefaultArg = p;
  669. }
  670. }
  671. if (LastMissingDefaultArg > 0) {
  672. // Some default arguments were missing. Clear out all of the
  673. // default arguments up to (and including) the last missing
  674. // default argument, so that we leave the function parameters
  675. // in a semantically valid state.
  676. for (p = 0; p <= LastMissingDefaultArg; ++p) {
  677. ParmVarDecl *Param = FD->getParamDecl(p);
  678. if (Param->hasDefaultArg()) {
  679. Param->setDefaultArg(nullptr);
  680. }
  681. }
  682. }
  683. }
  684. // CheckConstexprParameterTypes - Check whether a function's parameter types
  685. // are all literal types. If so, return true. If not, produce a suitable
  686. // diagnostic and return false.
  687. static bool CheckConstexprParameterTypes(Sema &SemaRef,
  688. const FunctionDecl *FD) {
  689. unsigned ArgIndex = 0;
  690. const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
  691. for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
  692. e = FT->param_type_end();
  693. i != e; ++i, ++ArgIndex) {
  694. const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
  695. SourceLocation ParamLoc = PD->getLocation();
  696. if (!(*i)->isDependentType() &&
  697. SemaRef.RequireLiteralType(ParamLoc, *i,
  698. diag::err_constexpr_non_literal_param,
  699. ArgIndex+1, PD->getSourceRange(),
  700. isa<CXXConstructorDecl>(FD)))
  701. return false;
  702. }
  703. return true;
  704. }
  705. /// \brief Get diagnostic %select index for tag kind for
  706. /// record diagnostic message.
  707. /// WARNING: Indexes apply to particular diagnostics only!
  708. ///
  709. /// \returns diagnostic %select index.
  710. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
  711. switch (Tag) {
  712. case TTK_Struct: return 0;
  713. case TTK_Interface: return 1;
  714. case TTK_Class: return 2;
  715. default: llvm_unreachable("Invalid tag kind for record diagnostic!");
  716. }
  717. }
  718. // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
  719. // the requirements of a constexpr function definition or a constexpr
  720. // constructor definition. If so, return true. If not, produce appropriate
  721. // diagnostics and return false.
  722. //
  723. // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
  724. bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
  725. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  726. if (MD && MD->isInstance()) {
  727. // C++11 [dcl.constexpr]p4:
  728. // The definition of a constexpr constructor shall satisfy the following
  729. // constraints:
  730. // - the class shall not have any virtual base classes;
  731. const CXXRecordDecl *RD = MD->getParent();
  732. if (RD->getNumVBases()) {
  733. Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
  734. << isa<CXXConstructorDecl>(NewFD)
  735. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  736. for (const auto &I : RD->vbases())
  737. Diag(I.getLocStart(),
  738. diag::note_constexpr_virtual_base_here) << I.getSourceRange();
  739. return false;
  740. }
  741. }
  742. if (!isa<CXXConstructorDecl>(NewFD)) {
  743. // C++11 [dcl.constexpr]p3:
  744. // The definition of a constexpr function shall satisfy the following
  745. // constraints:
  746. // - it shall not be virtual;
  747. const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
  748. if (Method && Method->isVirtual()) {
  749. Method = Method->getCanonicalDecl();
  750. Diag(Method->getLocation(), diag::err_constexpr_virtual);
  751. // If it's not obvious why this function is virtual, find an overridden
  752. // function which uses the 'virtual' keyword.
  753. const CXXMethodDecl *WrittenVirtual = Method;
  754. while (!WrittenVirtual->isVirtualAsWritten())
  755. WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
  756. if (WrittenVirtual != Method)
  757. Diag(WrittenVirtual->getLocation(),
  758. diag::note_overridden_virtual_function);
  759. return false;
  760. }
  761. // - its return type shall be a literal type;
  762. QualType RT = NewFD->getReturnType();
  763. if (!RT->isDependentType() &&
  764. RequireLiteralType(NewFD->getLocation(), RT,
  765. diag::err_constexpr_non_literal_return))
  766. return false;
  767. }
  768. // - each of its parameter types shall be a literal type;
  769. if (!CheckConstexprParameterTypes(*this, NewFD))
  770. return false;
  771. return true;
  772. }
  773. /// Check the given declaration statement is legal within a constexpr function
  774. /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
  775. ///
  776. /// \return true if the body is OK (maybe only as an extension), false if we
  777. /// have diagnosed a problem.
  778. static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
  779. DeclStmt *DS, SourceLocation &Cxx1yLoc) {
  780. // C++11 [dcl.constexpr]p3 and p4:
  781. // The definition of a constexpr function(p3) or constructor(p4) [...] shall
  782. // contain only
  783. for (const auto *DclIt : DS->decls()) {
  784. switch (DclIt->getKind()) {
  785. case Decl::StaticAssert:
  786. case Decl::Using:
  787. case Decl::UsingShadow:
  788. case Decl::UsingDirective:
  789. case Decl::UnresolvedUsingTypename:
  790. case Decl::UnresolvedUsingValue:
  791. // - static_assert-declarations
  792. // - using-declarations,
  793. // - using-directives,
  794. continue;
  795. case Decl::Typedef:
  796. case Decl::TypeAlias: {
  797. // - typedef declarations and alias-declarations that do not define
  798. // classes or enumerations,
  799. const auto *TN = cast<TypedefNameDecl>(DclIt);
  800. if (TN->getUnderlyingType()->isVariablyModifiedType()) {
  801. // Don't allow variably-modified types in constexpr functions.
  802. TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
  803. SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
  804. << TL.getSourceRange() << TL.getType()
  805. << isa<CXXConstructorDecl>(Dcl);
  806. return false;
  807. }
  808. continue;
  809. }
  810. case Decl::Enum:
  811. case Decl::CXXRecord:
  812. // C++1y allows types to be defined, not just declared.
  813. if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
  814. SemaRef.Diag(DS->getLocStart(),
  815. SemaRef.getLangOpts().CPlusPlus14
  816. ? diag::warn_cxx11_compat_constexpr_type_definition
  817. : diag::ext_constexpr_type_definition)
  818. << isa<CXXConstructorDecl>(Dcl);
  819. continue;
  820. case Decl::EnumConstant:
  821. case Decl::IndirectField:
  822. case Decl::ParmVar:
  823. // These can only appear with other declarations which are banned in
  824. // C++11 and permitted in C++1y, so ignore them.
  825. continue;
  826. case Decl::Var: {
  827. // C++1y [dcl.constexpr]p3 allows anything except:
  828. // a definition of a variable of non-literal type or of static or
  829. // thread storage duration or for which no initialization is performed.
  830. const auto *VD = cast<VarDecl>(DclIt);
  831. if (VD->isThisDeclarationADefinition()) {
  832. if (VD->isStaticLocal()) {
  833. SemaRef.Diag(VD->getLocation(),
  834. diag::err_constexpr_local_var_static)
  835. << isa<CXXConstructorDecl>(Dcl)
  836. << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
  837. return false;
  838. }
  839. if (!VD->getType()->isDependentType() &&
  840. SemaRef.RequireLiteralType(
  841. VD->getLocation(), VD->getType(),
  842. diag::err_constexpr_local_var_non_literal_type,
  843. isa<CXXConstructorDecl>(Dcl)))
  844. return false;
  845. if (!VD->getType()->isDependentType() &&
  846. !VD->hasInit() && !VD->isCXXForRangeDecl()) {
  847. SemaRef.Diag(VD->getLocation(),
  848. diag::err_constexpr_local_var_no_init)
  849. << isa<CXXConstructorDecl>(Dcl);
  850. return false;
  851. }
  852. }
  853. SemaRef.Diag(VD->getLocation(),
  854. SemaRef.getLangOpts().CPlusPlus14
  855. ? diag::warn_cxx11_compat_constexpr_local_var
  856. : diag::ext_constexpr_local_var)
  857. << isa<CXXConstructorDecl>(Dcl);
  858. continue;
  859. }
  860. case Decl::NamespaceAlias:
  861. case Decl::Function:
  862. // These are disallowed in C++11 and permitted in C++1y. Allow them
  863. // everywhere as an extension.
  864. if (!Cxx1yLoc.isValid())
  865. Cxx1yLoc = DS->getLocStart();
  866. continue;
  867. default:
  868. SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  869. << isa<CXXConstructorDecl>(Dcl);
  870. return false;
  871. }
  872. }
  873. return true;
  874. }
  875. /// Check that the given field is initialized within a constexpr constructor.
  876. ///
  877. /// \param Dcl The constexpr constructor being checked.
  878. /// \param Field The field being checked. This may be a member of an anonymous
  879. /// struct or union nested within the class being checked.
  880. /// \param Inits All declarations, including anonymous struct/union members and
  881. /// indirect members, for which any initialization was provided.
  882. /// \param Diagnosed Set to true if an error is produced.
  883. static void CheckConstexprCtorInitializer(Sema &SemaRef,
  884. const FunctionDecl *Dcl,
  885. FieldDecl *Field,
  886. llvm::SmallSet<Decl*, 16> &Inits,
  887. bool &Diagnosed) {
  888. if (Field->isInvalidDecl())
  889. return;
  890. if (Field->isUnnamedBitfield())
  891. return;
  892. // Anonymous unions with no variant members and empty anonymous structs do not
  893. // need to be explicitly initialized. FIXME: Anonymous structs that contain no
  894. // indirect fields don't need initializing.
  895. if (Field->isAnonymousStructOrUnion() &&
  896. (Field->getType()->isUnionType()
  897. ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
  898. : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
  899. return;
  900. if (!Inits.count(Field)) {
  901. if (!Diagnosed) {
  902. SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
  903. Diagnosed = true;
  904. }
  905. SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
  906. } else if (Field->isAnonymousStructOrUnion()) {
  907. const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
  908. for (auto *I : RD->fields())
  909. // If an anonymous union contains an anonymous struct of which any member
  910. // is initialized, all members must be initialized.
  911. if (!RD->isUnion() || Inits.count(I))
  912. CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
  913. }
  914. }
  915. /// Check the provided statement is allowed in a constexpr function
  916. /// definition.
  917. static bool
  918. CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
  919. SmallVectorImpl<SourceLocation> &ReturnStmts,
  920. SourceLocation &Cxx1yLoc) {
  921. // - its function-body shall be [...] a compound-statement that contains only
  922. switch (S->getStmtClass()) {
  923. case Stmt::NullStmtClass:
  924. // - null statements,
  925. return true;
  926. case Stmt::DeclStmtClass:
  927. // - static_assert-declarations
  928. // - using-declarations,
  929. // - using-directives,
  930. // - typedef declarations and alias-declarations that do not define
  931. // classes or enumerations,
  932. if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
  933. return false;
  934. return true;
  935. case Stmt::ReturnStmtClass:
  936. // - and exactly one return statement;
  937. if (isa<CXXConstructorDecl>(Dcl)) {
  938. // C++1y allows return statements in constexpr constructors.
  939. if (!Cxx1yLoc.isValid())
  940. Cxx1yLoc = S->getLocStart();
  941. return true;
  942. }
  943. ReturnStmts.push_back(S->getLocStart());
  944. return true;
  945. case Stmt::CompoundStmtClass: {
  946. // C++1y allows compound-statements.
  947. if (!Cxx1yLoc.isValid())
  948. Cxx1yLoc = S->getLocStart();
  949. CompoundStmt *CompStmt = cast<CompoundStmt>(S);
  950. for (auto *BodyIt : CompStmt->body()) {
  951. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
  952. Cxx1yLoc))
  953. return false;
  954. }
  955. return true;
  956. }
  957. case Stmt::AttributedStmtClass:
  958. if (!Cxx1yLoc.isValid())
  959. Cxx1yLoc = S->getLocStart();
  960. return true;
  961. case Stmt::IfStmtClass: {
  962. // C++1y allows if-statements.
  963. if (!Cxx1yLoc.isValid())
  964. Cxx1yLoc = S->getLocStart();
  965. IfStmt *If = cast<IfStmt>(S);
  966. if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
  967. Cxx1yLoc))
  968. return false;
  969. if (If->getElse() &&
  970. !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
  971. Cxx1yLoc))
  972. return false;
  973. return true;
  974. }
  975. case Stmt::WhileStmtClass:
  976. case Stmt::DoStmtClass:
  977. case Stmt::ForStmtClass:
  978. case Stmt::CXXForRangeStmtClass:
  979. case Stmt::ContinueStmtClass:
  980. // C++1y allows all of these. We don't allow them as extensions in C++11,
  981. // because they don't make sense without variable mutation.
  982. if (!SemaRef.getLangOpts().CPlusPlus14)
  983. break;
  984. if (!Cxx1yLoc.isValid())
  985. Cxx1yLoc = S->getLocStart();
  986. for (Stmt *SubStmt : S->children())
  987. if (SubStmt &&
  988. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  989. Cxx1yLoc))
  990. return false;
  991. return true;
  992. case Stmt::SwitchStmtClass:
  993. case Stmt::CaseStmtClass:
  994. case Stmt::DefaultStmtClass:
  995. case Stmt::BreakStmtClass:
  996. // C++1y allows switch-statements, and since they don't need variable
  997. // mutation, we can reasonably allow them in C++11 as an extension.
  998. if (!Cxx1yLoc.isValid())
  999. Cxx1yLoc = S->getLocStart();
  1000. for (Stmt *SubStmt : S->children())
  1001. if (SubStmt &&
  1002. !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
  1003. Cxx1yLoc))
  1004. return false;
  1005. return true;
  1006. default:
  1007. if (!isa<Expr>(S))
  1008. break;
  1009. // C++1y allows expression-statements.
  1010. if (!Cxx1yLoc.isValid())
  1011. Cxx1yLoc = S->getLocStart();
  1012. return true;
  1013. }
  1014. SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
  1015. << isa<CXXConstructorDecl>(Dcl);
  1016. return false;
  1017. }
  1018. /// Check the body for the given constexpr function declaration only contains
  1019. /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
  1020. ///
  1021. /// \return true if the body is OK, false if we have diagnosed a problem.
  1022. bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
  1023. if (isa<CXXTryStmt>(Body)) {
  1024. // C++11 [dcl.constexpr]p3:
  1025. // The definition of a constexpr function shall satisfy the following
  1026. // constraints: [...]
  1027. // - its function-body shall be = delete, = default, or a
  1028. // compound-statement
  1029. //
  1030. // C++11 [dcl.constexpr]p4:
  1031. // In the definition of a constexpr constructor, [...]
  1032. // - its function-body shall not be a function-try-block;
  1033. Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
  1034. << isa<CXXConstructorDecl>(Dcl);
  1035. return false;
  1036. }
  1037. SmallVector<SourceLocation, 4> ReturnStmts;
  1038. // - its function-body shall be [...] a compound-statement that contains only
  1039. // [... list of cases ...]
  1040. CompoundStmt *CompBody = cast<CompoundStmt>(Body);
  1041. SourceLocation Cxx1yLoc;
  1042. for (auto *BodyIt : CompBody->body()) {
  1043. if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
  1044. return false;
  1045. }
  1046. if (Cxx1yLoc.isValid())
  1047. Diag(Cxx1yLoc,
  1048. getLangOpts().CPlusPlus14
  1049. ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
  1050. : diag::ext_constexpr_body_invalid_stmt)
  1051. << isa<CXXConstructorDecl>(Dcl);
  1052. if (const CXXConstructorDecl *Constructor
  1053. = dyn_cast<CXXConstructorDecl>(Dcl)) {
  1054. const CXXRecordDecl *RD = Constructor->getParent();
  1055. // DR1359:
  1056. // - every non-variant non-static data member and base class sub-object
  1057. // shall be initialized;
  1058. // DR1460:
  1059. // - if the class is a union having variant members, exactly one of them
  1060. // shall be initialized;
  1061. if (RD->isUnion()) {
  1062. if (Constructor->getNumCtorInitializers() == 0 &&
  1063. RD->hasVariantMembers()) {
  1064. Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
  1065. return false;
  1066. }
  1067. } else if (!Constructor->isDependentContext() &&
  1068. !Constructor->isDelegatingConstructor()) {
  1069. assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
  1070. // Skip detailed checking if we have enough initializers, and we would
  1071. // allow at most one initializer per member.
  1072. bool AnyAnonStructUnionMembers = false;
  1073. unsigned Fields = 0;
  1074. for (CXXRecordDecl::field_iterator I = RD->field_begin(),
  1075. E = RD->field_end(); I != E; ++I, ++Fields) {
  1076. if (I->isAnonymousStructOrUnion()) {
  1077. AnyAnonStructUnionMembers = true;
  1078. break;
  1079. }
  1080. }
  1081. // DR1460:
  1082. // - if the class is a union-like class, but is not a union, for each of
  1083. // its anonymous union members having variant members, exactly one of
  1084. // them shall be initialized;
  1085. if (AnyAnonStructUnionMembers ||
  1086. Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
  1087. // Check initialization of non-static data members. Base classes are
  1088. // always initialized so do not need to be checked. Dependent bases
  1089. // might not have initializers in the member initializer list.
  1090. llvm::SmallSet<Decl*, 16> Inits;
  1091. for (const auto *I: Constructor->inits()) {
  1092. if (FieldDecl *FD = I->getMember())
  1093. Inits.insert(FD);
  1094. else if (IndirectFieldDecl *ID = I->getIndirectMember())
  1095. Inits.insert(ID->chain_begin(), ID->chain_end());
  1096. }
  1097. bool Diagnosed = false;
  1098. for (auto *I : RD->fields())
  1099. CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
  1100. if (Diagnosed)
  1101. return false;
  1102. }
  1103. }
  1104. } else {
  1105. if (ReturnStmts.empty()) {
  1106. // C++1y doesn't require constexpr functions to contain a 'return'
  1107. // statement. We still do, unless the return type might be void, because
  1108. // otherwise if there's no return statement, the function cannot
  1109. // be used in a core constant expression.
  1110. bool OK = getLangOpts().CPlusPlus14 &&
  1111. (Dcl->getReturnType()->isVoidType() ||
  1112. Dcl->getReturnType()->isDependentType());
  1113. Diag(Dcl->getLocation(),
  1114. OK ? diag::warn_cxx11_compat_constexpr_body_no_return
  1115. : diag::err_constexpr_body_no_return);
  1116. return OK;
  1117. }
  1118. if (ReturnStmts.size() > 1) {
  1119. Diag(ReturnStmts.back(),
  1120. getLangOpts().CPlusPlus14
  1121. ? diag::warn_cxx11_compat_constexpr_body_multiple_return
  1122. : diag::ext_constexpr_body_multiple_return);
  1123. for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
  1124. Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
  1125. }
  1126. }
  1127. // C++11 [dcl.constexpr]p5:
  1128. // if no function argument values exist such that the function invocation
  1129. // substitution would produce a constant expression, the program is
  1130. // ill-formed; no diagnostic required.
  1131. // C++11 [dcl.constexpr]p3:
  1132. // - every constructor call and implicit conversion used in initializing the
  1133. // return value shall be one of those allowed in a constant expression.
  1134. // C++11 [dcl.constexpr]p4:
  1135. // - every constructor involved in initializing non-static data members and
  1136. // base class sub-objects shall be a constexpr constructor.
  1137. SmallVector<PartialDiagnosticAt, 8> Diags;
  1138. if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
  1139. Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
  1140. << isa<CXXConstructorDecl>(Dcl);
  1141. for (size_t I = 0, N = Diags.size(); I != N; ++I)
  1142. Diag(Diags[I].first, Diags[I].second);
  1143. // Don't return false here: we allow this for compatibility in
  1144. // system headers.
  1145. }
  1146. return true;
  1147. }
  1148. /// isCurrentClassName - Determine whether the identifier II is the
  1149. /// name of the class type currently being defined. In the case of
  1150. /// nested classes, this will only return true if II is the name of
  1151. /// the innermost class.
  1152. bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
  1153. const CXXScopeSpec *SS) {
  1154. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1155. CXXRecordDecl *CurDecl;
  1156. if (SS && SS->isSet() && !SS->isInvalid()) {
  1157. DeclContext *DC = computeDeclContext(*SS, true);
  1158. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1159. } else
  1160. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1161. if (CurDecl && CurDecl->getIdentifier())
  1162. return &II == CurDecl->getIdentifier();
  1163. return false;
  1164. }
  1165. /// \brief Determine whether the identifier II is a typo for the name of
  1166. /// the class type currently being defined. If so, update it to the identifier
  1167. /// that should have been used.
  1168. bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
  1169. assert(getLangOpts().CPlusPlus && "No class names in C!");
  1170. if (!getLangOpts().SpellChecking)
  1171. return false;
  1172. CXXRecordDecl *CurDecl;
  1173. if (SS && SS->isSet() && !SS->isInvalid()) {
  1174. DeclContext *DC = computeDeclContext(*SS, true);
  1175. CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
  1176. } else
  1177. CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
  1178. if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
  1179. 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
  1180. < II->getLength()) {
  1181. II = CurDecl->getIdentifier();
  1182. return true;
  1183. }
  1184. return false;
  1185. }
  1186. /// \brief Determine whether the given class is a base class of the given
  1187. /// class, including looking at dependent bases.
  1188. static bool findCircularInheritance(const CXXRecordDecl *Class,
  1189. const CXXRecordDecl *Current) {
  1190. SmallVector<const CXXRecordDecl*, 8> Queue;
  1191. Class = Class->getCanonicalDecl();
  1192. while (true) {
  1193. for (const auto &I : Current->bases()) {
  1194. CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
  1195. if (!Base)
  1196. continue;
  1197. Base = Base->getDefinition();
  1198. if (!Base)
  1199. continue;
  1200. if (Base->getCanonicalDecl() == Class)
  1201. return true;
  1202. Queue.push_back(Base);
  1203. }
  1204. if (Queue.empty())
  1205. return false;
  1206. Current = Queue.pop_back_val();
  1207. }
  1208. return false;
  1209. }
  1210. /// \brief Check the validity of a C++ base class specifier.
  1211. ///
  1212. /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
  1213. /// and returns NULL otherwise.
  1214. CXXBaseSpecifier *
  1215. Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
  1216. SourceRange SpecifierRange,
  1217. bool Virtual, AccessSpecifier Access,
  1218. TypeSourceInfo *TInfo,
  1219. SourceLocation EllipsisLoc) {
  1220. QualType BaseType = TInfo->getType();
  1221. // C++ [class.union]p1:
  1222. // A union shall not have base classes.
  1223. if (Class->isUnion()) {
  1224. Diag(Class->getLocation(), diag::err_base_clause_on_union)
  1225. << SpecifierRange;
  1226. return nullptr;
  1227. }
  1228. if (EllipsisLoc.isValid() &&
  1229. !TInfo->getType()->containsUnexpandedParameterPack()) {
  1230. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  1231. << TInfo->getTypeLoc().getSourceRange();
  1232. EllipsisLoc = SourceLocation();
  1233. }
  1234. SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
  1235. if (BaseType->isDependentType()) {
  1236. // Make sure that we don't have circular inheritance among our dependent
  1237. // bases. For non-dependent bases, the check for completeness below handles
  1238. // this.
  1239. if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
  1240. if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
  1241. ((BaseDecl = BaseDecl->getDefinition()) &&
  1242. findCircularInheritance(Class, BaseDecl))) {
  1243. Diag(BaseLoc, diag::err_circular_inheritance)
  1244. << BaseType << Context.getTypeDeclType(Class);
  1245. if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
  1246. Diag(BaseDecl->getLocation(), diag::note_previous_decl)
  1247. << BaseType;
  1248. return nullptr;
  1249. }
  1250. }
  1251. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1252. Class->getTagKind() == TTK_Class,
  1253. Access, TInfo, EllipsisLoc);
  1254. }
  1255. // Base specifiers must be record types.
  1256. if (!BaseType->isRecordType()) {
  1257. Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
  1258. return nullptr;
  1259. }
  1260. // C++ [class.union]p1:
  1261. // A union shall not be used as a base class.
  1262. if (BaseType->isUnionType()) {
  1263. Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
  1264. return nullptr;
  1265. }
  1266. // For the MS ABI, propagate DLL attributes to base class templates.
  1267. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1268. if (Attr *ClassAttr = getDLLAttr(Class)) {
  1269. if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  1270. BaseType->getAsCXXRecordDecl())) {
  1271. propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
  1272. BaseLoc);
  1273. }
  1274. }
  1275. }
  1276. // C++ [class.derived]p2:
  1277. // The class-name in a base-specifier shall not be an incompletely
  1278. // defined class.
  1279. if (RequireCompleteType(BaseLoc, BaseType,
  1280. diag::err_incomplete_base_class, SpecifierRange)) {
  1281. Class->setInvalidDecl();
  1282. return nullptr;
  1283. }
  1284. // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
  1285. RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
  1286. assert(BaseDecl && "Record type has no declaration");
  1287. BaseDecl = BaseDecl->getDefinition();
  1288. assert(BaseDecl && "Base type is not incomplete, but has no definition");
  1289. CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
  1290. assert(CXXBaseDecl && "Base type is not a C++ type");
  1291. // A class which contains a flexible array member is not suitable for use as a
  1292. // base class:
  1293. // - If the layout determines that a base comes before another base,
  1294. // the flexible array member would index into the subsequent base.
  1295. // - If the layout determines that base comes before the derived class,
  1296. // the flexible array member would index into the derived class.
  1297. if (CXXBaseDecl->hasFlexibleArrayMember()) {
  1298. Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
  1299. << CXXBaseDecl->getDeclName();
  1300. return nullptr;
  1301. }
  1302. // C++ [class]p3:
  1303. // If a class is marked final and it appears as a base-type-specifier in
  1304. // base-clause, the program is ill-formed.
  1305. if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
  1306. Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
  1307. << CXXBaseDecl->getDeclName()
  1308. << FA->isSpelledAsSealed();
  1309. Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
  1310. << CXXBaseDecl->getDeclName() << FA->getRange();
  1311. return nullptr;
  1312. }
  1313. if (BaseDecl->isInvalidDecl())
  1314. Class->setInvalidDecl();
  1315. // Create the base specifier.
  1316. return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
  1317. Class->getTagKind() == TTK_Class,
  1318. Access, TInfo, EllipsisLoc);
  1319. }
  1320. /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
  1321. /// one entry in the base class list of a class specifier, for
  1322. /// example:
  1323. /// class foo : public bar, virtual private baz {
  1324. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  1325. BaseResult
  1326. Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
  1327. ParsedAttributes &Attributes,
  1328. bool Virtual, AccessSpecifier Access,
  1329. ParsedType basetype, SourceLocation BaseLoc,
  1330. SourceLocation EllipsisLoc) {
  1331. if (!classdecl)
  1332. return true;
  1333. AdjustDeclIfTemplate(classdecl);
  1334. CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
  1335. if (!Class)
  1336. return true;
  1337. // We haven't yet attached the base specifiers.
  1338. Class->setIsParsingBaseSpecifiers();
  1339. // We do not support any C++11 attributes on base-specifiers yet.
  1340. // Diagnose any attributes we see.
  1341. if (!Attributes.empty()) {
  1342. for (AttributeList *Attr = Attributes.getList(); Attr;
  1343. Attr = Attr->getNext()) {
  1344. if (Attr->isInvalid() ||
  1345. Attr->getKind() == AttributeList::IgnoredAttribute)
  1346. continue;
  1347. Diag(Attr->getLoc(),
  1348. Attr->getKind() == AttributeList::UnknownAttribute
  1349. ? diag::warn_unknown_attribute_ignored
  1350. : diag::err_base_specifier_attribute)
  1351. << Attr->getName();
  1352. }
  1353. }
  1354. TypeSourceInfo *TInfo = nullptr;
  1355. GetTypeFromParser(basetype, &TInfo);
  1356. if (EllipsisLoc.isInvalid() &&
  1357. DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
  1358. UPPC_BaseType))
  1359. return true;
  1360. if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
  1361. Virtual, Access, TInfo,
  1362. EllipsisLoc))
  1363. return BaseSpec;
  1364. else
  1365. Class->setInvalidDecl();
  1366. return true;
  1367. }
  1368. /// Use small set to collect indirect bases. As this is only used
  1369. /// locally, there's no need to abstract the small size parameter.
  1370. typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
  1371. /// \brief Recursively add the bases of Type. Don't add Type itself.
  1372. static void
  1373. NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
  1374. const QualType &Type)
  1375. {
  1376. // Even though the incoming type is a base, it might not be
  1377. // a class -- it could be a template parm, for instance.
  1378. if (auto Rec = Type->getAs<RecordType>()) {
  1379. auto Decl = Rec->getAsCXXRecordDecl();
  1380. // Iterate over its bases.
  1381. for (const auto &BaseSpec : Decl->bases()) {
  1382. QualType Base = Context.getCanonicalType(BaseSpec.getType())
  1383. .getUnqualifiedType();
  1384. if (Set.insert(Base).second)
  1385. // If we've not already seen it, recurse.
  1386. NoteIndirectBases(Context, Set, Base);
  1387. }
  1388. }
  1389. }
  1390. // HLSL Change Starts
  1391. static bool isConcreteBaseType(const QualType& t)
  1392. {
  1393. // Other than interfaces, all base types are concrete.
  1394. const Type* type = t.getTypePtr();
  1395. if (!type->isRecordType()) return true; // Likely should have been rejected before.
  1396. return !(type->getAsCXXRecordDecl()->getTagKind() == TagTypeKind::TTK_Interface);
  1397. }
  1398. // HLSL Change Ends
  1399. /// \brief Performs the actual work of attaching the given base class
  1400. /// specifiers to a C++ class.
  1401. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
  1402. unsigned NumBases) {
  1403. if (NumBases == 0)
  1404. return false;
  1405. // HLSL Change Starts
  1406. if (Class->getTagKind() == TagTypeKind::TTK_Interface) {
  1407. Diag(Bases[0]->getLocStart(), diag::err_hlsl_interfaces_cannot_inherit);
  1408. return true;
  1409. }
  1410. // HLSL Change Ends
  1411. // Used to keep track of which base types we have already seen, so
  1412. // that we can properly diagnose redundant direct base types. Note
  1413. // that the key is always the unqualified canonical type of the base
  1414. // class.
  1415. std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
  1416. // Used to track indirect bases so we can see if a direct base is
  1417. // ambiguous.
  1418. IndirectBaseSet IndirectBaseTypes;
  1419. // Copy non-redundant base specifiers into permanent storage.
  1420. bool ConcreteBaseTypeFound = false; // HLSL Change
  1421. bool ConcreteBaseTypeReported = false; // HLSL Change
  1422. unsigned NumGoodBases = 0;
  1423. bool Invalid = false;
  1424. for (unsigned idx = 0; idx < NumBases; ++idx) {
  1425. QualType NewBaseType
  1426. = Context.getCanonicalType(Bases[idx]->getType());
  1427. NewBaseType = NewBaseType.getLocalUnqualifiedType();
  1428. // HLSL Change Starts
  1429. if (!ConcreteBaseTypeReported) {
  1430. if (isConcreteBaseType(NewBaseType)) {
  1431. if (ConcreteBaseTypeFound) {
  1432. Diag(Bases[idx]->getLocStart(), diag::err_hlsl_multiple_concrete_bases);
  1433. Invalid = true;
  1434. ConcreteBaseTypeReported = true;
  1435. } else {
  1436. ConcreteBaseTypeFound = true;
  1437. }
  1438. }
  1439. }
  1440. // HLSL Change Ends
  1441. CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
  1442. if (KnownBase) {
  1443. // C++ [class.mi]p3:
  1444. // A class shall not be specified as a direct base class of a
  1445. // derived class more than once.
  1446. Diag(Bases[idx]->getLocStart(),
  1447. diag::err_duplicate_base_class)
  1448. << KnownBase->getType()
  1449. << Bases[idx]->getSourceRange();
  1450. // Delete the duplicate base class specifier; we're going to
  1451. // overwrite its pointer later.
  1452. Context.Deallocate(Bases[idx]);
  1453. Invalid = true;
  1454. } else {
  1455. // Okay, add this new base class.
  1456. KnownBase = Bases[idx];
  1457. Bases[NumGoodBases++] = Bases[idx];
  1458. // Note this base's direct & indirect bases, if there could be ambiguity.
  1459. if (NumBases > 1)
  1460. NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
  1461. if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
  1462. const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
  1463. if (Class->isInterface() &&
  1464. (!RD->isInterface() ||
  1465. KnownBase->getAccessSpecifier() != AS_public)) {
  1466. // The Microsoft extension __interface does not permit bases that
  1467. // are not themselves public interfaces.
  1468. Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
  1469. << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
  1470. << RD->getSourceRange();
  1471. Invalid = true;
  1472. }
  1473. if (RD->hasAttr<WeakAttr>())
  1474. Class->addAttr(WeakAttr::CreateImplicit(Context));
  1475. }
  1476. }
  1477. }
  1478. // Attach the remaining base class specifiers to the derived class.
  1479. Class->setBases(Bases, NumGoodBases);
  1480. for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
  1481. // Check whether this direct base is inaccessible due to ambiguity.
  1482. QualType BaseType = Bases[idx]->getType();
  1483. CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
  1484. .getUnqualifiedType();
  1485. if (IndirectBaseTypes.count(CanonicalBase)) {
  1486. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1487. /*DetectVirtual=*/true);
  1488. bool found
  1489. = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
  1490. assert(found);
  1491. (void)found;
  1492. if (Paths.isAmbiguous(CanonicalBase))
  1493. Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
  1494. << BaseType << getAmbiguousPathsDisplayString(Paths)
  1495. << Bases[idx]->getSourceRange();
  1496. else
  1497. assert(Bases[idx]->isVirtual());
  1498. }
  1499. // Delete the base class specifier, since its data has been copied
  1500. // into the CXXRecordDecl.
  1501. Context.Deallocate(Bases[idx]);
  1502. }
  1503. return Invalid;
  1504. }
  1505. /// ActOnBaseSpecifiers - Attach the given base specifiers to the
  1506. /// class, after checking whether there are any duplicate base
  1507. /// classes.
  1508. void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
  1509. unsigned NumBases) {
  1510. if (!ClassDecl || !Bases || !NumBases)
  1511. return;
  1512. AdjustDeclIfTemplate(ClassDecl);
  1513. AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
  1514. }
  1515. /// \brief Determine whether the type \p Derived is a C++ class that is
  1516. /// derived from the type \p Base.
  1517. bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
  1518. if (!getLangOpts().CPlusPlus)
  1519. return false;
  1520. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  1521. if (!DerivedRD)
  1522. return false;
  1523. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  1524. if (!BaseRD)
  1525. return false;
  1526. // If either the base or the derived type is invalid, don't try to
  1527. // check whether one is derived from the other.
  1528. if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
  1529. return false;
  1530. // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
  1531. return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
  1532. }
  1533. /// \brief Determine whether the type \p Derived is a C++ class that is
  1534. /// derived from the type \p Base.
  1535. bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
  1536. if (!getLangOpts().CPlusPlus)
  1537. return false;
  1538. CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
  1539. if (!DerivedRD)
  1540. return false;
  1541. CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
  1542. if (!BaseRD)
  1543. return false;
  1544. return DerivedRD->isDerivedFrom(BaseRD, Paths);
  1545. }
  1546. void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
  1547. CXXCastPath &BasePathArray) {
  1548. assert(BasePathArray.empty() && "Base path array must be empty!");
  1549. assert(Paths.isRecordingPaths() && "Must record paths!");
  1550. const CXXBasePath &Path = Paths.front();
  1551. // We first go backward and check if we have a virtual base.
  1552. // FIXME: It would be better if CXXBasePath had the base specifier for
  1553. // the nearest virtual base.
  1554. unsigned Start = 0;
  1555. for (unsigned I = Path.size(); I != 0; --I) {
  1556. if (Path[I - 1].Base->isVirtual()) {
  1557. Start = I - 1;
  1558. break;
  1559. }
  1560. }
  1561. // Now add all bases.
  1562. for (unsigned I = Start, E = Path.size(); I != E; ++I)
  1563. BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
  1564. }
  1565. /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
  1566. /// conversion (where Derived and Base are class types) is
  1567. /// well-formed, meaning that the conversion is unambiguous (and
  1568. /// that all of the base classes are accessible). Returns true
  1569. /// and emits a diagnostic if the code is ill-formed, returns false
  1570. /// otherwise. Loc is the location where this routine should point to
  1571. /// if there is an error, and Range is the source range to highlight
  1572. /// if there is an error.
  1573. bool
  1574. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  1575. unsigned InaccessibleBaseID,
  1576. unsigned AmbigiousBaseConvID,
  1577. SourceLocation Loc, SourceRange Range,
  1578. DeclarationName Name,
  1579. CXXCastPath *BasePath) {
  1580. // First, determine whether the path from Derived to Base is
  1581. // ambiguous. This is slightly more expensive than checking whether
  1582. // the Derived to Base conversion exists, because here we need to
  1583. // explore multiple paths to determine if there is an ambiguity.
  1584. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1585. /*DetectVirtual=*/false);
  1586. bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
  1587. // HLSL Change Begin - fix crash when Paths is empty.
  1588. // Merged from upstream.
  1589. if (!DerivationOkay)
  1590. return true;
  1591. // HLSL Change End.
  1592. if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
  1593. if (InaccessibleBaseID) {
  1594. // Check that the base class can be accessed.
  1595. switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
  1596. InaccessibleBaseID)) {
  1597. case AR_inaccessible:
  1598. return true;
  1599. case AR_accessible:
  1600. case AR_dependent:
  1601. case AR_delayed:
  1602. break;
  1603. }
  1604. }
  1605. // Build a base path if necessary.
  1606. if (BasePath)
  1607. BuildBasePathArray(Paths, *BasePath);
  1608. return false;
  1609. }
  1610. if (AmbigiousBaseConvID) {
  1611. // We know that the derived-to-base conversion is ambiguous, and
  1612. // we're going to produce a diagnostic. Perform the derived-to-base
  1613. // search just one more time to compute all of the possible paths so
  1614. // that we can print them out. This is more expensive than any of
  1615. // the previous derived-to-base checks we've done, but at this point
  1616. // performance isn't as much of an issue.
  1617. Paths.clear();
  1618. Paths.setRecordingPaths(true);
  1619. bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
  1620. assert(StillOkay && "Can only be used with a derived-to-base conversion");
  1621. (void)StillOkay;
  1622. // Build up a textual representation of the ambiguous paths, e.g.,
  1623. // D -> B -> A, that will be used to illustrate the ambiguous
  1624. // conversions in the diagnostic. We only print one of the paths
  1625. // to each base class subobject.
  1626. std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
  1627. Diag(Loc, AmbigiousBaseConvID)
  1628. << Derived << Base << PathDisplayStr << Range << Name;
  1629. }
  1630. return true;
  1631. }
  1632. bool
  1633. Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
  1634. SourceLocation Loc, SourceRange Range,
  1635. CXXCastPath *BasePath,
  1636. bool IgnoreAccess) {
  1637. return CheckDerivedToBaseConversion(Derived, Base,
  1638. IgnoreAccess ? 0
  1639. : diag::err_upcast_to_inaccessible_base,
  1640. diag::err_ambiguous_derived_to_base_conv,
  1641. Loc, Range, DeclarationName(),
  1642. BasePath);
  1643. }
  1644. /// @brief Builds a string representing ambiguous paths from a
  1645. /// specific derived class to different subobjects of the same base
  1646. /// class.
  1647. ///
  1648. /// This function builds a string that can be used in error messages
  1649. /// to show the different paths that one can take through the
  1650. /// inheritance hierarchy to go from the derived class to different
  1651. /// subobjects of a base class. The result looks something like this:
  1652. /// @code
  1653. /// struct D -> struct B -> struct A
  1654. /// struct D -> struct C -> struct A
  1655. /// @endcode
  1656. std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
  1657. std::string PathDisplayStr;
  1658. std::set<unsigned> DisplayedPaths;
  1659. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  1660. Path != Paths.end(); ++Path) {
  1661. if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
  1662. // We haven't displayed a path to this particular base
  1663. // class subobject yet.
  1664. PathDisplayStr += "\n ";
  1665. PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
  1666. for (CXXBasePath::const_iterator Element = Path->begin();
  1667. Element != Path->end(); ++Element)
  1668. PathDisplayStr += " -> " + Element->Base->getType().getAsString();
  1669. }
  1670. }
  1671. return PathDisplayStr;
  1672. }
  1673. //===----------------------------------------------------------------------===//
  1674. // C++ class member Handling
  1675. //===----------------------------------------------------------------------===//
  1676. /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
  1677. bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
  1678. SourceLocation ASLoc,
  1679. SourceLocation ColonLoc,
  1680. AttributeList *Attrs) {
  1681. assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
  1682. AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
  1683. ASLoc, ColonLoc);
  1684. CurContext->addHiddenDecl(ASDecl);
  1685. return ProcessAccessDeclAttributeList(ASDecl, Attrs);
  1686. }
  1687. /// CheckOverrideControl - Check C++11 override control semantics.
  1688. void Sema::CheckOverrideControl(NamedDecl *D) {
  1689. if (D->isInvalidDecl())
  1690. return;
  1691. // We only care about "override" and "final" declarations.
  1692. if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
  1693. return;
  1694. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  1695. // We can't check dependent instance methods.
  1696. if (MD && MD->isInstance() &&
  1697. (MD->getParent()->hasAnyDependentBases() ||
  1698. MD->getType()->isDependentType()))
  1699. return;
  1700. if (MD && !MD->isVirtual()) {
  1701. // If we have a non-virtual method, check if if hides a virtual method.
  1702. // (In that case, it's most likely the method has the wrong type.)
  1703. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  1704. FindHiddenVirtualMethods(MD, OverloadedMethods);
  1705. if (!OverloadedMethods.empty()) {
  1706. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  1707. Diag(OA->getLocation(),
  1708. diag::override_keyword_hides_virtual_member_function)
  1709. << "override" << (OverloadedMethods.size() > 1);
  1710. } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  1711. Diag(FA->getLocation(),
  1712. diag::override_keyword_hides_virtual_member_function)
  1713. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  1714. << (OverloadedMethods.size() > 1);
  1715. }
  1716. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  1717. MD->setInvalidDecl();
  1718. return;
  1719. }
  1720. // Fall through into the general case diagnostic.
  1721. // FIXME: We might want to attempt typo correction here.
  1722. }
  1723. if (!MD || !MD->isVirtual()) {
  1724. if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
  1725. Diag(OA->getLocation(),
  1726. diag::override_keyword_only_allowed_on_virtual_member_functions)
  1727. << "override" << FixItHint::CreateRemoval(OA->getLocation());
  1728. D->dropAttr<OverrideAttr>();
  1729. }
  1730. if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
  1731. Diag(FA->getLocation(),
  1732. diag::override_keyword_only_allowed_on_virtual_member_functions)
  1733. << (FA->isSpelledAsSealed() ? "sealed" : "final")
  1734. << FixItHint::CreateRemoval(FA->getLocation());
  1735. D->dropAttr<FinalAttr>();
  1736. }
  1737. return;
  1738. }
  1739. // C++11 [class.virtual]p5:
  1740. // If a function is marked with the virt-specifier override and
  1741. // does not override a member function of a base class, the program is
  1742. // ill-formed.
  1743. bool HasOverriddenMethods =
  1744. MD->begin_overridden_methods() != MD->end_overridden_methods();
  1745. if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
  1746. Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
  1747. << MD->getDeclName();
  1748. }
  1749. void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
  1750. if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
  1751. return;
  1752. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
  1753. if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
  1754. isa<CXXDestructorDecl>(MD))
  1755. return;
  1756. SourceLocation Loc = MD->getLocation();
  1757. SourceLocation SpellingLoc = Loc;
  1758. if (getSourceManager().isMacroArgExpansion(Loc))
  1759. SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
  1760. SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
  1761. if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
  1762. return;
  1763. if (MD->size_overridden_methods() > 0) {
  1764. Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
  1765. << MD->getDeclName();
  1766. const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
  1767. Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
  1768. }
  1769. }
  1770. /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
  1771. /// function overrides a virtual member function marked 'final', according to
  1772. /// C++11 [class.virtual]p4.
  1773. bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
  1774. const CXXMethodDecl *Old) {
  1775. FinalAttr *FA = Old->getAttr<FinalAttr>();
  1776. if (!FA)
  1777. return false;
  1778. Diag(New->getLocation(), diag::err_final_function_overridden)
  1779. << New->getDeclName()
  1780. << FA->isSpelledAsSealed();
  1781. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  1782. return true;
  1783. }
  1784. static bool InitializationHasSideEffects(const FieldDecl &FD) {
  1785. const Type *T = FD.getType()->getBaseElementTypeUnsafe();
  1786. // FIXME: Destruction of ObjC lifetime types has side-effects.
  1787. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
  1788. return !RD->isCompleteDefinition() ||
  1789. !RD->hasTrivialDefaultConstructor() ||
  1790. !RD->hasTrivialDestructor();
  1791. return false;
  1792. }
  1793. static AttributeList *getMSPropertyAttr(AttributeList *list) {
  1794. for (AttributeList *it = list; it != nullptr; it = it->getNext())
  1795. if (it->isDeclspecPropertyAttribute())
  1796. return it;
  1797. return nullptr;
  1798. }
  1799. /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
  1800. /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
  1801. /// bitfield width if there is one, 'InitExpr' specifies the initializer if
  1802. /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
  1803. /// present (but parsing it has been deferred).
  1804. NamedDecl *
  1805. Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
  1806. MultiTemplateParamsArg TemplateParameterLists,
  1807. Expr *BW, const VirtSpecifiers &VS,
  1808. InClassInitStyle InitStyle) {
  1809. const DeclSpec &DS = D.getDeclSpec();
  1810. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  1811. DeclarationName Name = NameInfo.getName();
  1812. SourceLocation Loc = NameInfo.getLoc();
  1813. // For anonymous bitfields, the location should point to the type.
  1814. if (Loc.isInvalid())
  1815. Loc = D.getLocStart();
  1816. Expr *BitWidth = static_cast<Expr*>(BW);
  1817. assert(isa<CXXRecordDecl>(CurContext));
  1818. assert(!DS.isFriendSpecified());
  1819. bool isFunc = D.isDeclarationOfFunction();
  1820. if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
  1821. // The Microsoft extension __interface only permits public member functions
  1822. // and prohibits constructors, destructors, operators, non-public member
  1823. // functions, static methods and data members.
  1824. unsigned InvalidDecl;
  1825. bool ShowDeclName = true;
  1826. if (!isFunc)
  1827. InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
  1828. else if (AS != AS_public)
  1829. InvalidDecl = 2;
  1830. else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
  1831. InvalidDecl = 3;
  1832. else switch (Name.getNameKind()) {
  1833. case DeclarationName::CXXConstructorName:
  1834. InvalidDecl = 4;
  1835. ShowDeclName = false;
  1836. break;
  1837. case DeclarationName::CXXDestructorName:
  1838. InvalidDecl = 5;
  1839. ShowDeclName = false;
  1840. break;
  1841. case DeclarationName::CXXOperatorName:
  1842. case DeclarationName::CXXConversionFunctionName:
  1843. InvalidDecl = 6;
  1844. break;
  1845. default:
  1846. InvalidDecl = 0;
  1847. break;
  1848. }
  1849. if (InvalidDecl) {
  1850. if (ShowDeclName)
  1851. Diag(Loc, diag::err_invalid_member_in_interface)
  1852. << (InvalidDecl-1) << Name;
  1853. else
  1854. Diag(Loc, diag::err_invalid_member_in_interface)
  1855. << (InvalidDecl-1) << "";
  1856. return nullptr;
  1857. }
  1858. }
  1859. // C++ 9.2p6: A member shall not be declared to have automatic storage
  1860. // duration (auto, register) or with the extern storage-class-specifier.
  1861. // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
  1862. // data members and cannot be applied to names declared const or static,
  1863. // and cannot be applied to reference members.
  1864. switch (DS.getStorageClassSpec()) {
  1865. case DeclSpec::SCS_unspecified:
  1866. case DeclSpec::SCS_typedef:
  1867. case DeclSpec::SCS_static:
  1868. break;
  1869. case DeclSpec::SCS_mutable:
  1870. if (isFunc) {
  1871. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
  1872. // FIXME: It would be nicer if the keyword was ignored only for this
  1873. // declarator. Otherwise we could get follow-up errors.
  1874. D.getMutableDeclSpec().ClearStorageClassSpecs();
  1875. }
  1876. break;
  1877. default:
  1878. Diag(DS.getStorageClassSpecLoc(),
  1879. diag::err_storageclass_invalid_for_member);
  1880. D.getMutableDeclSpec().ClearStorageClassSpecs();
  1881. break;
  1882. }
  1883. bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
  1884. DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
  1885. !isFunc);
  1886. if (DS.isConstexprSpecified() && isInstField) {
  1887. SemaDiagnosticBuilder B =
  1888. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
  1889. SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
  1890. if (InitStyle == ICIS_NoInit) {
  1891. B << 0 << 0;
  1892. if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
  1893. B << FixItHint::CreateRemoval(ConstexprLoc);
  1894. else {
  1895. B << FixItHint::CreateReplacement(ConstexprLoc, "const");
  1896. D.getMutableDeclSpec().ClearConstexprSpec();
  1897. const char *PrevSpec;
  1898. unsigned DiagID;
  1899. bool Failed = D.getMutableDeclSpec().SetTypeQual(
  1900. DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
  1901. (void)Failed;
  1902. assert(!Failed && "Making a constexpr member const shouldn't fail");
  1903. }
  1904. } else {
  1905. B << 1;
  1906. const char *PrevSpec;
  1907. unsigned DiagID;
  1908. if (D.getMutableDeclSpec().SetStorageClassSpec(
  1909. *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
  1910. Context.getPrintingPolicy())) {
  1911. assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
  1912. "This is the only DeclSpec that should fail to be applied");
  1913. B << 1;
  1914. } else {
  1915. B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
  1916. isInstField = false;
  1917. }
  1918. }
  1919. }
  1920. NamedDecl *Member;
  1921. if (isInstField) {
  1922. CXXScopeSpec &SS = D.getCXXScopeSpec();
  1923. // Data members must have identifiers for names.
  1924. if (!Name.isIdentifier()) {
  1925. Diag(Loc, diag::err_bad_variable_name)
  1926. << Name;
  1927. return nullptr;
  1928. }
  1929. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1930. // Member field could not be with "template" keyword.
  1931. // So TemplateParameterLists should be empty in this case.
  1932. if (TemplateParameterLists.size()) {
  1933. TemplateParameterList* TemplateParams = TemplateParameterLists[0];
  1934. if (TemplateParams->size()) {
  1935. // There is no such thing as a member field template.
  1936. Diag(D.getIdentifierLoc(), diag::err_template_member)
  1937. << II
  1938. << SourceRange(TemplateParams->getTemplateLoc(),
  1939. TemplateParams->getRAngleLoc());
  1940. } else {
  1941. // There is an extraneous 'template<>' for this member.
  1942. Diag(TemplateParams->getTemplateLoc(),
  1943. diag::err_template_member_noparams)
  1944. << II
  1945. << SourceRange(TemplateParams->getTemplateLoc(),
  1946. TemplateParams->getRAngleLoc());
  1947. }
  1948. return nullptr;
  1949. }
  1950. if (SS.isSet() && !SS.isInvalid()) {
  1951. // The user provided a superfluous scope specifier inside a class
  1952. // definition:
  1953. //
  1954. // class X {
  1955. // int X::member;
  1956. // };
  1957. if (DeclContext *DC = computeDeclContext(SS, false))
  1958. diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
  1959. else
  1960. Diag(D.getIdentifierLoc(), diag::err_member_qualification)
  1961. << Name << SS.getRange();
  1962. SS.clear();
  1963. }
  1964. AttributeList *MSPropertyAttr =
  1965. getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
  1966. if (MSPropertyAttr) {
  1967. Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  1968. BitWidth, InitStyle, AS, MSPropertyAttr);
  1969. if (!Member)
  1970. return nullptr;
  1971. isInstField = false;
  1972. } else {
  1973. Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
  1974. BitWidth, InitStyle, AS);
  1975. assert(Member && "HandleField never returns null");
  1976. }
  1977. } else {
  1978. Member = HandleDeclarator(S, D, TemplateParameterLists);
  1979. if (!Member)
  1980. return nullptr;
  1981. // Non-instance-fields can't have a bitfield.
  1982. if (BitWidth) {
  1983. if (Member->isInvalidDecl()) {
  1984. // don't emit another diagnostic.
  1985. } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
  1986. // C++ 9.6p3: A bit-field shall not be a static member.
  1987. // "static member 'A' cannot be a bit-field"
  1988. Diag(Loc, diag::err_static_not_bitfield)
  1989. << Name << BitWidth->getSourceRange();
  1990. } else if (isa<TypedefDecl>(Member)) {
  1991. // "typedef member 'x' cannot be a bit-field"
  1992. Diag(Loc, diag::err_typedef_not_bitfield)
  1993. << Name << BitWidth->getSourceRange();
  1994. } else {
  1995. // A function typedef ("typedef int f(); f a;").
  1996. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  1997. Diag(Loc, diag::err_not_integral_type_bitfield)
  1998. << Name << cast<ValueDecl>(Member)->getType()
  1999. << BitWidth->getSourceRange();
  2000. }
  2001. BitWidth = nullptr;
  2002. Member->setInvalidDecl();
  2003. }
  2004. Member->setAccess(AS);
  2005. // If we have declared a member function template or static data member
  2006. // template, set the access of the templated declaration as well.
  2007. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
  2008. FunTmpl->getTemplatedDecl()->setAccess(AS);
  2009. else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
  2010. VarTmpl->getTemplatedDecl()->setAccess(AS);
  2011. }
  2012. if (VS.isOverrideSpecified())
  2013. Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
  2014. if (VS.isFinalSpecified())
  2015. Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
  2016. VS.isFinalSpelledSealed()));
  2017. if (VS.getLastLocation().isValid()) {
  2018. // Update the end location of a method that has a virt-specifiers.
  2019. if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
  2020. MD->setRangeEnd(VS.getLastLocation());
  2021. }
  2022. CheckOverrideControl(Member);
  2023. assert((Name || isInstField) && "No identifier for non-field ?");
  2024. if (isInstField) {
  2025. FieldDecl *FD = cast<FieldDecl>(Member);
  2026. FieldCollector->Add(FD);
  2027. if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
  2028. // Remember all explicit private FieldDecls that have a name, no side
  2029. // effects and are not part of a dependent type declaration.
  2030. if (!FD->isImplicit() && FD->getDeclName() &&
  2031. FD->getAccess() == AS_private &&
  2032. !FD->hasAttr<UnusedAttr>() &&
  2033. !FD->getParent()->isDependentContext() &&
  2034. !InitializationHasSideEffects(*FD))
  2035. UnusedPrivateFields.insert(FD);
  2036. }
  2037. }
  2038. return Member;
  2039. }
  2040. namespace {
  2041. class UninitializedFieldVisitor
  2042. : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
  2043. Sema &S;
  2044. // List of Decls to generate a warning on. Also remove Decls that become
  2045. // initialized.
  2046. llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
  2047. // List of base classes of the record. Classes are removed after their
  2048. // initializers.
  2049. llvm::SmallPtrSetImpl<QualType> &BaseClasses;
  2050. // Vector of decls to be removed from the Decl set prior to visiting the
  2051. // nodes. These Decls may have been initialized in the prior initializer.
  2052. llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
  2053. // If non-null, add a note to the warning pointing back to the constructor.
  2054. const CXXConstructorDecl *Constructor;
  2055. // Variables to hold state when processing an initializer list. When
  2056. // InitList is true, special case initialization of FieldDecls matching
  2057. // InitListFieldDecl.
  2058. bool InitList;
  2059. FieldDecl *InitListFieldDecl;
  2060. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  2061. public:
  2062. typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
  2063. UninitializedFieldVisitor(Sema &S,
  2064. llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
  2065. llvm::SmallPtrSetImpl<QualType> &BaseClasses)
  2066. : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
  2067. Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
  2068. // Returns true if the use of ME is not an uninitialized use.
  2069. bool IsInitListMemberExprInitialized(MemberExpr *ME,
  2070. bool CheckReferenceOnly) {
  2071. llvm::SmallVector<FieldDecl*, 4> Fields;
  2072. bool ReferenceField = false;
  2073. while (ME) {
  2074. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  2075. if (!FD)
  2076. return false;
  2077. Fields.push_back(FD);
  2078. if (FD->getType()->isReferenceType())
  2079. ReferenceField = true;
  2080. ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
  2081. }
  2082. // Binding a reference to an unintialized field is not an
  2083. // uninitialized use.
  2084. if (CheckReferenceOnly && !ReferenceField)
  2085. return true;
  2086. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  2087. // Discard the first field since it is the field decl that is being
  2088. // initialized.
  2089. for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
  2090. UsedFieldIndex.push_back((*I)->getFieldIndex());
  2091. }
  2092. for (auto UsedIter = UsedFieldIndex.begin(),
  2093. UsedEnd = UsedFieldIndex.end(),
  2094. OrigIter = InitFieldIndex.begin(),
  2095. OrigEnd = InitFieldIndex.end();
  2096. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  2097. if (*UsedIter < *OrigIter)
  2098. return true;
  2099. if (*UsedIter > *OrigIter)
  2100. break;
  2101. }
  2102. return false;
  2103. }
  2104. void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
  2105. bool AddressOf) {
  2106. if (isa<EnumConstantDecl>(ME->getMemberDecl()))
  2107. return;
  2108. // FieldME is the inner-most MemberExpr that is not an anonymous struct
  2109. // or union.
  2110. MemberExpr *FieldME = ME;
  2111. bool AllPODFields = FieldME->getType().isPODType(S.Context);
  2112. Expr *Base = ME;
  2113. while (MemberExpr *SubME =
  2114. dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
  2115. if (isa<VarDecl>(SubME->getMemberDecl()))
  2116. return;
  2117. if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
  2118. if (!FD->isAnonymousStructOrUnion())
  2119. FieldME = SubME;
  2120. if (!FieldME->getType().isPODType(S.Context))
  2121. AllPODFields = false;
  2122. Base = SubME->getBase();
  2123. }
  2124. if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
  2125. return;
  2126. if (AddressOf && AllPODFields)
  2127. return;
  2128. ValueDecl* FoundVD = FieldME->getMemberDecl();
  2129. if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
  2130. while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
  2131. BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
  2132. }
  2133. if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
  2134. QualType T = BaseCast->getType();
  2135. if (T->isPointerType() &&
  2136. BaseClasses.count(T->getPointeeType())) {
  2137. S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
  2138. << T->getPointeeType() << FoundVD;
  2139. }
  2140. }
  2141. }
  2142. if (!Decls.count(FoundVD))
  2143. return;
  2144. const bool IsReference = FoundVD->getType()->isReferenceType();
  2145. if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
  2146. // Special checking for initializer lists.
  2147. if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
  2148. return;
  2149. }
  2150. } else {
  2151. // Prevent double warnings on use of unbounded references.
  2152. if (CheckReferenceOnly && !IsReference)
  2153. return;
  2154. }
  2155. unsigned diag = IsReference
  2156. ? diag::warn_reference_field_is_uninit
  2157. : diag::warn_field_is_uninit;
  2158. S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
  2159. if (Constructor)
  2160. S.Diag(Constructor->getLocation(),
  2161. diag::note_uninit_in_this_constructor)
  2162. << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
  2163. }
  2164. void HandleValue(Expr *E, bool AddressOf) {
  2165. E = E->IgnoreParens();
  2166. if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  2167. HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
  2168. AddressOf /*AddressOf*/);
  2169. return;
  2170. }
  2171. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2172. Visit(CO->getCond());
  2173. HandleValue(CO->getTrueExpr(), AddressOf);
  2174. HandleValue(CO->getFalseExpr(), AddressOf);
  2175. return;
  2176. }
  2177. if (BinaryConditionalOperator *BCO =
  2178. dyn_cast<BinaryConditionalOperator>(E)) {
  2179. Visit(BCO->getCond());
  2180. HandleValue(BCO->getFalseExpr(), AddressOf);
  2181. return;
  2182. }
  2183. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  2184. HandleValue(OVE->getSourceExpr(), AddressOf);
  2185. return;
  2186. }
  2187. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2188. switch (BO->getOpcode()) {
  2189. default:
  2190. break;
  2191. case(BO_PtrMemD):
  2192. case(BO_PtrMemI):
  2193. HandleValue(BO->getLHS(), AddressOf);
  2194. Visit(BO->getRHS());
  2195. return;
  2196. case(BO_Comma):
  2197. Visit(BO->getLHS());
  2198. HandleValue(BO->getRHS(), AddressOf);
  2199. return;
  2200. }
  2201. }
  2202. Visit(E);
  2203. }
  2204. void CheckInitListExpr(InitListExpr *ILE) {
  2205. InitFieldIndex.push_back(0);
  2206. for (auto Child : ILE->children()) {
  2207. if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
  2208. CheckInitListExpr(SubList);
  2209. } else {
  2210. Visit(Child);
  2211. }
  2212. ++InitFieldIndex.back();
  2213. }
  2214. InitFieldIndex.pop_back();
  2215. }
  2216. void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
  2217. FieldDecl *Field, const Type *BaseClass) {
  2218. // Remove Decls that may have been initialized in the previous
  2219. // initializer.
  2220. for (ValueDecl* VD : DeclsToRemove)
  2221. Decls.erase(VD);
  2222. DeclsToRemove.clear();
  2223. Constructor = FieldConstructor;
  2224. InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  2225. if (ILE && Field) {
  2226. InitList = true;
  2227. InitListFieldDecl = Field;
  2228. InitFieldIndex.clear();
  2229. CheckInitListExpr(ILE);
  2230. } else {
  2231. InitList = false;
  2232. Visit(E);
  2233. }
  2234. if (Field)
  2235. Decls.erase(Field);
  2236. if (BaseClass)
  2237. BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
  2238. }
  2239. void VisitMemberExpr(MemberExpr *ME) {
  2240. // All uses of unbounded reference fields will warn.
  2241. HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
  2242. }
  2243. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  2244. if (E->getCastKind() == CK_LValueToRValue) {
  2245. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  2246. return;
  2247. }
  2248. Inherited::VisitImplicitCastExpr(E);
  2249. }
  2250. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  2251. if (E->getConstructor()->isCopyConstructor()) {
  2252. Expr *ArgExpr = E->getArg(0);
  2253. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  2254. if (ILE->getNumInits() == 1)
  2255. ArgExpr = ILE->getInit(0);
  2256. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  2257. if (ICE->getCastKind() == CK_NoOp)
  2258. ArgExpr = ICE->getSubExpr();
  2259. HandleValue(ArgExpr, false /*AddressOf*/);
  2260. return;
  2261. }
  2262. Inherited::VisitCXXConstructExpr(E);
  2263. }
  2264. void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2265. Expr *Callee = E->getCallee();
  2266. if (isa<MemberExpr>(Callee)) {
  2267. HandleValue(Callee, false /*AddressOf*/);
  2268. for (auto Arg : E->arguments())
  2269. Visit(Arg);
  2270. return;
  2271. }
  2272. Inherited::VisitCXXMemberCallExpr(E);
  2273. }
  2274. void VisitCallExpr(CallExpr *E) {
  2275. // Treat std::move as a use.
  2276. if (E->getNumArgs() == 1) {
  2277. if (FunctionDecl *FD = E->getDirectCallee()) {
  2278. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  2279. FD->getIdentifier()->isStr("move")) {
  2280. HandleValue(E->getArg(0), false /*AddressOf*/);
  2281. return;
  2282. }
  2283. }
  2284. }
  2285. Inherited::VisitCallExpr(E);
  2286. }
  2287. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  2288. Expr *Callee = E->getCallee();
  2289. if (isa<UnresolvedLookupExpr>(Callee))
  2290. return Inherited::VisitCXXOperatorCallExpr(E);
  2291. Visit(Callee);
  2292. for (auto Arg : E->arguments())
  2293. HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
  2294. }
  2295. void VisitBinaryOperator(BinaryOperator *E) {
  2296. // If a field assignment is detected, remove the field from the
  2297. // uninitiailized field set.
  2298. if (E->getOpcode() == BO_Assign)
  2299. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
  2300. if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  2301. if (!FD->getType()->isReferenceType())
  2302. DeclsToRemove.push_back(FD);
  2303. if (E->isCompoundAssignmentOp()) {
  2304. HandleValue(E->getLHS(), false /*AddressOf*/);
  2305. Visit(E->getRHS());
  2306. return;
  2307. }
  2308. Inherited::VisitBinaryOperator(E);
  2309. }
  2310. void VisitUnaryOperator(UnaryOperator *E) {
  2311. if (E->isIncrementDecrementOp()) {
  2312. HandleValue(E->getSubExpr(), false /*AddressOf*/);
  2313. return;
  2314. }
  2315. if (E->getOpcode() == UO_AddrOf) {
  2316. if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
  2317. HandleValue(ME->getBase(), true /*AddressOf*/);
  2318. return;
  2319. }
  2320. }
  2321. Inherited::VisitUnaryOperator(E);
  2322. }
  2323. };
  2324. // Diagnose value-uses of fields to initialize themselves, e.g.
  2325. // foo(foo)
  2326. // where foo is not also a parameter to the constructor.
  2327. // Also diagnose across field uninitialized use such as
  2328. // x(y), y(x)
  2329. // TODO: implement -Wuninitialized and fold this into that framework.
  2330. static void DiagnoseUninitializedFields(
  2331. Sema &SemaRef, const CXXConstructorDecl *Constructor) {
  2332. if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
  2333. Constructor->getLocation())) {
  2334. return;
  2335. }
  2336. if (Constructor->isInvalidDecl())
  2337. return;
  2338. const CXXRecordDecl *RD = Constructor->getParent();
  2339. if (RD->getDescribedClassTemplate())
  2340. return;
  2341. // Holds fields that are uninitialized.
  2342. llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
  2343. // At the beginning, all fields are uninitialized.
  2344. for (auto *I : RD->decls()) {
  2345. if (auto *FD = dyn_cast<FieldDecl>(I)) {
  2346. UninitializedFields.insert(FD);
  2347. } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
  2348. UninitializedFields.insert(IFD->getAnonField());
  2349. }
  2350. }
  2351. llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
  2352. for (auto I : RD->bases())
  2353. UninitializedBaseClasses.insert(I.getType().getCanonicalType());
  2354. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  2355. return;
  2356. UninitializedFieldVisitor UninitializedChecker(SemaRef,
  2357. UninitializedFields,
  2358. UninitializedBaseClasses);
  2359. for (const auto *FieldInit : Constructor->inits()) {
  2360. if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
  2361. break;
  2362. Expr *InitExpr = FieldInit->getInit();
  2363. if (!InitExpr)
  2364. continue;
  2365. if (CXXDefaultInitExpr *Default =
  2366. dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
  2367. InitExpr = Default->getExpr();
  2368. if (!InitExpr)
  2369. continue;
  2370. // In class initializers will point to the constructor.
  2371. UninitializedChecker.CheckInitializer(InitExpr, Constructor,
  2372. FieldInit->getAnyMember(),
  2373. FieldInit->getBaseClass());
  2374. } else {
  2375. UninitializedChecker.CheckInitializer(InitExpr, nullptr,
  2376. FieldInit->getAnyMember(),
  2377. FieldInit->getBaseClass());
  2378. }
  2379. }
  2380. }
  2381. } // namespace
  2382. /// \brief Enter a new C++ default initializer scope. After calling this, the
  2383. /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
  2384. /// parsing or instantiating the initializer failed.
  2385. void Sema::ActOnStartCXXInClassMemberInitializer() {
  2386. // Create a synthetic function scope to represent the call to the constructor
  2387. // that notionally surrounds a use of this initializer.
  2388. PushFunctionScope();
  2389. }
  2390. /// \brief This is invoked after parsing an in-class initializer for a
  2391. /// non-static C++ class member, and after instantiating an in-class initializer
  2392. /// in a class template. Such actions are deferred until the class is complete.
  2393. void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
  2394. SourceLocation InitLoc,
  2395. Expr *InitExpr) {
  2396. // Pop the notional constructor scope we created earlier.
  2397. PopFunctionScopeInfo(nullptr, D);
  2398. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  2399. assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
  2400. "must set init style when field is created");
  2401. if (!InitExpr) {
  2402. D->setInvalidDecl();
  2403. if (FD)
  2404. FD->removeInClassInitializer();
  2405. return;
  2406. }
  2407. if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
  2408. FD->setInvalidDecl();
  2409. FD->removeInClassInitializer();
  2410. return;
  2411. }
  2412. ExprResult Init = InitExpr;
  2413. if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
  2414. InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
  2415. InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
  2416. ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
  2417. : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
  2418. InitializationSequence Seq(*this, Entity, Kind, InitExpr);
  2419. Init = Seq.Perform(*this, Entity, Kind, InitExpr);
  2420. if (Init.isInvalid()) {
  2421. FD->setInvalidDecl();
  2422. return;
  2423. }
  2424. }
  2425. // C++11 [class.base.init]p7:
  2426. // The initialization of each base and member constitutes a
  2427. // full-expression.
  2428. Init = ActOnFinishFullExpr(Init.get(), InitLoc);
  2429. if (Init.isInvalid()) {
  2430. FD->setInvalidDecl();
  2431. return;
  2432. }
  2433. InitExpr = Init.get();
  2434. FD->setInClassInitializer(InitExpr);
  2435. }
  2436. /// \brief Find the direct and/or virtual base specifiers that
  2437. /// correspond to the given base type, for use in base initialization
  2438. /// within a constructor.
  2439. static bool FindBaseInitializer(Sema &SemaRef,
  2440. CXXRecordDecl *ClassDecl,
  2441. QualType BaseType,
  2442. const CXXBaseSpecifier *&DirectBaseSpec,
  2443. const CXXBaseSpecifier *&VirtualBaseSpec) {
  2444. // First, check for a direct base class.
  2445. DirectBaseSpec = nullptr;
  2446. for (const auto &Base : ClassDecl->bases()) {
  2447. if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
  2448. // We found a direct base of this type. That's what we're
  2449. // initializing.
  2450. DirectBaseSpec = &Base;
  2451. break;
  2452. }
  2453. }
  2454. // Check for a virtual base class.
  2455. // FIXME: We might be able to short-circuit this if we know in advance that
  2456. // there are no virtual bases.
  2457. VirtualBaseSpec = nullptr;
  2458. if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
  2459. // We haven't found a base yet; search the class hierarchy for a
  2460. // virtual base class.
  2461. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  2462. /*DetectVirtual=*/false);
  2463. if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
  2464. BaseType, Paths)) {
  2465. for (CXXBasePaths::paths_iterator Path = Paths.begin();
  2466. Path != Paths.end(); ++Path) {
  2467. if (Path->back().Base->isVirtual()) {
  2468. VirtualBaseSpec = Path->back().Base;
  2469. break;
  2470. }
  2471. }
  2472. }
  2473. }
  2474. return DirectBaseSpec || VirtualBaseSpec;
  2475. }
  2476. /// \brief Handle a C++ member initializer using braced-init-list syntax.
  2477. MemInitResult
  2478. Sema::ActOnMemInitializer(Decl *ConstructorD,
  2479. Scope *S,
  2480. CXXScopeSpec &SS,
  2481. IdentifierInfo *MemberOrBase,
  2482. ParsedType TemplateTypeTy,
  2483. const DeclSpec &DS,
  2484. SourceLocation IdLoc,
  2485. Expr *InitList,
  2486. SourceLocation EllipsisLoc) {
  2487. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  2488. DS, IdLoc, InitList,
  2489. EllipsisLoc);
  2490. }
  2491. /// \brief Handle a C++ member initializer using parentheses syntax.
  2492. MemInitResult
  2493. Sema::ActOnMemInitializer(Decl *ConstructorD,
  2494. Scope *S,
  2495. CXXScopeSpec &SS,
  2496. IdentifierInfo *MemberOrBase,
  2497. ParsedType TemplateTypeTy,
  2498. const DeclSpec &DS,
  2499. SourceLocation IdLoc,
  2500. SourceLocation LParenLoc,
  2501. ArrayRef<Expr *> Args,
  2502. SourceLocation RParenLoc,
  2503. SourceLocation EllipsisLoc) {
  2504. Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
  2505. Args, RParenLoc);
  2506. return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
  2507. DS, IdLoc, List, EllipsisLoc);
  2508. }
  2509. namespace {
  2510. // Callback to only accept typo corrections that can be a valid C++ member
  2511. // intializer: either a non-static field member or a base class.
  2512. class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
  2513. public:
  2514. explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
  2515. : ClassDecl(ClassDecl) {}
  2516. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2517. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  2518. if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
  2519. return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
  2520. return isa<TypeDecl>(ND);
  2521. }
  2522. return false;
  2523. }
  2524. private:
  2525. CXXRecordDecl *ClassDecl;
  2526. };
  2527. }
  2528. /// \brief Handle a C++ member initializer.
  2529. MemInitResult
  2530. Sema::BuildMemInitializer(Decl *ConstructorD,
  2531. Scope *S,
  2532. CXXScopeSpec &SS,
  2533. IdentifierInfo *MemberOrBase,
  2534. ParsedType TemplateTypeTy,
  2535. const DeclSpec &DS,
  2536. SourceLocation IdLoc,
  2537. Expr *Init,
  2538. SourceLocation EllipsisLoc) {
  2539. ExprResult Res = CorrectDelayedTyposInExpr(Init);
  2540. if (!Res.isUsable())
  2541. return true;
  2542. Init = Res.get();
  2543. if (!ConstructorD)
  2544. return true;
  2545. AdjustDeclIfTemplate(ConstructorD);
  2546. CXXConstructorDecl *Constructor
  2547. = dyn_cast<CXXConstructorDecl>(ConstructorD);
  2548. if (!Constructor) {
  2549. // The user wrote a constructor initializer on a function that is
  2550. // not a C++ constructor. Ignore the error for now, because we may
  2551. // have more member initializers coming; we'll diagnose it just
  2552. // once in ActOnMemInitializers.
  2553. return true;
  2554. }
  2555. CXXRecordDecl *ClassDecl = Constructor->getParent();
  2556. // C++ [class.base.init]p2:
  2557. // Names in a mem-initializer-id are looked up in the scope of the
  2558. // constructor's class and, if not found in that scope, are looked
  2559. // up in the scope containing the constructor's definition.
  2560. // [Note: if the constructor's class contains a member with the
  2561. // same name as a direct or virtual base class of the class, a
  2562. // mem-initializer-id naming the member or base class and composed
  2563. // of a single identifier refers to the class member. A
  2564. // mem-initializer-id for the hidden base class may be specified
  2565. // using a qualified name. ]
  2566. if (!SS.getScopeRep() && !TemplateTypeTy) {
  2567. // Look for a member, first.
  2568. DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
  2569. if (!Result.empty()) {
  2570. ValueDecl *Member;
  2571. if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
  2572. (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
  2573. if (EllipsisLoc.isValid())
  2574. Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
  2575. << MemberOrBase
  2576. << SourceRange(IdLoc, Init->getSourceRange().getEnd());
  2577. return BuildMemberInitializer(Member, Init, IdLoc);
  2578. }
  2579. }
  2580. }
  2581. // It didn't name a member, so see if it names a class.
  2582. QualType BaseType;
  2583. TypeSourceInfo *TInfo = nullptr;
  2584. if (TemplateTypeTy) {
  2585. BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
  2586. } else if (DS.getTypeSpecType() == TST_decltype) {
  2587. BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
  2588. } else {
  2589. LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
  2590. LookupParsedName(R, S, &SS);
  2591. TypeDecl *TyD = R.getAsSingle<TypeDecl>();
  2592. if (!TyD) {
  2593. if (R.isAmbiguous()) return true;
  2594. // We don't want access-control diagnostics here.
  2595. R.suppressDiagnostics();
  2596. if (SS.isSet() && isDependentScopeSpecifier(SS)) {
  2597. bool NotUnknownSpecialization = false;
  2598. DeclContext *DC = computeDeclContext(SS, false);
  2599. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
  2600. NotUnknownSpecialization = !Record->hasAnyDependentBases();
  2601. if (!NotUnknownSpecialization) {
  2602. // When the scope specifier can refer to a member of an unknown
  2603. // specialization, we take it as a type name.
  2604. BaseType = CheckTypenameType(ETK_None, SourceLocation(),
  2605. SS.getWithLocInContext(Context),
  2606. *MemberOrBase, IdLoc);
  2607. if (BaseType.isNull())
  2608. return true;
  2609. R.clear();
  2610. R.setLookupName(MemberOrBase);
  2611. }
  2612. }
  2613. // If no results were found, try to correct typos.
  2614. TypoCorrection Corr;
  2615. if (R.empty() && BaseType.isNull() &&
  2616. (Corr = CorrectTypo(
  2617. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  2618. llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
  2619. CTK_ErrorRecovery, ClassDecl))) {
  2620. if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
  2621. // We have found a non-static data member with a similar
  2622. // name to what was typed; complain and initialize that
  2623. // member.
  2624. diagnoseTypo(Corr,
  2625. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  2626. << MemberOrBase << true);
  2627. return BuildMemberInitializer(Member, Init, IdLoc);
  2628. } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
  2629. const CXXBaseSpecifier *DirectBaseSpec;
  2630. const CXXBaseSpecifier *VirtualBaseSpec;
  2631. if (FindBaseInitializer(*this, ClassDecl,
  2632. Context.getTypeDeclType(Type),
  2633. DirectBaseSpec, VirtualBaseSpec)) {
  2634. // We have found a direct or virtual base class with a
  2635. // similar name to what was typed; complain and initialize
  2636. // that base class.
  2637. diagnoseTypo(Corr,
  2638. PDiag(diag::err_mem_init_not_member_or_class_suggest)
  2639. << MemberOrBase << false,
  2640. PDiag() /*Suppress note, we provide our own.*/);
  2641. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
  2642. : VirtualBaseSpec;
  2643. Diag(BaseSpec->getLocStart(),
  2644. diag::note_base_class_specified_here)
  2645. << BaseSpec->getType()
  2646. << BaseSpec->getSourceRange();
  2647. TyD = Type;
  2648. }
  2649. }
  2650. }
  2651. if (!TyD && BaseType.isNull()) {
  2652. Diag(IdLoc, diag::err_mem_init_not_member_or_class)
  2653. << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
  2654. return true;
  2655. }
  2656. }
  2657. if (BaseType.isNull()) {
  2658. BaseType = Context.getTypeDeclType(TyD);
  2659. MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
  2660. if (SS.isSet())
  2661. // FIXME: preserve source range information
  2662. BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
  2663. BaseType);
  2664. }
  2665. }
  2666. if (!TInfo)
  2667. TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
  2668. return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
  2669. }
  2670. /// Checks a member initializer expression for cases where reference (or
  2671. /// pointer) members are bound to by-value parameters (or their addresses).
  2672. static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
  2673. Expr *Init,
  2674. SourceLocation IdLoc) {
  2675. QualType MemberTy = Member->getType();
  2676. // We only handle pointers and references currently.
  2677. // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
  2678. if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
  2679. return;
  2680. const bool IsPointer = MemberTy->isPointerType();
  2681. if (IsPointer) {
  2682. if (const UnaryOperator *Op
  2683. = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
  2684. // The only case we're worried about with pointers requires taking the
  2685. // address.
  2686. if (Op->getOpcode() != UO_AddrOf)
  2687. return;
  2688. Init = Op->getSubExpr();
  2689. } else {
  2690. // We only handle address-of expression initializers for pointers.
  2691. return;
  2692. }
  2693. }
  2694. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
  2695. // We only warn when referring to a non-reference parameter declaration.
  2696. const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
  2697. if (!Parameter || Parameter->getType()->isReferenceType())
  2698. return;
  2699. S.Diag(Init->getExprLoc(),
  2700. IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
  2701. : diag::warn_bind_ref_member_to_parameter)
  2702. << Member << Parameter << Init->getSourceRange();
  2703. } else {
  2704. // Other initializers are fine.
  2705. return;
  2706. }
  2707. S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
  2708. << (unsigned)IsPointer;
  2709. }
  2710. MemInitResult
  2711. Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
  2712. SourceLocation IdLoc) {
  2713. FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
  2714. IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
  2715. assert((DirectMember || IndirectMember) &&
  2716. "Member must be a FieldDecl or IndirectFieldDecl");
  2717. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  2718. return true;
  2719. if (Member->isInvalidDecl())
  2720. return true;
  2721. MultiExprArg Args;
  2722. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  2723. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  2724. } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  2725. Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
  2726. } else {
  2727. // Template instantiation doesn't reconstruct ParenListExprs for us.
  2728. Args = Init;
  2729. }
  2730. SourceRange InitRange = Init->getSourceRange();
  2731. if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
  2732. // Can't check initialization for a member of dependent type or when
  2733. // any of the arguments are type-dependent expressions.
  2734. DiscardCleanupsInEvaluationContext();
  2735. } else {
  2736. bool InitList = false;
  2737. if (isa<InitListExpr>(Init)) {
  2738. InitList = true;
  2739. Args = Init;
  2740. }
  2741. // Initialize the member.
  2742. InitializedEntity MemberEntity =
  2743. DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
  2744. : InitializedEntity::InitializeMember(IndirectMember,
  2745. nullptr);
  2746. InitializationKind Kind =
  2747. InitList ? InitializationKind::CreateDirectList(IdLoc)
  2748. : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
  2749. InitRange.getEnd());
  2750. InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
  2751. ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
  2752. nullptr);
  2753. if (MemberInit.isInvalid())
  2754. return true;
  2755. CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
  2756. // C++11 [class.base.init]p7:
  2757. // The initialization of each base and member constitutes a
  2758. // full-expression.
  2759. MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
  2760. if (MemberInit.isInvalid())
  2761. return true;
  2762. Init = MemberInit.get();
  2763. }
  2764. if (DirectMember) {
  2765. return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
  2766. InitRange.getBegin(), Init,
  2767. InitRange.getEnd());
  2768. } else {
  2769. return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
  2770. InitRange.getBegin(), Init,
  2771. InitRange.getEnd());
  2772. }
  2773. }
  2774. MemInitResult
  2775. Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
  2776. CXXRecordDecl *ClassDecl) {
  2777. SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
  2778. if (!LangOpts.CPlusPlus11)
  2779. return Diag(NameLoc, diag::err_delegating_ctor)
  2780. << TInfo->getTypeLoc().getLocalSourceRange();
  2781. Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
  2782. bool InitList = true;
  2783. MultiExprArg Args = Init;
  2784. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  2785. InitList = false;
  2786. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  2787. }
  2788. SourceRange InitRange = Init->getSourceRange();
  2789. // Initialize the object.
  2790. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
  2791. QualType(ClassDecl->getTypeForDecl(), 0));
  2792. InitializationKind Kind =
  2793. InitList ? InitializationKind::CreateDirectList(NameLoc)
  2794. : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
  2795. InitRange.getEnd());
  2796. InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
  2797. ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
  2798. Args, nullptr);
  2799. if (DelegationInit.isInvalid())
  2800. return true;
  2801. assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
  2802. "Delegating constructor with no target?");
  2803. // C++11 [class.base.init]p7:
  2804. // The initialization of each base and member constitutes a
  2805. // full-expression.
  2806. DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
  2807. InitRange.getBegin());
  2808. if (DelegationInit.isInvalid())
  2809. return true;
  2810. // If we are in a dependent context, template instantiation will
  2811. // perform this type-checking again. Just save the arguments that we
  2812. // received in a ParenListExpr.
  2813. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  2814. // of the information that we have about the base
  2815. // initializer. However, deconstructing the ASTs is a dicey process,
  2816. // and this approach is far more likely to get the corner cases right.
  2817. if (CurContext->isDependentContext())
  2818. DelegationInit = Init;
  2819. return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
  2820. DelegationInit.getAs<Expr>(),
  2821. InitRange.getEnd());
  2822. }
  2823. MemInitResult
  2824. Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
  2825. Expr *Init, CXXRecordDecl *ClassDecl,
  2826. SourceLocation EllipsisLoc) {
  2827. SourceLocation BaseLoc
  2828. = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
  2829. if (!BaseType->isDependentType() && !BaseType->isRecordType())
  2830. return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
  2831. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2832. // C++ [class.base.init]p2:
  2833. // [...] Unless the mem-initializer-id names a nonstatic data
  2834. // member of the constructor's class or a direct or virtual base
  2835. // of that class, the mem-initializer is ill-formed. A
  2836. // mem-initializer-list can initialize a base class using any
  2837. // name that denotes that base class type.
  2838. bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
  2839. SourceRange InitRange = Init->getSourceRange();
  2840. if (EllipsisLoc.isValid()) {
  2841. // This is a pack expansion.
  2842. if (!BaseType->containsUnexpandedParameterPack()) {
  2843. Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
  2844. << SourceRange(BaseLoc, InitRange.getEnd());
  2845. EllipsisLoc = SourceLocation();
  2846. }
  2847. } else {
  2848. // Check for any unexpanded parameter packs.
  2849. if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
  2850. return true;
  2851. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
  2852. return true;
  2853. }
  2854. // Check for direct and virtual base classes.
  2855. const CXXBaseSpecifier *DirectBaseSpec = nullptr;
  2856. const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
  2857. if (!Dependent) {
  2858. if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
  2859. BaseType))
  2860. return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
  2861. FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
  2862. VirtualBaseSpec);
  2863. // C++ [base.class.init]p2:
  2864. // Unless the mem-initializer-id names a nonstatic data member of the
  2865. // constructor's class or a direct or virtual base of that class, the
  2866. // mem-initializer is ill-formed.
  2867. if (!DirectBaseSpec && !VirtualBaseSpec) {
  2868. // If the class has any dependent bases, then it's possible that
  2869. // one of those types will resolve to the same type as
  2870. // BaseType. Therefore, just treat this as a dependent base
  2871. // class initialization. FIXME: Should we try to check the
  2872. // initialization anyway? It seems odd.
  2873. if (ClassDecl->hasAnyDependentBases())
  2874. Dependent = true;
  2875. else
  2876. return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
  2877. << BaseType << Context.getTypeDeclType(ClassDecl)
  2878. << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2879. }
  2880. }
  2881. if (Dependent) {
  2882. DiscardCleanupsInEvaluationContext();
  2883. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  2884. /*IsVirtual=*/false,
  2885. InitRange.getBegin(), Init,
  2886. InitRange.getEnd(), EllipsisLoc);
  2887. }
  2888. // C++ [base.class.init]p2:
  2889. // If a mem-initializer-id is ambiguous because it designates both
  2890. // a direct non-virtual base class and an inherited virtual base
  2891. // class, the mem-initializer is ill-formed.
  2892. if (DirectBaseSpec && VirtualBaseSpec)
  2893. return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
  2894. << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
  2895. const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
  2896. if (!BaseSpec)
  2897. BaseSpec = VirtualBaseSpec;
  2898. // Initialize the base.
  2899. bool InitList = true;
  2900. MultiExprArg Args = Init;
  2901. if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
  2902. InitList = false;
  2903. Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
  2904. }
  2905. InitializedEntity BaseEntity =
  2906. InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
  2907. InitializationKind Kind =
  2908. InitList ? InitializationKind::CreateDirectList(BaseLoc)
  2909. : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
  2910. InitRange.getEnd());
  2911. InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
  2912. ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
  2913. if (BaseInit.isInvalid())
  2914. return true;
  2915. // C++11 [class.base.init]p7:
  2916. // The initialization of each base and member constitutes a
  2917. // full-expression.
  2918. BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
  2919. if (BaseInit.isInvalid())
  2920. return true;
  2921. // If we are in a dependent context, template instantiation will
  2922. // perform this type-checking again. Just save the arguments that we
  2923. // received in a ParenListExpr.
  2924. // FIXME: This isn't quite ideal, since our ASTs don't capture all
  2925. // of the information that we have about the base
  2926. // initializer. However, deconstructing the ASTs is a dicey process,
  2927. // and this approach is far more likely to get the corner cases right.
  2928. if (CurContext->isDependentContext())
  2929. BaseInit = Init;
  2930. return new (Context) CXXCtorInitializer(Context, BaseTInfo,
  2931. BaseSpec->isVirtual(),
  2932. InitRange.getBegin(),
  2933. BaseInit.getAs<Expr>(),
  2934. InitRange.getEnd(), EllipsisLoc);
  2935. }
  2936. // Create a static_cast\<T&&>(expr).
  2937. static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
  2938. if (T.isNull()) T = E->getType();
  2939. QualType TargetType = SemaRef.BuildReferenceType(
  2940. T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
  2941. SourceLocation ExprLoc = E->getLocStart();
  2942. TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
  2943. TargetType, ExprLoc);
  2944. return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  2945. SourceRange(ExprLoc, ExprLoc),
  2946. E->getSourceRange()).get();
  2947. }
  2948. /// ImplicitInitializerKind - How an implicit base or member initializer should
  2949. /// initialize its base or member.
  2950. enum ImplicitInitializerKind {
  2951. IIK_Default,
  2952. IIK_Copy,
  2953. IIK_Move,
  2954. IIK_Inherit
  2955. };
  2956. static bool
  2957. BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  2958. ImplicitInitializerKind ImplicitInitKind,
  2959. CXXBaseSpecifier *BaseSpec,
  2960. bool IsInheritedVirtualBase,
  2961. CXXCtorInitializer *&CXXBaseInit) {
  2962. InitializedEntity InitEntity
  2963. = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
  2964. IsInheritedVirtualBase);
  2965. ExprResult BaseInit;
  2966. switch (ImplicitInitKind) {
  2967. case IIK_Inherit: {
  2968. const CXXRecordDecl *Inherited =
  2969. Constructor->getInheritedConstructor()->getParent();
  2970. const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  2971. if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
  2972. // C++11 [class.inhctor]p8:
  2973. // Each expression in the expression-list is of the form
  2974. // static_cast<T&&>(p), where p is the name of the corresponding
  2975. // constructor parameter and T is the declared type of p.
  2976. SmallVector<Expr*, 16> Args;
  2977. for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
  2978. ParmVarDecl *PD = Constructor->getParamDecl(I);
  2979. ExprResult ArgExpr =
  2980. SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  2981. VK_LValue, SourceLocation());
  2982. if (ArgExpr.isInvalid())
  2983. return true;
  2984. Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
  2985. }
  2986. InitializationKind InitKind = InitializationKind::CreateDirect(
  2987. Constructor->getLocation(), SourceLocation(), SourceLocation());
  2988. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
  2989. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
  2990. break;
  2991. }
  2992. }
  2993. // Fall through.
  2994. case IIK_Default: {
  2995. InitializationKind InitKind
  2996. = InitializationKind::CreateDefault(Constructor->getLocation());
  2997. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  2998. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  2999. break;
  3000. }
  3001. case IIK_Move:
  3002. case IIK_Copy: {
  3003. bool Moving = ImplicitInitKind == IIK_Move;
  3004. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3005. QualType ParamType = Param->getType().getNonReferenceType();
  3006. Expr *CopyCtorArg =
  3007. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3008. SourceLocation(), Param, false,
  3009. Constructor->getLocation(), ParamType,
  3010. VK_LValue, nullptr);
  3011. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
  3012. // Cast to the base class to avoid ambiguities.
  3013. QualType ArgTy =
  3014. SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
  3015. ParamType.getQualifiers());
  3016. if (Moving) {
  3017. CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
  3018. }
  3019. CXXCastPath BasePath;
  3020. BasePath.push_back(BaseSpec);
  3021. CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
  3022. CK_UncheckedDerivedToBase,
  3023. Moving ? VK_XValue : VK_LValue,
  3024. &BasePath).get();
  3025. InitializationKind InitKind
  3026. = InitializationKind::CreateDirect(Constructor->getLocation(),
  3027. SourceLocation(), SourceLocation());
  3028. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3029. BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
  3030. break;
  3031. }
  3032. }
  3033. BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
  3034. if (BaseInit.isInvalid())
  3035. return true;
  3036. CXXBaseInit =
  3037. new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3038. SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
  3039. SourceLocation()),
  3040. BaseSpec->isVirtual(),
  3041. SourceLocation(),
  3042. BaseInit.getAs<Expr>(),
  3043. SourceLocation(),
  3044. SourceLocation());
  3045. return false;
  3046. }
  3047. static bool RefersToRValueRef(Expr *MemRef) {
  3048. ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
  3049. return Referenced->getType()->isRValueReferenceType();
  3050. }
  3051. static bool
  3052. BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
  3053. ImplicitInitializerKind ImplicitInitKind,
  3054. FieldDecl *Field, IndirectFieldDecl *Indirect,
  3055. CXXCtorInitializer *&CXXMemberInit) {
  3056. if (Field->isInvalidDecl())
  3057. return true;
  3058. SourceLocation Loc = Constructor->getLocation();
  3059. if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
  3060. bool Moving = ImplicitInitKind == IIK_Move;
  3061. ParmVarDecl *Param = Constructor->getParamDecl(0);
  3062. QualType ParamType = Param->getType().getNonReferenceType();
  3063. // Suppress copying zero-width bitfields.
  3064. if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
  3065. return false;
  3066. Expr *MemberExprBase =
  3067. DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
  3068. SourceLocation(), Param, false,
  3069. Loc, ParamType, VK_LValue, nullptr);
  3070. SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
  3071. if (Moving) {
  3072. MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
  3073. }
  3074. // Build a reference to this field within the parameter.
  3075. CXXScopeSpec SS;
  3076. LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
  3077. Sema::LookupMemberName);
  3078. MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
  3079. : cast<ValueDecl>(Field), AS_public);
  3080. MemberLookup.resolveKind();
  3081. ExprResult CtorArg
  3082. = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
  3083. ParamType, Loc,
  3084. /*IsArrow=*/false,
  3085. SS,
  3086. /*TemplateKWLoc=*/SourceLocation(),
  3087. /*FirstQualifierInScope=*/nullptr,
  3088. MemberLookup,
  3089. /*TemplateArgs=*/nullptr);
  3090. if (CtorArg.isInvalid())
  3091. return true;
  3092. // C++11 [class.copy]p15:
  3093. // - if a member m has rvalue reference type T&&, it is direct-initialized
  3094. // with static_cast<T&&>(x.m);
  3095. if (RefersToRValueRef(CtorArg.get())) {
  3096. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3097. }
  3098. // When the field we are copying is an array, create index variables for
  3099. // each dimension of the array. We use these index variables to subscript
  3100. // the source array, and other clients (e.g., CodeGen) will perform the
  3101. // necessary iteration with these index variables.
  3102. SmallVector<VarDecl *, 4> IndexVariables;
  3103. QualType BaseType = Field->getType();
  3104. QualType SizeType = SemaRef.Context.getSizeType();
  3105. bool InitializingArray = false;
  3106. while (const ConstantArrayType *Array
  3107. = SemaRef.Context.getAsConstantArrayType(BaseType)) {
  3108. InitializingArray = true;
  3109. // Create the iteration variable for this array index.
  3110. IdentifierInfo *IterationVarName = nullptr;
  3111. {
  3112. SmallString<8> Str;
  3113. llvm::raw_svector_ostream OS(Str);
  3114. OS << "__i" << IndexVariables.size();
  3115. IterationVarName = &SemaRef.Context.Idents.get(OS.str());
  3116. }
  3117. VarDecl *IterationVar
  3118. = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
  3119. IterationVarName, SizeType,
  3120. SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  3121. SC_None);
  3122. IndexVariables.push_back(IterationVar);
  3123. // Create a reference to the iteration variable.
  3124. ExprResult IterationVarRef
  3125. = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
  3126. assert(!IterationVarRef.isInvalid() &&
  3127. "Reference to invented variable cannot fail!");
  3128. IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
  3129. assert(!IterationVarRef.isInvalid() &&
  3130. "Conversion of invented variable cannot fail!");
  3131. // Subscript the array with this iteration variable.
  3132. CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
  3133. IterationVarRef.get(),
  3134. Loc);
  3135. if (CtorArg.isInvalid())
  3136. return true;
  3137. BaseType = Array->getElementType();
  3138. }
  3139. // The array subscript expression is an lvalue, which is wrong for moving.
  3140. if (Moving && InitializingArray)
  3141. CtorArg = CastForMoving(SemaRef, CtorArg.get());
  3142. // Construct the entity that we will be initializing. For an array, this
  3143. // will be first element in the array, which may require several levels
  3144. // of array-subscript entities.
  3145. SmallVector<InitializedEntity, 4> Entities;
  3146. Entities.reserve(1 + IndexVariables.size());
  3147. if (Indirect)
  3148. Entities.push_back(InitializedEntity::InitializeMember(Indirect));
  3149. else
  3150. Entities.push_back(InitializedEntity::InitializeMember(Field));
  3151. for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
  3152. Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
  3153. 0,
  3154. Entities.back()));
  3155. // Direct-initialize to use the copy constructor.
  3156. InitializationKind InitKind =
  3157. InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
  3158. Expr *CtorArgE = CtorArg.getAs<Expr>();
  3159. InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
  3160. CtorArgE);
  3161. ExprResult MemberInit
  3162. = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
  3163. MultiExprArg(&CtorArgE, 1));
  3164. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3165. if (MemberInit.isInvalid())
  3166. return true;
  3167. if (Indirect) {
  3168. assert(IndexVariables.size() == 0 &&
  3169. "Indirect field improperly initialized");
  3170. CXXMemberInit
  3171. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
  3172. Loc, Loc,
  3173. MemberInit.getAs<Expr>(),
  3174. Loc);
  3175. } else
  3176. CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
  3177. Loc, MemberInit.getAs<Expr>(),
  3178. Loc,
  3179. IndexVariables.data(),
  3180. IndexVariables.size());
  3181. return false;
  3182. }
  3183. assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
  3184. "Unhandled implicit init kind!");
  3185. QualType FieldBaseElementType =
  3186. SemaRef.Context.getBaseElementType(Field->getType());
  3187. if (FieldBaseElementType->isRecordType()) {
  3188. InitializedEntity InitEntity
  3189. = Indirect? InitializedEntity::InitializeMember(Indirect)
  3190. : InitializedEntity::InitializeMember(Field);
  3191. InitializationKind InitKind =
  3192. InitializationKind::CreateDefault(Loc);
  3193. InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
  3194. ExprResult MemberInit =
  3195. InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
  3196. MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
  3197. if (MemberInit.isInvalid())
  3198. return true;
  3199. if (Indirect)
  3200. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3201. Indirect, Loc,
  3202. Loc,
  3203. MemberInit.get(),
  3204. Loc);
  3205. else
  3206. CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
  3207. Field, Loc, Loc,
  3208. MemberInit.get(),
  3209. Loc);
  3210. return false;
  3211. }
  3212. if (!Field->getParent()->isUnion()) {
  3213. if (FieldBaseElementType->isReferenceType()) {
  3214. SemaRef.Diag(Constructor->getLocation(),
  3215. diag::err_uninitialized_member_in_ctor)
  3216. << (int)Constructor->isImplicit()
  3217. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3218. << 0 << Field->getDeclName();
  3219. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3220. return true;
  3221. }
  3222. if (FieldBaseElementType.isConstQualified()) {
  3223. SemaRef.Diag(Constructor->getLocation(),
  3224. diag::err_uninitialized_member_in_ctor)
  3225. << (int)Constructor->isImplicit()
  3226. << SemaRef.Context.getTagDeclType(Constructor->getParent())
  3227. << 1 << Field->getDeclName();
  3228. SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
  3229. return true;
  3230. }
  3231. }
  3232. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  3233. FieldBaseElementType->isObjCRetainableType() &&
  3234. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
  3235. FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
  3236. // ARC:
  3237. // Default-initialize Objective-C pointers to NULL.
  3238. CXXMemberInit
  3239. = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
  3240. Loc, Loc,
  3241. new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
  3242. Loc);
  3243. return false;
  3244. }
  3245. // Nothing to initialize.
  3246. CXXMemberInit = nullptr;
  3247. return false;
  3248. }
  3249. namespace {
  3250. struct BaseAndFieldInfo {
  3251. Sema &S;
  3252. CXXConstructorDecl *Ctor;
  3253. bool AnyErrorsInInits;
  3254. ImplicitInitializerKind IIK;
  3255. llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
  3256. SmallVector<CXXCtorInitializer*, 8> AllToInit;
  3257. llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
  3258. BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
  3259. : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
  3260. bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
  3261. if (Generated && Ctor->isCopyConstructor())
  3262. IIK = IIK_Copy;
  3263. else if (Generated && Ctor->isMoveConstructor())
  3264. IIK = IIK_Move;
  3265. else if (Ctor->getInheritedConstructor())
  3266. IIK = IIK_Inherit;
  3267. else
  3268. IIK = IIK_Default;
  3269. }
  3270. bool isImplicitCopyOrMove() const {
  3271. switch (IIK) {
  3272. case IIK_Copy:
  3273. case IIK_Move:
  3274. return true;
  3275. case IIK_Default:
  3276. case IIK_Inherit:
  3277. return false;
  3278. }
  3279. llvm_unreachable("Invalid ImplicitInitializerKind!");
  3280. }
  3281. bool addFieldInitializer(CXXCtorInitializer *Init) {
  3282. AllToInit.push_back(Init);
  3283. // Check whether this initializer makes the field "used".
  3284. if (Init->getInit()->HasSideEffects(S.Context))
  3285. S.UnusedPrivateFields.remove(Init->getAnyMember());
  3286. return false;
  3287. }
  3288. bool isInactiveUnionMember(FieldDecl *Field) {
  3289. RecordDecl *Record = Field->getParent();
  3290. if (!Record->isUnion())
  3291. return false;
  3292. if (FieldDecl *Active =
  3293. ActiveUnionMember.lookup(Record->getCanonicalDecl()))
  3294. return Active != Field->getCanonicalDecl();
  3295. // In an implicit copy or move constructor, ignore any in-class initializer.
  3296. if (isImplicitCopyOrMove())
  3297. return true;
  3298. // If there's no explicit initialization, the field is active only if it
  3299. // has an in-class initializer...
  3300. if (Field->hasInClassInitializer())
  3301. return false;
  3302. // ... or it's an anonymous struct or union whose class has an in-class
  3303. // initializer.
  3304. if (!Field->isAnonymousStructOrUnion())
  3305. return true;
  3306. CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
  3307. return !FieldRD->hasInClassInitializer();
  3308. }
  3309. /// \brief Determine whether the given field is, or is within, a union member
  3310. /// that is inactive (because there was an initializer given for a different
  3311. /// member of the union, or because the union was not initialized at all).
  3312. bool isWithinInactiveUnionMember(FieldDecl *Field,
  3313. IndirectFieldDecl *Indirect) {
  3314. if (!Indirect)
  3315. return isInactiveUnionMember(Field);
  3316. for (auto *C : Indirect->chain()) {
  3317. FieldDecl *Field = dyn_cast<FieldDecl>(C);
  3318. if (Field && isInactiveUnionMember(Field))
  3319. return true;
  3320. }
  3321. return false;
  3322. }
  3323. };
  3324. }
  3325. /// \brief Determine whether the given type is an incomplete or zero-lenfgth
  3326. /// array type.
  3327. static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
  3328. if (T->isIncompleteArrayType())
  3329. return true;
  3330. while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
  3331. if (!ArrayT->getSize())
  3332. return true;
  3333. T = ArrayT->getElementType();
  3334. }
  3335. return false;
  3336. }
  3337. static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
  3338. FieldDecl *Field,
  3339. IndirectFieldDecl *Indirect = nullptr) {
  3340. if (Field->isInvalidDecl())
  3341. return false;
  3342. // Overwhelmingly common case: we have a direct initializer for this field.
  3343. if (CXXCtorInitializer *Init =
  3344. Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
  3345. return Info.addFieldInitializer(Init);
  3346. // C++11 [class.base.init]p8:
  3347. // if the entity is a non-static data member that has a
  3348. // brace-or-equal-initializer and either
  3349. // -- the constructor's class is a union and no other variant member of that
  3350. // union is designated by a mem-initializer-id or
  3351. // -- the constructor's class is not a union, and, if the entity is a member
  3352. // of an anonymous union, no other member of that union is designated by
  3353. // a mem-initializer-id,
  3354. // the entity is initialized as specified in [dcl.init].
  3355. //
  3356. // We also apply the same rules to handle anonymous structs within anonymous
  3357. // unions.
  3358. if (Info.isWithinInactiveUnionMember(Field, Indirect))
  3359. return false;
  3360. if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
  3361. ExprResult DIE =
  3362. SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
  3363. if (DIE.isInvalid())
  3364. return true;
  3365. CXXCtorInitializer *Init;
  3366. if (Indirect)
  3367. Init = new (SemaRef.Context)
  3368. CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
  3369. SourceLocation(), DIE.get(), SourceLocation());
  3370. else
  3371. Init = new (SemaRef.Context)
  3372. CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
  3373. SourceLocation(), DIE.get(), SourceLocation());
  3374. return Info.addFieldInitializer(Init);
  3375. }
  3376. // Don't initialize incomplete or zero-length arrays.
  3377. if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
  3378. return false;
  3379. // Don't try to build an implicit initializer if there were semantic
  3380. // errors in any of the initializers (and therefore we might be
  3381. // missing some that the user actually wrote).
  3382. if (Info.AnyErrorsInInits)
  3383. return false;
  3384. CXXCtorInitializer *Init = nullptr;
  3385. if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
  3386. Indirect, Init))
  3387. return true;
  3388. if (!Init)
  3389. return false;
  3390. return Info.addFieldInitializer(Init);
  3391. }
  3392. bool
  3393. Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
  3394. CXXCtorInitializer *Initializer) {
  3395. assert(Initializer->isDelegatingInitializer());
  3396. Constructor->setNumCtorInitializers(1);
  3397. CXXCtorInitializer **initializer =
  3398. new (Context) CXXCtorInitializer*[1];
  3399. memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
  3400. Constructor->setCtorInitializers(initializer);
  3401. if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
  3402. MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
  3403. DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
  3404. }
  3405. DelegatingCtorDecls.push_back(Constructor);
  3406. DiagnoseUninitializedFields(*this, Constructor);
  3407. return false;
  3408. }
  3409. bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
  3410. ArrayRef<CXXCtorInitializer *> Initializers) {
  3411. if (Constructor->isDependentContext()) {
  3412. // Just store the initializers as written, they will be checked during
  3413. // instantiation.
  3414. if (!Initializers.empty()) {
  3415. Constructor->setNumCtorInitializers(Initializers.size());
  3416. CXXCtorInitializer **baseOrMemberInitializers =
  3417. new (Context) CXXCtorInitializer*[Initializers.size()];
  3418. memcpy(baseOrMemberInitializers, Initializers.data(),
  3419. Initializers.size() * sizeof(CXXCtorInitializer*));
  3420. Constructor->setCtorInitializers(baseOrMemberInitializers);
  3421. }
  3422. // Let template instantiation know whether we had errors.
  3423. if (AnyErrors)
  3424. Constructor->setInvalidDecl();
  3425. return false;
  3426. }
  3427. BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
  3428. // We need to build the initializer AST according to order of construction
  3429. // and not what user specified in the Initializers list.
  3430. CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
  3431. if (!ClassDecl)
  3432. return true;
  3433. bool HadError = false;
  3434. for (unsigned i = 0; i < Initializers.size(); i++) {
  3435. CXXCtorInitializer *Member = Initializers[i];
  3436. if (Member->isBaseInitializer())
  3437. Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
  3438. else {
  3439. Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
  3440. if (IndirectFieldDecl *F = Member->getIndirectMember()) {
  3441. for (auto *C : F->chain()) {
  3442. FieldDecl *FD = dyn_cast<FieldDecl>(C);
  3443. if (FD && FD->getParent()->isUnion())
  3444. Info.ActiveUnionMember.insert(std::make_pair(
  3445. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  3446. }
  3447. } else if (FieldDecl *FD = Member->getMember()) {
  3448. if (FD->getParent()->isUnion())
  3449. Info.ActiveUnionMember.insert(std::make_pair(
  3450. FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
  3451. }
  3452. }
  3453. }
  3454. // Keep track of the direct virtual bases.
  3455. llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
  3456. for (auto &I : ClassDecl->bases()) {
  3457. if (I.isVirtual())
  3458. DirectVBases.insert(&I);
  3459. }
  3460. // Push virtual bases before others.
  3461. for (auto &VBase : ClassDecl->vbases()) {
  3462. if (CXXCtorInitializer *Value
  3463. = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
  3464. // [class.base.init]p7, per DR257:
  3465. // A mem-initializer where the mem-initializer-id names a virtual base
  3466. // class is ignored during execution of a constructor of any class that
  3467. // is not the most derived class.
  3468. if (ClassDecl->isAbstract()) {
  3469. // FIXME: Provide a fixit to remove the base specifier. This requires
  3470. // tracking the location of the associated comma for a base specifier.
  3471. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
  3472. << VBase.getType() << ClassDecl;
  3473. DiagnoseAbstractType(ClassDecl);
  3474. }
  3475. Info.AllToInit.push_back(Value);
  3476. } else if (!AnyErrors && !ClassDecl->isAbstract()) {
  3477. // [class.base.init]p8, per DR257:
  3478. // If a given [...] base class is not named by a mem-initializer-id
  3479. // [...] and the entity is not a virtual base class of an abstract
  3480. // class, then [...] the entity is default-initialized.
  3481. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
  3482. CXXCtorInitializer *CXXBaseInit;
  3483. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  3484. &VBase, IsInheritedVirtualBase,
  3485. CXXBaseInit)) {
  3486. HadError = true;
  3487. continue;
  3488. }
  3489. Info.AllToInit.push_back(CXXBaseInit);
  3490. }
  3491. }
  3492. // Non-virtual bases.
  3493. for (auto &Base : ClassDecl->bases()) {
  3494. // Virtuals are in the virtual base list and already constructed.
  3495. if (Base.isVirtual())
  3496. continue;
  3497. if (CXXCtorInitializer *Value
  3498. = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
  3499. Info.AllToInit.push_back(Value);
  3500. } else if (!AnyErrors) {
  3501. CXXCtorInitializer *CXXBaseInit;
  3502. if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
  3503. &Base, /*IsInheritedVirtualBase=*/false,
  3504. CXXBaseInit)) {
  3505. HadError = true;
  3506. continue;
  3507. }
  3508. Info.AllToInit.push_back(CXXBaseInit);
  3509. }
  3510. }
  3511. // Fields.
  3512. for (auto *Mem : ClassDecl->decls()) {
  3513. if (auto *F = dyn_cast<FieldDecl>(Mem)) {
  3514. // C++ [class.bit]p2:
  3515. // A declaration for a bit-field that omits the identifier declares an
  3516. // unnamed bit-field. Unnamed bit-fields are not members and cannot be
  3517. // initialized.
  3518. if (F->isUnnamedBitfield())
  3519. continue;
  3520. // If we're not generating the implicit copy/move constructor, then we'll
  3521. // handle anonymous struct/union fields based on their individual
  3522. // indirect fields.
  3523. if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
  3524. continue;
  3525. if (CollectFieldInitializer(*this, Info, F))
  3526. HadError = true;
  3527. continue;
  3528. }
  3529. // Beyond this point, we only consider default initialization.
  3530. if (Info.isImplicitCopyOrMove())
  3531. continue;
  3532. if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
  3533. if (F->getType()->isIncompleteArrayType()) {
  3534. assert(ClassDecl->hasFlexibleArrayMember() &&
  3535. "Incomplete array type is not valid");
  3536. continue;
  3537. }
  3538. // Initialize each field of an anonymous struct individually.
  3539. if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
  3540. HadError = true;
  3541. continue;
  3542. }
  3543. }
  3544. unsigned NumInitializers = Info.AllToInit.size();
  3545. if (NumInitializers > 0) {
  3546. Constructor->setNumCtorInitializers(NumInitializers);
  3547. CXXCtorInitializer **baseOrMemberInitializers =
  3548. new (Context) CXXCtorInitializer*[NumInitializers];
  3549. memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
  3550. NumInitializers * sizeof(CXXCtorInitializer*));
  3551. Constructor->setCtorInitializers(baseOrMemberInitializers);
  3552. // Constructors implicitly reference the base and member
  3553. // destructors.
  3554. MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
  3555. Constructor->getParent());
  3556. }
  3557. return HadError;
  3558. }
  3559. static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
  3560. if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
  3561. const RecordDecl *RD = RT->getDecl();
  3562. if (RD->isAnonymousStructOrUnion()) {
  3563. for (auto *Field : RD->fields())
  3564. PopulateKeysForFields(Field, IdealInits);
  3565. return;
  3566. }
  3567. }
  3568. IdealInits.push_back(Field->getCanonicalDecl());
  3569. }
  3570. static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
  3571. return Context.getCanonicalType(BaseType).getTypePtr();
  3572. }
  3573. static const void *GetKeyForMember(ASTContext &Context,
  3574. CXXCtorInitializer *Member) {
  3575. if (!Member->isAnyMemberInitializer())
  3576. return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
  3577. return Member->getAnyMember()->getCanonicalDecl();
  3578. }
  3579. static void DiagnoseBaseOrMemInitializerOrder(
  3580. Sema &SemaRef, const CXXConstructorDecl *Constructor,
  3581. ArrayRef<CXXCtorInitializer *> Inits) {
  3582. if (Constructor->getDeclContext()->isDependentContext())
  3583. return;
  3584. // Don't check initializers order unless the warning is enabled at the
  3585. // location of at least one initializer.
  3586. bool ShouldCheckOrder = false;
  3587. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  3588. CXXCtorInitializer *Init = Inits[InitIndex];
  3589. if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
  3590. Init->getSourceLocation())) {
  3591. ShouldCheckOrder = true;
  3592. break;
  3593. }
  3594. }
  3595. if (!ShouldCheckOrder)
  3596. return;
  3597. // Build the list of bases and members in the order that they'll
  3598. // actually be initialized. The explicit initializers should be in
  3599. // this same order but may be missing things.
  3600. SmallVector<const void*, 32> IdealInitKeys;
  3601. const CXXRecordDecl *ClassDecl = Constructor->getParent();
  3602. // 1. Virtual bases.
  3603. for (const auto &VBase : ClassDecl->vbases())
  3604. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
  3605. // 2. Non-virtual bases.
  3606. for (const auto &Base : ClassDecl->bases()) {
  3607. if (Base.isVirtual())
  3608. continue;
  3609. IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
  3610. }
  3611. // 3. Direct fields.
  3612. for (auto *Field : ClassDecl->fields()) {
  3613. if (Field->isUnnamedBitfield())
  3614. continue;
  3615. PopulateKeysForFields(Field, IdealInitKeys);
  3616. }
  3617. unsigned NumIdealInits = IdealInitKeys.size();
  3618. unsigned IdealIndex = 0;
  3619. CXXCtorInitializer *PrevInit = nullptr;
  3620. for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
  3621. CXXCtorInitializer *Init = Inits[InitIndex];
  3622. const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
  3623. // Scan forward to try to find this initializer in the idealized
  3624. // initializers list.
  3625. for (; IdealIndex != NumIdealInits; ++IdealIndex)
  3626. if (InitKey == IdealInitKeys[IdealIndex])
  3627. break;
  3628. // If we didn't find this initializer, it must be because we
  3629. // scanned past it on a previous iteration. That can only
  3630. // happen if we're out of order; emit a warning.
  3631. if (IdealIndex == NumIdealInits && PrevInit) {
  3632. Sema::SemaDiagnosticBuilder D =
  3633. SemaRef.Diag(PrevInit->getSourceLocation(),
  3634. diag::warn_initializer_out_of_order);
  3635. if (PrevInit->isAnyMemberInitializer())
  3636. D << 0 << PrevInit->getAnyMember()->getDeclName();
  3637. else
  3638. D << 1 << PrevInit->getTypeSourceInfo()->getType();
  3639. if (Init->isAnyMemberInitializer())
  3640. D << 0 << Init->getAnyMember()->getDeclName();
  3641. else
  3642. D << 1 << Init->getTypeSourceInfo()->getType();
  3643. // Move back to the initializer's location in the ideal list.
  3644. for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
  3645. if (InitKey == IdealInitKeys[IdealIndex])
  3646. break;
  3647. assert(IdealIndex != NumIdealInits &&
  3648. "initializer not found in initializer list");
  3649. }
  3650. PrevInit = Init;
  3651. }
  3652. }
  3653. namespace {
  3654. bool CheckRedundantInit(Sema &S,
  3655. CXXCtorInitializer *Init,
  3656. CXXCtorInitializer *&PrevInit) {
  3657. if (!PrevInit) {
  3658. PrevInit = Init;
  3659. return false;
  3660. }
  3661. if (FieldDecl *Field = Init->getAnyMember())
  3662. S.Diag(Init->getSourceLocation(),
  3663. diag::err_multiple_mem_initialization)
  3664. << Field->getDeclName()
  3665. << Init->getSourceRange();
  3666. else {
  3667. const Type *BaseClass = Init->getBaseClass();
  3668. assert(BaseClass && "neither field nor base");
  3669. S.Diag(Init->getSourceLocation(),
  3670. diag::err_multiple_base_initialization)
  3671. << QualType(BaseClass, 0)
  3672. << Init->getSourceRange();
  3673. }
  3674. S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
  3675. << 0 << PrevInit->getSourceRange();
  3676. return true;
  3677. }
  3678. typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
  3679. typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
  3680. bool CheckRedundantUnionInit(Sema &S,
  3681. CXXCtorInitializer *Init,
  3682. RedundantUnionMap &Unions) {
  3683. FieldDecl *Field = Init->getAnyMember();
  3684. RecordDecl *Parent = Field->getParent();
  3685. NamedDecl *Child = Field;
  3686. while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
  3687. if (Parent->isUnion()) {
  3688. UnionEntry &En = Unions[Parent];
  3689. if (En.first && En.first != Child) {
  3690. S.Diag(Init->getSourceLocation(),
  3691. diag::err_multiple_mem_union_initialization)
  3692. << Field->getDeclName()
  3693. << Init->getSourceRange();
  3694. S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
  3695. << 0 << En.second->getSourceRange();
  3696. return true;
  3697. }
  3698. if (!En.first) {
  3699. En.first = Child;
  3700. En.second = Init;
  3701. }
  3702. if (!Parent->isAnonymousStructOrUnion())
  3703. return false;
  3704. }
  3705. Child = Parent;
  3706. Parent = cast<RecordDecl>(Parent->getDeclContext());
  3707. }
  3708. return false;
  3709. }
  3710. }
  3711. /// ActOnMemInitializers - Handle the member initializers for a constructor.
  3712. void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
  3713. SourceLocation ColonLoc,
  3714. ArrayRef<CXXCtorInitializer*> MemInits,
  3715. bool AnyErrors) {
  3716. if (!ConstructorDecl)
  3717. return;
  3718. AdjustDeclIfTemplate(ConstructorDecl);
  3719. CXXConstructorDecl *Constructor
  3720. = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  3721. if (!Constructor) {
  3722. Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
  3723. return;
  3724. }
  3725. // Mapping for the duplicate initializers check.
  3726. // For member initializers, this is keyed with a FieldDecl*.
  3727. // For base initializers, this is keyed with a Type*.
  3728. llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
  3729. // Mapping for the inconsistent anonymous-union initializers check.
  3730. RedundantUnionMap MemberUnions;
  3731. bool HadError = false;
  3732. for (unsigned i = 0; i < MemInits.size(); i++) {
  3733. CXXCtorInitializer *Init = MemInits[i];
  3734. // Set the source order index.
  3735. Init->setSourceOrder(i);
  3736. if (Init->isAnyMemberInitializer()) {
  3737. const void *Key = GetKeyForMember(Context, Init);
  3738. if (CheckRedundantInit(*this, Init, Members[Key]) ||
  3739. CheckRedundantUnionInit(*this, Init, MemberUnions))
  3740. HadError = true;
  3741. } else if (Init->isBaseInitializer()) {
  3742. const void *Key = GetKeyForMember(Context, Init);
  3743. if (CheckRedundantInit(*this, Init, Members[Key]))
  3744. HadError = true;
  3745. } else {
  3746. assert(Init->isDelegatingInitializer());
  3747. // This must be the only initializer
  3748. if (MemInits.size() != 1) {
  3749. Diag(Init->getSourceLocation(),
  3750. diag::err_delegating_initializer_alone)
  3751. << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
  3752. // We will treat this as being the only initializer.
  3753. }
  3754. SetDelegatingInitializer(Constructor, MemInits[i]);
  3755. // Return immediately as the initializer is set.
  3756. return;
  3757. }
  3758. }
  3759. if (HadError)
  3760. return;
  3761. DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
  3762. SetCtorInitializers(Constructor, AnyErrors, MemInits);
  3763. DiagnoseUninitializedFields(*this, Constructor);
  3764. }
  3765. void
  3766. Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
  3767. CXXRecordDecl *ClassDecl) {
  3768. // Ignore dependent contexts. Also ignore unions, since their members never
  3769. // have destructors implicitly called.
  3770. if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
  3771. return;
  3772. // FIXME: all the access-control diagnostics are positioned on the
  3773. // field/base declaration. That's probably good; that said, the
  3774. // user might reasonably want to know why the destructor is being
  3775. // emitted, and we currently don't say.
  3776. // Non-static data members.
  3777. for (auto *Field : ClassDecl->fields()) {
  3778. if (Field->isInvalidDecl())
  3779. continue;
  3780. // Don't destroy incomplete or zero-length arrays.
  3781. if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
  3782. continue;
  3783. QualType FieldType = Context.getBaseElementType(Field->getType());
  3784. const RecordType* RT = FieldType->getAs<RecordType>();
  3785. if (!RT)
  3786. continue;
  3787. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  3788. if (FieldClassDecl->isInvalidDecl())
  3789. continue;
  3790. if (FieldClassDecl->hasIrrelevantDestructor())
  3791. continue;
  3792. // The destructor for an implicit anonymous union member is never invoked.
  3793. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  3794. continue;
  3795. CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
  3796. assert(Dtor && "No dtor found for FieldClassDecl!");
  3797. CheckDestructorAccess(Field->getLocation(), Dtor,
  3798. PDiag(diag::err_access_dtor_field)
  3799. << Field->getDeclName()
  3800. << FieldType);
  3801. MarkFunctionReferenced(Location, Dtor);
  3802. DiagnoseUseOfDecl(Dtor, Location);
  3803. }
  3804. llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
  3805. // Bases.
  3806. for (const auto &Base : ClassDecl->bases()) {
  3807. // Bases are always records in a well-formed non-dependent class.
  3808. const RecordType *RT = Base.getType()->getAs<RecordType>();
  3809. // Remember direct virtual bases.
  3810. if (Base.isVirtual())
  3811. DirectVirtualBases.insert(RT);
  3812. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  3813. // If our base class is invalid, we probably can't get its dtor anyway.
  3814. if (BaseClassDecl->isInvalidDecl())
  3815. continue;
  3816. if (BaseClassDecl->hasIrrelevantDestructor())
  3817. continue;
  3818. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  3819. assert(Dtor && "No dtor found for BaseClassDecl!");
  3820. // FIXME: caret should be on the start of the class name
  3821. CheckDestructorAccess(Base.getLocStart(), Dtor,
  3822. PDiag(diag::err_access_dtor_base)
  3823. << Base.getType()
  3824. << Base.getSourceRange(),
  3825. Context.getTypeDeclType(ClassDecl));
  3826. MarkFunctionReferenced(Location, Dtor);
  3827. DiagnoseUseOfDecl(Dtor, Location);
  3828. }
  3829. // Virtual bases.
  3830. for (const auto &VBase : ClassDecl->vbases()) {
  3831. // Bases are always records in a well-formed non-dependent class.
  3832. const RecordType *RT = VBase.getType()->castAs<RecordType>();
  3833. // Ignore direct virtual bases.
  3834. if (DirectVirtualBases.count(RT))
  3835. continue;
  3836. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  3837. // If our base class is invalid, we probably can't get its dtor anyway.
  3838. if (BaseClassDecl->isInvalidDecl())
  3839. continue;
  3840. if (BaseClassDecl->hasIrrelevantDestructor())
  3841. continue;
  3842. CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
  3843. assert(Dtor && "No dtor found for BaseClassDecl!");
  3844. if (CheckDestructorAccess(
  3845. ClassDecl->getLocation(), Dtor,
  3846. PDiag(diag::err_access_dtor_vbase)
  3847. << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
  3848. Context.getTypeDeclType(ClassDecl)) ==
  3849. AR_accessible) {
  3850. CheckDerivedToBaseConversion(
  3851. Context.getTypeDeclType(ClassDecl), VBase.getType(),
  3852. diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
  3853. SourceRange(), DeclarationName(), nullptr);
  3854. }
  3855. MarkFunctionReferenced(Location, Dtor);
  3856. DiagnoseUseOfDecl(Dtor, Location);
  3857. }
  3858. }
  3859. void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
  3860. if (!CDtorDecl)
  3861. return;
  3862. if (CXXConstructorDecl *Constructor
  3863. = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
  3864. SetCtorInitializers(Constructor, /*AnyErrors=*/false);
  3865. DiagnoseUninitializedFields(*this, Constructor);
  3866. }
  3867. }
  3868. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  3869. unsigned DiagID, AbstractDiagSelID SelID) {
  3870. class NonAbstractTypeDiagnoser : public TypeDiagnoser {
  3871. unsigned DiagID;
  3872. AbstractDiagSelID SelID;
  3873. public:
  3874. NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
  3875. : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
  3876. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  3877. if (Suppressed) return;
  3878. if (SelID == -1)
  3879. S.Diag(Loc, DiagID) << T;
  3880. else
  3881. S.Diag(Loc, DiagID) << SelID << T;
  3882. }
  3883. } Diagnoser(DiagID, SelID);
  3884. return RequireNonAbstractType(Loc, T, Diagnoser);
  3885. }
  3886. bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
  3887. TypeDiagnoser &Diagnoser) {
  3888. if (!getLangOpts().CPlusPlus)
  3889. return false;
  3890. if (const ArrayType *AT = Context.getAsArrayType(T))
  3891. return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
  3892. if (const PointerType *PT = T->getAs<PointerType>()) {
  3893. // Find the innermost pointer type.
  3894. while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
  3895. PT = T;
  3896. if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
  3897. return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
  3898. }
  3899. const RecordType *RT = T->getAs<RecordType>();
  3900. if (!RT)
  3901. return false;
  3902. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  3903. // We can't answer whether something is abstract until it has a
  3904. // definition. If it's currently being defined, we'll walk back
  3905. // over all the declarations when we have a full definition.
  3906. const CXXRecordDecl *Def = RD->getDefinition();
  3907. if (!Def || Def->isBeingDefined())
  3908. return false;
  3909. if (!RD->isAbstract())
  3910. return false;
  3911. Diagnoser.diagnose(*this, Loc, T);
  3912. DiagnoseAbstractType(RD);
  3913. return true;
  3914. }
  3915. void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
  3916. // Check if we've already emitted the list of pure virtual functions
  3917. // for this class.
  3918. if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
  3919. return;
  3920. // If the diagnostic is suppressed, don't emit the notes. We're only
  3921. // going to emit them once, so try to attach them to a diagnostic we're
  3922. // actually going to show.
  3923. if (Diags.isLastDiagnosticIgnored())
  3924. return;
  3925. CXXFinalOverriderMap FinalOverriders;
  3926. RD->getFinalOverriders(FinalOverriders);
  3927. // Keep a set of seen pure methods so we won't diagnose the same method
  3928. // more than once.
  3929. llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
  3930. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  3931. MEnd = FinalOverriders.end();
  3932. M != MEnd;
  3933. ++M) {
  3934. for (OverridingMethods::iterator SO = M->second.begin(),
  3935. SOEnd = M->second.end();
  3936. SO != SOEnd; ++SO) {
  3937. // C++ [class.abstract]p4:
  3938. // A class is abstract if it contains or inherits at least one
  3939. // pure virtual function for which the final overrider is pure
  3940. // virtual.
  3941. //
  3942. if (SO->second.size() != 1)
  3943. continue;
  3944. if (!SO->second.front().Method->isPure())
  3945. continue;
  3946. if (!SeenPureMethods.insert(SO->second.front().Method).second)
  3947. continue;
  3948. Diag(SO->second.front().Method->getLocation(),
  3949. diag::note_pure_virtual_function)
  3950. << SO->second.front().Method->getDeclName() << RD->getDeclName();
  3951. }
  3952. }
  3953. if (!PureVirtualClassDiagSet)
  3954. PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
  3955. PureVirtualClassDiagSet->insert(RD);
  3956. }
  3957. namespace {
  3958. struct AbstractUsageInfo {
  3959. Sema &S;
  3960. CXXRecordDecl *Record;
  3961. CanQualType AbstractType;
  3962. bool Invalid;
  3963. AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
  3964. : S(S), Record(Record),
  3965. AbstractType(S.Context.getCanonicalType(
  3966. S.Context.getTypeDeclType(Record))),
  3967. Invalid(false) {}
  3968. void DiagnoseAbstractType() {
  3969. if (Invalid) return;
  3970. S.DiagnoseAbstractType(Record);
  3971. Invalid = true;
  3972. }
  3973. void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
  3974. };
  3975. struct CheckAbstractUsage {
  3976. AbstractUsageInfo &Info;
  3977. const NamedDecl *Ctx;
  3978. CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
  3979. : Info(Info), Ctx(Ctx) {}
  3980. void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3981. switch (TL.getTypeLocClass()) {
  3982. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  3983. #define TYPELOC(CLASS, PARENT) \
  3984. case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
  3985. #include "clang/AST/TypeLocNodes.def"
  3986. }
  3987. }
  3988. void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3989. Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
  3990. for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
  3991. if (!TL.getParam(I))
  3992. continue;
  3993. TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
  3994. if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
  3995. }
  3996. }
  3997. void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  3998. Visit(TL.getElementLoc(), Sema::AbstractArrayType);
  3999. }
  4000. void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4001. // Visit the type parameters from a permissive context.
  4002. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
  4003. TemplateArgumentLoc TAL = TL.getArgLoc(I);
  4004. if (TAL.getArgument().getKind() == TemplateArgument::Type)
  4005. if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
  4006. Visit(TSI->getTypeLoc(), Sema::AbstractNone);
  4007. // TODO: other template argument types?
  4008. }
  4009. }
  4010. // Visit pointee types from a permissive context.
  4011. #define CheckPolymorphic(Type) \
  4012. void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
  4013. Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
  4014. }
  4015. CheckPolymorphic(PointerTypeLoc)
  4016. CheckPolymorphic(ReferenceTypeLoc)
  4017. CheckPolymorphic(MemberPointerTypeLoc)
  4018. CheckPolymorphic(BlockPointerTypeLoc)
  4019. CheckPolymorphic(AtomicTypeLoc)
  4020. /// Handle all the types we haven't given a more specific
  4021. /// implementation for above.
  4022. void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
  4023. // Every other kind of type that we haven't called out already
  4024. // that has an inner type is either (1) sugar or (2) contains that
  4025. // inner type in some way as a subobject.
  4026. if (TypeLoc Next = TL.getNextTypeLoc())
  4027. return Visit(Next, Sel);
  4028. // If there's no inner type and we're in a permissive context,
  4029. // don't diagnose.
  4030. if (Sel == Sema::AbstractNone) return;
  4031. // Check whether the type matches the abstract type.
  4032. QualType T = TL.getType();
  4033. if (T->isArrayType()) {
  4034. Sel = Sema::AbstractArrayType;
  4035. T = Info.S.Context.getBaseElementType(T);
  4036. }
  4037. CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
  4038. if (CT != Info.AbstractType) return;
  4039. // It matched; do some magic.
  4040. if (Sel == Sema::AbstractArrayType) {
  4041. Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
  4042. << T << TL.getSourceRange();
  4043. } else {
  4044. Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
  4045. << Sel << T << TL.getSourceRange();
  4046. }
  4047. Info.DiagnoseAbstractType();
  4048. }
  4049. };
  4050. void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
  4051. Sema::AbstractDiagSelID Sel) {
  4052. CheckAbstractUsage(*this, D).Visit(TL, Sel);
  4053. }
  4054. }
  4055. /// Check for invalid uses of an abstract type in a method declaration.
  4056. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4057. CXXMethodDecl *MD) {
  4058. // No need to do the check on definitions, which require that
  4059. // the return/param types be complete.
  4060. if (MD->doesThisDeclarationHaveABody())
  4061. return;
  4062. // For safety's sake, just ignore it if we don't have type source
  4063. // information. This should never happen for non-implicit methods,
  4064. // but...
  4065. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  4066. Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
  4067. }
  4068. /// Check for invalid uses of an abstract type within a class definition.
  4069. static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
  4070. CXXRecordDecl *RD) {
  4071. for (auto *D : RD->decls()) {
  4072. if (D->isImplicit()) continue;
  4073. // Methods and method templates.
  4074. if (isa<CXXMethodDecl>(D)) {
  4075. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
  4076. } else if (isa<FunctionTemplateDecl>(D)) {
  4077. FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
  4078. CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
  4079. // Fields and static variables.
  4080. } else if (isa<FieldDecl>(D)) {
  4081. FieldDecl *FD = cast<FieldDecl>(D);
  4082. if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
  4083. Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
  4084. } else if (isa<VarDecl>(D)) {
  4085. VarDecl *VD = cast<VarDecl>(D);
  4086. if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
  4087. Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
  4088. // Nested classes and class templates.
  4089. } else if (isa<CXXRecordDecl>(D)) {
  4090. CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
  4091. } else if (isa<ClassTemplateDecl>(D)) {
  4092. CheckAbstractClassUsage(Info,
  4093. cast<ClassTemplateDecl>(D)->getTemplatedDecl());
  4094. }
  4095. }
  4096. }
  4097. /// \brief Check class-level dllimport/dllexport attribute.
  4098. void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
  4099. Attr *ClassAttr = getDLLAttr(Class);
  4100. // MSVC inherits DLL attributes to partial class template specializations.
  4101. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
  4102. if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
  4103. if (Attr *TemplateAttr =
  4104. getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
  4105. auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
  4106. A->setInherited(true);
  4107. ClassAttr = A;
  4108. }
  4109. }
  4110. }
  4111. if (!ClassAttr)
  4112. return;
  4113. if (!Class->isExternallyVisible()) {
  4114. Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
  4115. << Class << ClassAttr;
  4116. return;
  4117. }
  4118. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  4119. !ClassAttr->isInherited()) {
  4120. // Diagnose dll attributes on members of class with dll attribute.
  4121. for (Decl *Member : Class->decls()) {
  4122. if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
  4123. continue;
  4124. InheritableAttr *MemberAttr = getDLLAttr(Member);
  4125. if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
  4126. continue;
  4127. Diag(MemberAttr->getLocation(),
  4128. diag::err_attribute_dll_member_of_dll_class)
  4129. << MemberAttr << ClassAttr;
  4130. Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
  4131. Member->setInvalidDecl();
  4132. }
  4133. }
  4134. if (Class->getDescribedClassTemplate())
  4135. // Don't inherit dll attribute until the template is instantiated.
  4136. return;
  4137. // The class is either imported or exported.
  4138. const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
  4139. const bool ClassImported = !ClassExported;
  4140. TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
  4141. // Ignore explicit dllexport on explicit class template instantiation declarations.
  4142. if (ClassExported && !ClassAttr->isInherited() &&
  4143. TSK == TSK_ExplicitInstantiationDeclaration) {
  4144. Class->dropAttr<DLLExportAttr>();
  4145. return;
  4146. }
  4147. // Force declaration of implicit members so they can inherit the attribute.
  4148. ForceDeclarationOfImplicitMembers(Class);
  4149. // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
  4150. // seem to be true in practice?
  4151. for (Decl *Member : Class->decls()) {
  4152. VarDecl *VD = dyn_cast<VarDecl>(Member);
  4153. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
  4154. // Only methods and static fields inherit the attributes.
  4155. if (!VD && !MD)
  4156. continue;
  4157. if (MD) {
  4158. // Don't process deleted methods.
  4159. if (MD->isDeleted())
  4160. continue;
  4161. if (MD->isInlined()) {
  4162. // MinGW does not import or export inline methods.
  4163. if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
  4164. continue;
  4165. // MSVC versions before 2015 don't export the move assignment operators,
  4166. // so don't attempt to import them if we have a definition.
  4167. if (ClassImported && MD->isMoveAssignmentOperator() &&
  4168. !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
  4169. continue;
  4170. }
  4171. }
  4172. if (!cast<NamedDecl>(Member)->isExternallyVisible())
  4173. continue;
  4174. if (!getDLLAttr(Member)) {
  4175. auto *NewAttr =
  4176. cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4177. NewAttr->setInherited(true);
  4178. Member->addAttr(NewAttr);
  4179. }
  4180. if (MD && ClassExported) {
  4181. if (TSK == TSK_ExplicitInstantiationDeclaration)
  4182. // Don't go any further if this is just an explicit instantiation
  4183. // declaration.
  4184. continue;
  4185. if (MD->isUserProvided()) {
  4186. // Instantiate non-default class member functions ...
  4187. // .. except for certain kinds of template specializations.
  4188. if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
  4189. continue;
  4190. MarkFunctionReferenced(Class->getLocation(), MD);
  4191. // The function will be passed to the consumer when its definition is
  4192. // encountered.
  4193. } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
  4194. MD->isCopyAssignmentOperator() ||
  4195. MD->isMoveAssignmentOperator()) {
  4196. // Synthesize and instantiate non-trivial implicit methods, explicitly
  4197. // defaulted methods, and the copy and move assignment operators. The
  4198. // latter are exported even if they are trivial, because the address of
  4199. // an operator can be taken and should compare equal accross libraries.
  4200. DiagnosticErrorTrap Trap(Diags);
  4201. MarkFunctionReferenced(Class->getLocation(), MD);
  4202. if (Trap.hasErrorOccurred()) {
  4203. Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
  4204. << Class->getName() << !getLangOpts().CPlusPlus11;
  4205. break;
  4206. }
  4207. // There is no later point when we will see the definition of this
  4208. // function, so pass it to the consumer now.
  4209. Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
  4210. }
  4211. }
  4212. }
  4213. }
  4214. /// \brief Perform propagation of DLL attributes from a derived class to a
  4215. /// templated base class for MS compatibility.
  4216. void Sema::propagateDLLAttrToBaseClassTemplate(
  4217. CXXRecordDecl *Class, Attr *ClassAttr,
  4218. ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
  4219. if (getDLLAttr(
  4220. BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
  4221. // If the base class template has a DLL attribute, don't try to change it.
  4222. return;
  4223. }
  4224. auto TSK = BaseTemplateSpec->getSpecializationKind();
  4225. if (!getDLLAttr(BaseTemplateSpec) &&
  4226. (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
  4227. TSK == TSK_ImplicitInstantiation)) {
  4228. // The template hasn't been instantiated yet (or it has, but only as an
  4229. // explicit instantiation declaration or implicit instantiation, which means
  4230. // we haven't codegenned any members yet), so propagate the attribute.
  4231. auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
  4232. NewAttr->setInherited(true);
  4233. BaseTemplateSpec->addAttr(NewAttr);
  4234. // If the template is already instantiated, checkDLLAttributeRedeclaration()
  4235. // needs to be run again to work see the new attribute. Otherwise this will
  4236. // get run whenever the template is instantiated.
  4237. if (TSK != TSK_Undeclared)
  4238. checkClassLevelDLLAttribute(BaseTemplateSpec);
  4239. return;
  4240. }
  4241. if (getDLLAttr(BaseTemplateSpec)) {
  4242. // The template has already been specialized or instantiated with an
  4243. // attribute, explicitly or through propagation. We should not try to change
  4244. // it.
  4245. return;
  4246. }
  4247. // The template was previously instantiated or explicitly specialized without
  4248. // a dll attribute, It's too late for us to add an attribute, so warn that
  4249. // this is unsupported.
  4250. Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
  4251. << BaseTemplateSpec->isExplicitSpecialization();
  4252. Diag(ClassAttr->getLocation(), diag::note_attribute);
  4253. if (BaseTemplateSpec->isExplicitSpecialization()) {
  4254. Diag(BaseTemplateSpec->getLocation(),
  4255. diag::note_template_class_explicit_specialization_was_here)
  4256. << BaseTemplateSpec;
  4257. } else {
  4258. Diag(BaseTemplateSpec->getPointOfInstantiation(),
  4259. diag::note_template_class_instantiation_was_here)
  4260. << BaseTemplateSpec;
  4261. }
  4262. }
  4263. /// \brief Perform semantic checks on a class definition that has been
  4264. /// completing, introducing implicitly-declared members, checking for
  4265. /// abstract types, etc.
  4266. void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
  4267. if (!Record)
  4268. return;
  4269. if (Record->isAbstract() && !Record->isInvalidDecl()) {
  4270. AbstractUsageInfo Info(*this, Record);
  4271. CheckAbstractClassUsage(Info, Record);
  4272. }
  4273. // If this is not an aggregate type and has no user-declared constructor,
  4274. // complain about any non-static data members of reference or const scalar
  4275. // type, since they will never get initializers.
  4276. if (!Record->isInvalidDecl() && !Record->isDependentType() &&
  4277. !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
  4278. !Record->isLambda()) {
  4279. bool Complained = false;
  4280. for (const auto *F : Record->fields()) {
  4281. if (F->hasInClassInitializer() || F->isUnnamedBitfield())
  4282. continue;
  4283. if (F->getType()->isReferenceType() ||
  4284. (F->getType().isConstQualified() && F->getType()->isScalarType())) {
  4285. if (!Complained) {
  4286. Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
  4287. << Record->getTagKind() << Record;
  4288. Complained = true;
  4289. }
  4290. Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
  4291. << F->getType()->isReferenceType()
  4292. << F->getDeclName();
  4293. }
  4294. }
  4295. }
  4296. if (Record->getIdentifier()) {
  4297. // C++ [class.mem]p13:
  4298. // If T is the name of a class, then each of the following shall have a
  4299. // name different from T:
  4300. // - every member of every anonymous union that is a member of class T.
  4301. //
  4302. // C++ [class.mem]p14:
  4303. // In addition, if class T has a user-declared constructor (12.1), every
  4304. // non-static data member of class T shall have a name different from T.
  4305. DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
  4306. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  4307. ++I) {
  4308. NamedDecl *D = *I;
  4309. if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
  4310. isa<IndirectFieldDecl>(D)) {
  4311. Diag(D->getLocation(), diag::err_member_name_of_class)
  4312. << D->getDeclName();
  4313. break;
  4314. }
  4315. }
  4316. }
  4317. // Warn if the class has virtual methods but non-virtual public destructor.
  4318. if (Record->isPolymorphic() && !Record->isDependentType()) {
  4319. CXXDestructorDecl *dtor = Record->getDestructor();
  4320. if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
  4321. !Record->hasAttr<FinalAttr>())
  4322. Diag(dtor ? dtor->getLocation() : Record->getLocation(),
  4323. diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
  4324. }
  4325. if (Record->isAbstract()) {
  4326. if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
  4327. Diag(Record->getLocation(), diag::warn_abstract_final_class)
  4328. << FA->isSpelledAsSealed();
  4329. DiagnoseAbstractType(Record);
  4330. }
  4331. }
  4332. bool HasMethodWithOverrideControl = false,
  4333. HasOverridingMethodWithoutOverrideControl = false;
  4334. if (!Record->isDependentType()) {
  4335. for (auto *M : Record->methods()) {
  4336. // See if a method overloads virtual methods in a base
  4337. // class without overriding any.
  4338. if (!M->isStatic())
  4339. DiagnoseHiddenVirtualMethods(M);
  4340. if (M->hasAttr<OverrideAttr>())
  4341. HasMethodWithOverrideControl = true;
  4342. else if (M->size_overridden_methods() > 0)
  4343. HasOverridingMethodWithoutOverrideControl = true;
  4344. // Check whether the explicitly-defaulted special members are valid.
  4345. if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
  4346. CheckExplicitlyDefaultedSpecialMember(M);
  4347. // For an explicitly defaulted or deleted special member, we defer
  4348. // determining triviality until the class is complete. That time is now!
  4349. if (!M->isImplicit() && !M->isUserProvided()) {
  4350. CXXSpecialMember CSM = getSpecialMember(M);
  4351. if (CSM != CXXInvalid) {
  4352. M->setTrivial(SpecialMemberIsTrivial(M, CSM));
  4353. // Inform the class that we've finished declaring this member.
  4354. Record->finishedDefaultedOrDeletedMember(M);
  4355. }
  4356. }
  4357. }
  4358. }
  4359. if (HasMethodWithOverrideControl &&
  4360. HasOverridingMethodWithoutOverrideControl) {
  4361. // At least one method has the 'override' control declared.
  4362. // Diagnose all other overridden methods which do not have 'override' specified on them.
  4363. for (auto *M : Record->methods())
  4364. DiagnoseAbsenceOfOverrideControl(M);
  4365. }
  4366. // ms_struct is a request to use the same ABI rules as MSVC. Check
  4367. // whether this class uses any C++ features that are implemented
  4368. // completely differently in MSVC, and if so, emit a diagnostic.
  4369. // That diagnostic defaults to an error, but we allow projects to
  4370. // map it down to a warning (or ignore it). It's a fairly common
  4371. // practice among users of the ms_struct pragma to mass-annotate
  4372. // headers, sweeping up a bunch of types that the project doesn't
  4373. // really rely on MSVC-compatible layout for. We must therefore
  4374. // support "ms_struct except for C++ stuff" as a secondary ABI.
  4375. if (Record->isMsStruct(Context) &&
  4376. (Record->isPolymorphic() || Record->getNumBases())) {
  4377. Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
  4378. }
  4379. // Declare inheriting constructors. We do this eagerly here because:
  4380. // - The standard requires an eager diagnostic for conflicting inheriting
  4381. // constructors from different classes.
  4382. // - The lazy declaration of the other implicit constructors is so as to not
  4383. // waste space and performance on classes that are not meant to be
  4384. // instantiated (e.g. meta-functions). This doesn't apply to classes that
  4385. // have inheriting constructors.
  4386. DeclareInheritingConstructors(Record);
  4387. checkClassLevelDLLAttribute(Record);
  4388. }
  4389. /// Look up the special member function that would be called by a special
  4390. /// member function for a subobject of class type.
  4391. ///
  4392. /// \param Class The class type of the subobject.
  4393. /// \param CSM The kind of special member function.
  4394. /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
  4395. /// \param ConstRHS True if this is a copy operation with a const object
  4396. /// on its RHS, that is, if the argument to the outer special member
  4397. /// function is 'const' and this is not a field marked 'mutable'.
  4398. static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
  4399. Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
  4400. unsigned FieldQuals, bool ConstRHS) {
  4401. unsigned LHSQuals = 0;
  4402. if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
  4403. LHSQuals = FieldQuals;
  4404. unsigned RHSQuals = FieldQuals;
  4405. if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
  4406. RHSQuals = 0;
  4407. else if (ConstRHS)
  4408. RHSQuals |= Qualifiers::Const;
  4409. return S.LookupSpecialMember(Class, CSM,
  4410. RHSQuals & Qualifiers::Const,
  4411. RHSQuals & Qualifiers::Volatile,
  4412. false,
  4413. LHSQuals & Qualifiers::Const,
  4414. LHSQuals & Qualifiers::Volatile);
  4415. }
  4416. /// Is the special member function which would be selected to perform the
  4417. /// specified operation on the specified class type a constexpr constructor?
  4418. static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  4419. Sema::CXXSpecialMember CSM,
  4420. unsigned Quals, bool ConstRHS) {
  4421. Sema::SpecialMemberOverloadResult *SMOR =
  4422. lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
  4423. if (!SMOR || !SMOR->getMethod())
  4424. // A constructor we wouldn't select can't be "involved in initializing"
  4425. // anything.
  4426. return true;
  4427. return SMOR->getMethod()->isConstexpr();
  4428. }
  4429. /// Determine whether the specified special member function would be constexpr
  4430. /// if it were implicitly defined.
  4431. static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
  4432. Sema::CXXSpecialMember CSM,
  4433. bool ConstArg) {
  4434. if (!S.getLangOpts().CPlusPlus11)
  4435. return false;
  4436. // C++11 [dcl.constexpr]p4:
  4437. // In the definition of a constexpr constructor [...]
  4438. bool Ctor = true;
  4439. switch (CSM) {
  4440. case Sema::CXXDefaultConstructor:
  4441. // Since default constructor lookup is essentially trivial (and cannot
  4442. // involve, for instance, template instantiation), we compute whether a
  4443. // defaulted default constructor is constexpr directly within CXXRecordDecl.
  4444. //
  4445. // This is important for performance; we need to know whether the default
  4446. // constructor is constexpr to determine whether the type is a literal type.
  4447. return ClassDecl->defaultedDefaultConstructorIsConstexpr();
  4448. case Sema::CXXCopyConstructor:
  4449. case Sema::CXXMoveConstructor:
  4450. // For copy or move constructors, we need to perform overload resolution.
  4451. break;
  4452. case Sema::CXXCopyAssignment:
  4453. case Sema::CXXMoveAssignment:
  4454. if (!S.getLangOpts().CPlusPlus14)
  4455. return false;
  4456. // In C++1y, we need to perform overload resolution.
  4457. Ctor = false;
  4458. break;
  4459. case Sema::CXXDestructor:
  4460. case Sema::CXXInvalid:
  4461. return false;
  4462. }
  4463. // -- if the class is a non-empty union, or for each non-empty anonymous
  4464. // union member of a non-union class, exactly one non-static data member
  4465. // shall be initialized; [DR1359]
  4466. //
  4467. // If we squint, this is guaranteed, since exactly one non-static data member
  4468. // will be initialized (if the constructor isn't deleted), we just don't know
  4469. // which one.
  4470. if (Ctor && ClassDecl->isUnion())
  4471. return true;
  4472. // -- the class shall not have any virtual base classes;
  4473. if (Ctor && ClassDecl->getNumVBases())
  4474. return false;
  4475. // C++1y [class.copy]p26:
  4476. // -- [the class] is a literal type, and
  4477. if (!Ctor && !ClassDecl->isLiteral())
  4478. return false;
  4479. // -- every constructor involved in initializing [...] base class
  4480. // sub-objects shall be a constexpr constructor;
  4481. // -- the assignment operator selected to copy/move each direct base
  4482. // class is a constexpr function, and
  4483. for (const auto &B : ClassDecl->bases()) {
  4484. const RecordType *BaseType = B.getType()->getAs<RecordType>();
  4485. if (!BaseType) continue;
  4486. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  4487. if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
  4488. return false;
  4489. }
  4490. // -- every constructor involved in initializing non-static data members
  4491. // [...] shall be a constexpr constructor;
  4492. // -- every non-static data member and base class sub-object shall be
  4493. // initialized
  4494. // -- for each non-static data member of X that is of class type (or array
  4495. // thereof), the assignment operator selected to copy/move that member is
  4496. // a constexpr function
  4497. for (const auto *F : ClassDecl->fields()) {
  4498. if (F->isInvalidDecl())
  4499. continue;
  4500. QualType BaseType = S.Context.getBaseElementType(F->getType());
  4501. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  4502. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  4503. if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
  4504. BaseType.getCVRQualifiers(),
  4505. ConstArg && !F->isMutable()))
  4506. return false;
  4507. }
  4508. }
  4509. // All OK, it's constexpr!
  4510. return true;
  4511. }
  4512. static Sema::ImplicitExceptionSpecification
  4513. computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
  4514. switch (S.getSpecialMember(MD)) {
  4515. case Sema::CXXDefaultConstructor:
  4516. return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
  4517. case Sema::CXXCopyConstructor:
  4518. return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
  4519. case Sema::CXXCopyAssignment:
  4520. return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
  4521. case Sema::CXXMoveConstructor:
  4522. return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
  4523. case Sema::CXXMoveAssignment:
  4524. return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
  4525. case Sema::CXXDestructor:
  4526. return S.ComputeDefaultedDtorExceptionSpec(MD);
  4527. case Sema::CXXInvalid:
  4528. break;
  4529. }
  4530. assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
  4531. "only special members have implicit exception specs");
  4532. return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
  4533. }
  4534. static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
  4535. CXXMethodDecl *MD) {
  4536. FunctionProtoType::ExtProtoInfo EPI;
  4537. // Build an exception specification pointing back at this member.
  4538. EPI.ExceptionSpec.Type = EST_BasicNoexcept; // HLSL Change - EST_Unevaluated to EST_BasicNoexcept
  4539. EPI.ExceptionSpec.SourceDecl = MD;
  4540. // Set the calling convention to the default for C++ instance methods.
  4541. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
  4542. S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  4543. /*IsCXXMethod=*/true));
  4544. return EPI;
  4545. }
  4546. void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
  4547. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  4548. if (FPT->getExceptionSpecType() != EST_Unevaluated)
  4549. return;
  4550. // Evaluate the exception specification.
  4551. auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
  4552. // Update the type of the special member to use it.
  4553. UpdateExceptionSpec(MD, ESI);
  4554. // A user-provided destructor can be defined outside the class. When that
  4555. // happens, be sure to update the exception specification on both
  4556. // declarations.
  4557. const FunctionProtoType *CanonicalFPT =
  4558. MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
  4559. if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
  4560. UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
  4561. }
  4562. void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
  4563. CXXRecordDecl *RD = MD->getParent();
  4564. CXXSpecialMember CSM = getSpecialMember(MD);
  4565. assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
  4566. "not an explicitly-defaulted special member");
  4567. // Whether this was the first-declared instance of the constructor.
  4568. // This affects whether we implicitly add an exception spec and constexpr.
  4569. bool First = MD == MD->getCanonicalDecl();
  4570. bool HadError = false;
  4571. // C++11 [dcl.fct.def.default]p1:
  4572. // A function that is explicitly defaulted shall
  4573. // -- be a special member function (checked elsewhere),
  4574. // -- have the same type (except for ref-qualifiers, and except that a
  4575. // copy operation can take a non-const reference) as an implicit
  4576. // declaration, and
  4577. // -- not have default arguments.
  4578. unsigned ExpectedParams = 1;
  4579. if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
  4580. ExpectedParams = 0;
  4581. if (MD->getNumParams() != ExpectedParams) {
  4582. // This also checks for default arguments: a copy or move constructor with a
  4583. // default argument is classified as a default constructor, and assignment
  4584. // operations and destructors can't have default arguments.
  4585. Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
  4586. << CSM << MD->getSourceRange();
  4587. HadError = true;
  4588. } else if (MD->isVariadic()) {
  4589. Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
  4590. << CSM << MD->getSourceRange();
  4591. HadError = true;
  4592. }
  4593. const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
  4594. bool CanHaveConstParam = false;
  4595. if (CSM == CXXCopyConstructor)
  4596. CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
  4597. else if (CSM == CXXCopyAssignment)
  4598. CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
  4599. QualType ReturnType = Context.VoidTy;
  4600. if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
  4601. // Check for return type matching.
  4602. ReturnType = Type->getReturnType();
  4603. QualType ExpectedReturnType =
  4604. Context.getLValueReferenceType(Context.getTypeDeclType(RD));
  4605. if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
  4606. Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
  4607. << (CSM == CXXMoveAssignment) << ExpectedReturnType;
  4608. HadError = true;
  4609. }
  4610. // A defaulted special member cannot have cv-qualifiers.
  4611. if (Type->getTypeQuals()) {
  4612. Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
  4613. << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
  4614. HadError = true;
  4615. }
  4616. }
  4617. // Check for parameter type matching.
  4618. QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
  4619. bool HasConstParam = false;
  4620. if (ExpectedParams && ArgType->isReferenceType()) {
  4621. // Argument must be reference to possibly-const T.
  4622. QualType ReferentType = ArgType->getPointeeType();
  4623. HasConstParam = ReferentType.isConstQualified();
  4624. if (ReferentType.isVolatileQualified()) {
  4625. Diag(MD->getLocation(),
  4626. diag::err_defaulted_special_member_volatile_param) << CSM;
  4627. HadError = true;
  4628. }
  4629. if (HasConstParam && !CanHaveConstParam) {
  4630. if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
  4631. Diag(MD->getLocation(),
  4632. diag::err_defaulted_special_member_copy_const_param)
  4633. << (CSM == CXXCopyAssignment);
  4634. // FIXME: Explain why this special member can't be const.
  4635. } else {
  4636. Diag(MD->getLocation(),
  4637. diag::err_defaulted_special_member_move_const_param)
  4638. << (CSM == CXXMoveAssignment);
  4639. }
  4640. HadError = true;
  4641. }
  4642. } else if (ExpectedParams) {
  4643. // A copy assignment operator can take its argument by value, but a
  4644. // defaulted one cannot.
  4645. assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
  4646. Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
  4647. HadError = true;
  4648. }
  4649. // C++11 [dcl.fct.def.default]p2:
  4650. // An explicitly-defaulted function may be declared constexpr only if it
  4651. // would have been implicitly declared as constexpr,
  4652. // Do not apply this rule to members of class templates, since core issue 1358
  4653. // makes such functions always instantiate to constexpr functions. For
  4654. // functions which cannot be constexpr (for non-constructors in C++11 and for
  4655. // destructors in C++1y), this is checked elsewhere.
  4656. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
  4657. HasConstParam);
  4658. if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
  4659. : isa<CXXConstructorDecl>(MD)) &&
  4660. MD->isConstexpr() && !Constexpr &&
  4661. MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
  4662. Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
  4663. // FIXME: Explain why the special member can't be constexpr.
  4664. HadError = true;
  4665. }
  4666. // and may have an explicit exception-specification only if it is compatible
  4667. // with the exception-specification on the implicit declaration.
  4668. if (Type->hasExceptionSpec()) {
  4669. // Delay the check if this is the first declaration of the special member,
  4670. // since we may not have parsed some necessary in-class initializers yet.
  4671. if (First) {
  4672. // If the exception specification needs to be instantiated, do so now,
  4673. // before we clobber it with an EST_Unevaluated specification below.
  4674. if (Type->getExceptionSpecType() == EST_Uninstantiated) {
  4675. InstantiateExceptionSpec(MD->getLocStart(), MD);
  4676. Type = MD->getType()->getAs<FunctionProtoType>();
  4677. }
  4678. DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
  4679. } else
  4680. CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
  4681. }
  4682. // If a function is explicitly defaulted on its first declaration,
  4683. if (First) {
  4684. // -- it is implicitly considered to be constexpr if the implicit
  4685. // definition would be,
  4686. MD->setConstexpr(Constexpr);
  4687. // -- it is implicitly considered to have the same exception-specification
  4688. // as if it had been implicitly declared,
  4689. FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
  4690. EPI.ExceptionSpec.Type = EST_Unevaluated;
  4691. EPI.ExceptionSpec.SourceDecl = MD;
  4692. MD->setType(Context.getFunctionType(ReturnType,
  4693. llvm::makeArrayRef(&ArgType,
  4694. ExpectedParams),
  4695. EPI, None)); // HLSL Change - special members are all-in params
  4696. }
  4697. if (ShouldDeleteSpecialMember(MD, CSM)) {
  4698. if (First) {
  4699. SetDeclDeleted(MD, MD->getLocation());
  4700. } else {
  4701. // C++11 [dcl.fct.def.default]p4:
  4702. // [For a] user-provided explicitly-defaulted function [...] if such a
  4703. // function is implicitly defined as deleted, the program is ill-formed.
  4704. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
  4705. ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
  4706. HadError = true;
  4707. }
  4708. }
  4709. if (HadError)
  4710. MD->setInvalidDecl();
  4711. }
  4712. /// Check whether the exception specification provided for an
  4713. /// explicitly-defaulted special member matches the exception specification
  4714. /// that would have been generated for an implicit special member, per
  4715. /// C++11 [dcl.fct.def.default]p2.
  4716. void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
  4717. CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
  4718. // If the exception specification was explicitly specified but hadn't been
  4719. // parsed when the method was defaulted, grab it now.
  4720. if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
  4721. SpecifiedType =
  4722. MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
  4723. // Compute the implicit exception specification.
  4724. CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
  4725. /*IsCXXMethod=*/true);
  4726. FunctionProtoType::ExtProtoInfo EPI(CC);
  4727. EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
  4728. .getExceptionSpec();
  4729. const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
  4730. Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change - special members are all-in params
  4731. // Ensure that it matches.
  4732. CheckEquivalentExceptionSpec(
  4733. PDiag(diag::err_incorrect_defaulted_exception_spec)
  4734. << getSpecialMember(MD), PDiag(),
  4735. ImplicitType, SourceLocation(),
  4736. SpecifiedType, MD->getLocation());
  4737. }
  4738. void Sema::CheckDelayedMemberExceptionSpecs() {
  4739. decltype(DelayedExceptionSpecChecks) Checks;
  4740. decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
  4741. std::swap(Checks, DelayedExceptionSpecChecks);
  4742. std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
  4743. // Perform any deferred checking of exception specifications for virtual
  4744. // destructors.
  4745. for (auto &Check : Checks)
  4746. CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
  4747. // Check that any explicitly-defaulted methods have exception specifications
  4748. // compatible with their implicit exception specifications.
  4749. for (auto &Spec : Specs)
  4750. CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
  4751. }
  4752. namespace {
  4753. struct SpecialMemberDeletionInfo {
  4754. Sema &S;
  4755. CXXMethodDecl *MD;
  4756. Sema::CXXSpecialMember CSM;
  4757. bool Diagnose;
  4758. // Properties of the special member, computed for convenience.
  4759. bool IsConstructor, IsAssignment, IsMove, ConstArg;
  4760. SourceLocation Loc;
  4761. bool AllFieldsAreConst;
  4762. SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
  4763. Sema::CXXSpecialMember CSM, bool Diagnose)
  4764. : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
  4765. IsConstructor(false), IsAssignment(false), IsMove(false),
  4766. ConstArg(false), Loc(MD->getLocation()),
  4767. AllFieldsAreConst(true) {
  4768. switch (CSM) {
  4769. case Sema::CXXDefaultConstructor:
  4770. case Sema::CXXCopyConstructor:
  4771. IsConstructor = true;
  4772. break;
  4773. case Sema::CXXMoveConstructor:
  4774. IsConstructor = true;
  4775. IsMove = true;
  4776. break;
  4777. case Sema::CXXCopyAssignment:
  4778. IsAssignment = true;
  4779. break;
  4780. case Sema::CXXMoveAssignment:
  4781. IsAssignment = true;
  4782. IsMove = true;
  4783. break;
  4784. case Sema::CXXDestructor:
  4785. break;
  4786. case Sema::CXXInvalid:
  4787. llvm_unreachable("invalid special member kind");
  4788. }
  4789. if (MD->getNumParams()) {
  4790. if (const ReferenceType *RT =
  4791. MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
  4792. ConstArg = RT->getPointeeType().isConstQualified();
  4793. }
  4794. }
  4795. bool inUnion() const { return MD->getParent()->isUnion(); }
  4796. /// Look up the corresponding special member in the given class.
  4797. Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
  4798. unsigned Quals, bool IsMutable) {
  4799. return lookupCallFromSpecialMember(S, Class, CSM, Quals,
  4800. ConstArg && !IsMutable);
  4801. }
  4802. typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
  4803. bool shouldDeleteForBase(CXXBaseSpecifier *Base);
  4804. bool shouldDeleteForField(FieldDecl *FD);
  4805. bool shouldDeleteForAllConstMembers();
  4806. bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
  4807. unsigned Quals);
  4808. bool shouldDeleteForSubobjectCall(Subobject Subobj,
  4809. Sema::SpecialMemberOverloadResult *SMOR,
  4810. bool IsDtorCallInCtor);
  4811. bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
  4812. };
  4813. }
  4814. /// Is the given special member inaccessible when used on the given
  4815. /// sub-object.
  4816. bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
  4817. CXXMethodDecl *target) {
  4818. /// If we're operating on a base class, the object type is the
  4819. /// type of this special member.
  4820. QualType objectTy;
  4821. AccessSpecifier access = target->getAccess();
  4822. if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
  4823. objectTy = S.Context.getTypeDeclType(MD->getParent());
  4824. access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
  4825. // If we're operating on a field, the object type is the type of the field.
  4826. } else {
  4827. objectTy = S.Context.getTypeDeclType(target->getParent());
  4828. }
  4829. return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
  4830. }
  4831. /// Check whether we should delete a special member due to the implicit
  4832. /// definition containing a call to a special member of a subobject.
  4833. bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
  4834. Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
  4835. bool IsDtorCallInCtor) {
  4836. CXXMethodDecl *Decl = SMOR->getMethod();
  4837. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  4838. int DiagKind = -1;
  4839. if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
  4840. DiagKind = !Decl ? 0 : 1;
  4841. else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  4842. DiagKind = 2;
  4843. else if (!isAccessible(Subobj, Decl))
  4844. DiagKind = 3;
  4845. else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
  4846. !Decl->isTrivial()) {
  4847. // A member of a union must have a trivial corresponding special member.
  4848. // As a weird special case, a destructor call from a union's constructor
  4849. // must be accessible and non-deleted, but need not be trivial. Such a
  4850. // destructor is never actually called, but is semantically checked as
  4851. // if it were.
  4852. DiagKind = 4;
  4853. }
  4854. if (DiagKind == -1)
  4855. return false;
  4856. if (Diagnose) {
  4857. if (Field) {
  4858. S.Diag(Field->getLocation(),
  4859. diag::note_deleted_special_member_class_subobject)
  4860. << CSM << MD->getParent() << /*IsField*/true
  4861. << Field << DiagKind << IsDtorCallInCtor;
  4862. } else {
  4863. CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
  4864. S.Diag(Base->getLocStart(),
  4865. diag::note_deleted_special_member_class_subobject)
  4866. << CSM << MD->getParent() << /*IsField*/false
  4867. << Base->getType() << DiagKind << IsDtorCallInCtor;
  4868. }
  4869. if (DiagKind == 1)
  4870. S.NoteDeletedFunction(Decl);
  4871. // FIXME: Explain inaccessibility if DiagKind == 3.
  4872. }
  4873. return true;
  4874. }
  4875. /// Check whether we should delete a special member function due to having a
  4876. /// direct or virtual base class or non-static data member of class type M.
  4877. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
  4878. CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
  4879. FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
  4880. bool IsMutable = Field && Field->isMutable();
  4881. // C++11 [class.ctor]p5:
  4882. // -- any direct or virtual base class, or non-static data member with no
  4883. // brace-or-equal-initializer, has class type M (or array thereof) and
  4884. // either M has no default constructor or overload resolution as applied
  4885. // to M's default constructor results in an ambiguity or in a function
  4886. // that is deleted or inaccessible
  4887. // C++11 [class.copy]p11, C++11 [class.copy]p23:
  4888. // -- a direct or virtual base class B that cannot be copied/moved because
  4889. // overload resolution, as applied to B's corresponding special member,
  4890. // results in an ambiguity or a function that is deleted or inaccessible
  4891. // from the defaulted special member
  4892. // C++11 [class.dtor]p5:
  4893. // -- any direct or virtual base class [...] has a type with a destructor
  4894. // that is deleted or inaccessible
  4895. if (!(CSM == Sema::CXXDefaultConstructor &&
  4896. Field && Field->hasInClassInitializer()) &&
  4897. shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
  4898. false))
  4899. return true;
  4900. // C++11 [class.ctor]p5, C++11 [class.copy]p11:
  4901. // -- any direct or virtual base class or non-static data member has a
  4902. // type with a destructor that is deleted or inaccessible
  4903. if (IsConstructor) {
  4904. Sema::SpecialMemberOverloadResult *SMOR =
  4905. S.LookupSpecialMember(Class, Sema::CXXDestructor,
  4906. false, false, false, false, false);
  4907. if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
  4908. return true;
  4909. }
  4910. return false;
  4911. }
  4912. /// Check whether we should delete a special member function due to the class
  4913. /// having a particular direct or virtual base class.
  4914. bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
  4915. CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
  4916. return shouldDeleteForClassSubobject(BaseClass, Base, 0);
  4917. }
  4918. /// Check whether we should delete a special member function due to the class
  4919. /// having a particular non-static data member.
  4920. bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
  4921. QualType FieldType = S.Context.getBaseElementType(FD->getType());
  4922. CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
  4923. if (CSM == Sema::CXXDefaultConstructor) {
  4924. // For a default constructor, all references must be initialized in-class
  4925. // and, if a union, it must have a non-const member.
  4926. if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
  4927. if (Diagnose)
  4928. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  4929. << MD->getParent() << FD << FieldType << /*Reference*/0;
  4930. return true;
  4931. }
  4932. // C++11 [class.ctor]p5: any non-variant non-static data member of
  4933. // const-qualified type (or array thereof) with no
  4934. // brace-or-equal-initializer does not have a user-provided default
  4935. // constructor.
  4936. if (!inUnion() && FieldType.isConstQualified() &&
  4937. !FD->hasInClassInitializer() &&
  4938. (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
  4939. if (Diagnose)
  4940. S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
  4941. << MD->getParent() << FD << FD->getType() << /*Const*/1;
  4942. return true;
  4943. }
  4944. if (inUnion() && !FieldType.isConstQualified())
  4945. AllFieldsAreConst = false;
  4946. } else if (CSM == Sema::CXXCopyConstructor) {
  4947. // For a copy constructor, data members must not be of rvalue reference
  4948. // type.
  4949. if (FieldType->isRValueReferenceType()) {
  4950. if (Diagnose)
  4951. S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
  4952. << MD->getParent() << FD << FieldType;
  4953. return true;
  4954. }
  4955. } else if (IsAssignment) {
  4956. // For an assignment operator, data members must not be of reference type.
  4957. if (FieldType->isReferenceType()) {
  4958. if (Diagnose)
  4959. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  4960. << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
  4961. return true;
  4962. }
  4963. if (!FieldRecord && FieldType.isConstQualified()) {
  4964. // C++11 [class.copy]p23:
  4965. // -- a non-static data member of const non-class type (or array thereof)
  4966. if (Diagnose)
  4967. S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
  4968. << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
  4969. return true;
  4970. }
  4971. }
  4972. if (FieldRecord) {
  4973. // Some additional restrictions exist on the variant members.
  4974. if (!inUnion() && FieldRecord->isUnion() &&
  4975. FieldRecord->isAnonymousStructOrUnion()) {
  4976. bool AllVariantFieldsAreConst = true;
  4977. // FIXME: Handle anonymous unions declared within anonymous unions.
  4978. for (auto *UI : FieldRecord->fields()) {
  4979. QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
  4980. if (!UnionFieldType.isConstQualified())
  4981. AllVariantFieldsAreConst = false;
  4982. CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
  4983. if (UnionFieldRecord &&
  4984. shouldDeleteForClassSubobject(UnionFieldRecord, UI,
  4985. UnionFieldType.getCVRQualifiers()))
  4986. return true;
  4987. }
  4988. // At least one member in each anonymous union must be non-const
  4989. if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
  4990. !FieldRecord->field_empty()) {
  4991. if (Diagnose)
  4992. S.Diag(FieldRecord->getLocation(),
  4993. diag::note_deleted_default_ctor_all_const)
  4994. << MD->getParent() << /*anonymous union*/1;
  4995. return true;
  4996. }
  4997. // Don't check the implicit member of the anonymous union type.
  4998. // This is technically non-conformant, but sanity demands it.
  4999. return false;
  5000. }
  5001. if (shouldDeleteForClassSubobject(FieldRecord, FD,
  5002. FieldType.getCVRQualifiers()))
  5003. return true;
  5004. }
  5005. return false;
  5006. }
  5007. /// C++11 [class.ctor] p5:
  5008. /// A defaulted default constructor for a class X is defined as deleted if
  5009. /// X is a union and all of its variant members are of const-qualified type.
  5010. bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
  5011. // This is a silly definition, because it gives an empty union a deleted
  5012. // default constructor. Don't do that.
  5013. if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
  5014. !MD->getParent()->field_empty()) {
  5015. if (Diagnose)
  5016. S.Diag(MD->getParent()->getLocation(),
  5017. diag::note_deleted_default_ctor_all_const)
  5018. << MD->getParent() << /*not anonymous union*/0;
  5019. return true;
  5020. }
  5021. return false;
  5022. }
  5023. /// Determine whether a defaulted special member function should be defined as
  5024. /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
  5025. /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
  5026. bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
  5027. bool Diagnose) {
  5028. if (MD->isInvalidDecl())
  5029. return false;
  5030. CXXRecordDecl *RD = MD->getParent();
  5031. assert(!RD->isDependentType() && "do deletion after instantiation");
  5032. if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
  5033. return false;
  5034. // C++11 [expr.lambda.prim]p19:
  5035. // The closure type associated with a lambda-expression has a
  5036. // deleted (8.4.3) default constructor and a deleted copy
  5037. // assignment operator.
  5038. if (RD->isLambda() &&
  5039. (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
  5040. if (Diagnose)
  5041. Diag(RD->getLocation(), diag::note_lambda_decl);
  5042. return true;
  5043. }
  5044. // For an anonymous struct or union, the copy and assignment special members
  5045. // will never be used, so skip the check. For an anonymous union declared at
  5046. // namespace scope, the constructor and destructor are used.
  5047. if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
  5048. RD->isAnonymousStructOrUnion())
  5049. return false;
  5050. // C++11 [class.copy]p7, p18:
  5051. // If the class definition declares a move constructor or move assignment
  5052. // operator, an implicitly declared copy constructor or copy assignment
  5053. // operator is defined as deleted.
  5054. if (MD->isImplicit() &&
  5055. (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
  5056. CXXMethodDecl *UserDeclaredMove = nullptr;
  5057. // In Microsoft mode, a user-declared move only causes the deletion of the
  5058. // corresponding copy operation, not both copy operations.
  5059. if (RD->hasUserDeclaredMoveConstructor() &&
  5060. (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
  5061. if (!Diagnose) return true;
  5062. // Find any user-declared move constructor.
  5063. for (auto *I : RD->ctors()) {
  5064. if (I->isMoveConstructor()) {
  5065. UserDeclaredMove = I;
  5066. break;
  5067. }
  5068. }
  5069. assert(UserDeclaredMove);
  5070. } else if (RD->hasUserDeclaredMoveAssignment() &&
  5071. (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
  5072. if (!Diagnose) return true;
  5073. // Find any user-declared move assignment operator.
  5074. for (auto *I : RD->methods()) {
  5075. if (I->isMoveAssignmentOperator()) {
  5076. UserDeclaredMove = I;
  5077. break;
  5078. }
  5079. }
  5080. assert(UserDeclaredMove);
  5081. }
  5082. if (UserDeclaredMove) {
  5083. Diag(UserDeclaredMove->getLocation(),
  5084. diag::note_deleted_copy_user_declared_move)
  5085. << (CSM == CXXCopyAssignment) << RD
  5086. << UserDeclaredMove->isMoveAssignmentOperator();
  5087. return true;
  5088. }
  5089. }
  5090. // Do access control from the special member function
  5091. ContextRAII MethodContext(*this, MD);
  5092. // C++11 [class.dtor]p5:
  5093. // -- for a virtual destructor, lookup of the non-array deallocation function
  5094. // results in an ambiguity or in a function that is deleted or inaccessible
  5095. if (CSM == CXXDestructor && MD->isVirtual()) {
  5096. FunctionDecl *OperatorDelete = nullptr;
  5097. DeclarationName Name =
  5098. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  5099. if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
  5100. OperatorDelete, false)) {
  5101. if (Diagnose)
  5102. Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
  5103. return true;
  5104. }
  5105. }
  5106. SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
  5107. for (auto &BI : RD->bases())
  5108. if (!BI.isVirtual() &&
  5109. SMI.shouldDeleteForBase(&BI))
  5110. return true;
  5111. // Per DR1611, do not consider virtual bases of constructors of abstract
  5112. // classes, since we are not going to construct them.
  5113. if (!RD->isAbstract() || !SMI.IsConstructor) {
  5114. for (auto &BI : RD->vbases())
  5115. if (SMI.shouldDeleteForBase(&BI))
  5116. return true;
  5117. }
  5118. for (auto *FI : RD->fields())
  5119. if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
  5120. SMI.shouldDeleteForField(FI))
  5121. return true;
  5122. if (SMI.shouldDeleteForAllConstMembers())
  5123. return true;
  5124. if (getLangOpts().CUDA) {
  5125. // We should delete the special member in CUDA mode if target inference
  5126. // failed.
  5127. return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
  5128. Diagnose);
  5129. }
  5130. return false;
  5131. }
  5132. /// Perform lookup for a special member of the specified kind, and determine
  5133. /// whether it is trivial. If the triviality can be determined without the
  5134. /// lookup, skip it. This is intended for use when determining whether a
  5135. /// special member of a containing object is trivial, and thus does not ever
  5136. /// perform overload resolution for default constructors.
  5137. ///
  5138. /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
  5139. /// member that was most likely to be intended to be trivial, if any.
  5140. static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
  5141. Sema::CXXSpecialMember CSM, unsigned Quals,
  5142. bool ConstRHS, CXXMethodDecl **Selected) {
  5143. if (Selected)
  5144. *Selected = nullptr;
  5145. switch (CSM) {
  5146. case Sema::CXXInvalid:
  5147. llvm_unreachable("not a special member");
  5148. case Sema::CXXDefaultConstructor:
  5149. // C++11 [class.ctor]p5:
  5150. // A default constructor is trivial if:
  5151. // - all the [direct subobjects] have trivial default constructors
  5152. //
  5153. // Note, no overload resolution is performed in this case.
  5154. if (RD->hasTrivialDefaultConstructor())
  5155. return true;
  5156. if (Selected) {
  5157. // If there's a default constructor which could have been trivial, dig it
  5158. // out. Otherwise, if there's any user-provided default constructor, point
  5159. // to that as an example of why there's not a trivial one.
  5160. CXXConstructorDecl *DefCtor = nullptr;
  5161. if (RD->needsImplicitDefaultConstructor())
  5162. S.DeclareImplicitDefaultConstructor(RD);
  5163. for (auto *CI : RD->ctors()) {
  5164. if (!CI->isDefaultConstructor())
  5165. continue;
  5166. DefCtor = CI;
  5167. if (!DefCtor->isUserProvided())
  5168. break;
  5169. }
  5170. *Selected = DefCtor;
  5171. }
  5172. return false;
  5173. case Sema::CXXDestructor:
  5174. // C++11 [class.dtor]p5:
  5175. // A destructor is trivial if:
  5176. // - all the direct [subobjects] have trivial destructors
  5177. if (RD->hasTrivialDestructor())
  5178. return true;
  5179. if (Selected) {
  5180. if (RD->needsImplicitDestructor())
  5181. S.DeclareImplicitDestructor(RD);
  5182. *Selected = RD->getDestructor();
  5183. }
  5184. return false;
  5185. case Sema::CXXCopyConstructor:
  5186. // C++11 [class.copy]p12:
  5187. // A copy constructor is trivial if:
  5188. // - the constructor selected to copy each direct [subobject] is trivial
  5189. if (RD->hasTrivialCopyConstructor()) {
  5190. if (Quals == Qualifiers::Const)
  5191. // We must either select the trivial copy constructor or reach an
  5192. // ambiguity; no need to actually perform overload resolution.
  5193. return true;
  5194. } else if (!Selected) {
  5195. return false;
  5196. }
  5197. // In C++98, we are not supposed to perform overload resolution here, but we
  5198. // treat that as a language defect, as suggested on cxx-abi-dev, to treat
  5199. // cases like B as having a non-trivial copy constructor:
  5200. // struct A { template<typename T> A(T&); };
  5201. // struct B { mutable A a; };
  5202. goto NeedOverloadResolution;
  5203. case Sema::CXXCopyAssignment:
  5204. // C++11 [class.copy]p25:
  5205. // A copy assignment operator is trivial if:
  5206. // - the assignment operator selected to copy each direct [subobject] is
  5207. // trivial
  5208. if (RD->hasTrivialCopyAssignment()) {
  5209. if (Quals == Qualifiers::Const)
  5210. return true;
  5211. } else if (!Selected) {
  5212. return false;
  5213. }
  5214. // In C++98, we are not supposed to perform overload resolution here, but we
  5215. // treat that as a language defect.
  5216. goto NeedOverloadResolution;
  5217. case Sema::CXXMoveConstructor:
  5218. case Sema::CXXMoveAssignment:
  5219. NeedOverloadResolution:
  5220. Sema::SpecialMemberOverloadResult *SMOR =
  5221. lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
  5222. // The standard doesn't describe how to behave if the lookup is ambiguous.
  5223. // We treat it as not making the member non-trivial, just like the standard
  5224. // mandates for the default constructor. This should rarely matter, because
  5225. // the member will also be deleted.
  5226. if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
  5227. return true;
  5228. if (!SMOR->getMethod()) {
  5229. assert(SMOR->getKind() ==
  5230. Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
  5231. return false;
  5232. }
  5233. // We deliberately don't check if we found a deleted special member. We're
  5234. // not supposed to!
  5235. if (Selected)
  5236. *Selected = SMOR->getMethod();
  5237. return SMOR->getMethod()->isTrivial();
  5238. }
  5239. llvm_unreachable("unknown special method kind");
  5240. }
  5241. static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
  5242. for (auto *CI : RD->ctors())
  5243. if (!CI->isImplicit())
  5244. return CI;
  5245. // Look for constructor templates.
  5246. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
  5247. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
  5248. if (CXXConstructorDecl *CD =
  5249. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
  5250. return CD;
  5251. }
  5252. return nullptr;
  5253. }
  5254. /// The kind of subobject we are checking for triviality. The values of this
  5255. /// enumeration are used in diagnostics.
  5256. enum TrivialSubobjectKind {
  5257. /// The subobject is a base class.
  5258. TSK_BaseClass,
  5259. /// The subobject is a non-static data member.
  5260. TSK_Field,
  5261. /// The object is actually the complete object.
  5262. TSK_CompleteObject
  5263. };
  5264. /// Check whether the special member selected for a given type would be trivial.
  5265. static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
  5266. QualType SubType, bool ConstRHS,
  5267. Sema::CXXSpecialMember CSM,
  5268. TrivialSubobjectKind Kind,
  5269. bool Diagnose) {
  5270. CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
  5271. if (!SubRD)
  5272. return true;
  5273. CXXMethodDecl *Selected;
  5274. if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
  5275. ConstRHS, Diagnose ? &Selected : nullptr))
  5276. return true;
  5277. if (Diagnose) {
  5278. if (ConstRHS)
  5279. SubType.addConst();
  5280. if (!Selected && CSM == Sema::CXXDefaultConstructor) {
  5281. S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
  5282. << Kind << SubType.getUnqualifiedType();
  5283. if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
  5284. S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
  5285. } else if (!Selected)
  5286. S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
  5287. << Kind << SubType.getUnqualifiedType() << CSM << SubType;
  5288. else if (Selected->isUserProvided()) {
  5289. if (Kind == TSK_CompleteObject)
  5290. S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
  5291. << Kind << SubType.getUnqualifiedType() << CSM;
  5292. else {
  5293. S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
  5294. << Kind << SubType.getUnqualifiedType() << CSM;
  5295. S.Diag(Selected->getLocation(), diag::note_declared_at);
  5296. }
  5297. } else {
  5298. if (Kind != TSK_CompleteObject)
  5299. S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
  5300. << Kind << SubType.getUnqualifiedType() << CSM;
  5301. // Explain why the defaulted or deleted special member isn't trivial.
  5302. S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
  5303. }
  5304. }
  5305. return false;
  5306. }
  5307. /// Check whether the members of a class type allow a special member to be
  5308. /// trivial.
  5309. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
  5310. Sema::CXXSpecialMember CSM,
  5311. bool ConstArg, bool Diagnose) {
  5312. for (const auto *FI : RD->fields()) {
  5313. if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
  5314. continue;
  5315. QualType FieldType = S.Context.getBaseElementType(FI->getType());
  5316. // Pretend anonymous struct or union members are members of this class.
  5317. if (FI->isAnonymousStructOrUnion()) {
  5318. if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
  5319. CSM, ConstArg, Diagnose))
  5320. return false;
  5321. continue;
  5322. }
  5323. // C++11 [class.ctor]p5:
  5324. // A default constructor is trivial if [...]
  5325. // -- no non-static data member of its class has a
  5326. // brace-or-equal-initializer
  5327. if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
  5328. if (Diagnose)
  5329. S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
  5330. return false;
  5331. }
  5332. // Objective C ARC 4.3.5:
  5333. // [...] nontrivally ownership-qualified types are [...] not trivially
  5334. // default constructible, copy constructible, move constructible, copy
  5335. // assignable, move assignable, or destructible [...]
  5336. if (S.getLangOpts().ObjCAutoRefCount &&
  5337. FieldType.hasNonTrivialObjCLifetime()) {
  5338. if (Diagnose)
  5339. S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
  5340. << RD << FieldType.getObjCLifetime();
  5341. return false;
  5342. }
  5343. bool ConstRHS = ConstArg && !FI->isMutable();
  5344. if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
  5345. CSM, TSK_Field, Diagnose))
  5346. return false;
  5347. }
  5348. return true;
  5349. }
  5350. /// Diagnose why the specified class does not have a trivial special member of
  5351. /// the given kind.
  5352. void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
  5353. QualType Ty = Context.getRecordType(RD);
  5354. bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
  5355. checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
  5356. TSK_CompleteObject, /*Diagnose*/true);
  5357. }
  5358. /// Determine whether a defaulted or deleted special member function is trivial,
  5359. /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
  5360. /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
  5361. bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
  5362. bool Diagnose) {
  5363. assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
  5364. CXXRecordDecl *RD = MD->getParent();
  5365. bool ConstArg = false;
  5366. // C++11 [class.copy]p12, p25: [DR1593]
  5367. // A [special member] is trivial if [...] its parameter-type-list is
  5368. // equivalent to the parameter-type-list of an implicit declaration [...]
  5369. switch (CSM) {
  5370. case CXXDefaultConstructor:
  5371. case CXXDestructor:
  5372. // Trivial default constructors and destructors cannot have parameters.
  5373. break;
  5374. case CXXCopyConstructor:
  5375. case CXXCopyAssignment: {
  5376. // Trivial copy operations always have const, non-volatile parameter types.
  5377. ConstArg = true;
  5378. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  5379. const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
  5380. if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
  5381. if (Diagnose)
  5382. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  5383. << Param0->getSourceRange() << Param0->getType()
  5384. << Context.getLValueReferenceType(
  5385. Context.getRecordType(RD).withConst());
  5386. return false;
  5387. }
  5388. break;
  5389. }
  5390. case CXXMoveConstructor:
  5391. case CXXMoveAssignment: {
  5392. // Trivial move operations always have non-cv-qualified parameters.
  5393. const ParmVarDecl *Param0 = MD->getParamDecl(0);
  5394. const RValueReferenceType *RT =
  5395. Param0->getType()->getAs<RValueReferenceType>();
  5396. if (!RT || RT->getPointeeType().getCVRQualifiers()) {
  5397. if (Diagnose)
  5398. Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
  5399. << Param0->getSourceRange() << Param0->getType()
  5400. << Context.getRValueReferenceType(Context.getRecordType(RD));
  5401. return false;
  5402. }
  5403. break;
  5404. }
  5405. case CXXInvalid:
  5406. llvm_unreachable("not a special member");
  5407. }
  5408. if (MD->getMinRequiredArguments() < MD->getNumParams()) {
  5409. if (Diagnose)
  5410. Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
  5411. diag::note_nontrivial_default_arg)
  5412. << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
  5413. return false;
  5414. }
  5415. if (MD->isVariadic()) {
  5416. if (Diagnose)
  5417. Diag(MD->getLocation(), diag::note_nontrivial_variadic);
  5418. return false;
  5419. }
  5420. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  5421. // A copy/move [constructor or assignment operator] is trivial if
  5422. // -- the [member] selected to copy/move each direct base class subobject
  5423. // is trivial
  5424. //
  5425. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  5426. // A [default constructor or destructor] is trivial if
  5427. // -- all the direct base classes have trivial [default constructors or
  5428. // destructors]
  5429. for (const auto &BI : RD->bases())
  5430. if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
  5431. ConstArg, CSM, TSK_BaseClass, Diagnose))
  5432. return false;
  5433. // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
  5434. // A copy/move [constructor or assignment operator] for a class X is
  5435. // trivial if
  5436. // -- for each non-static data member of X that is of class type (or array
  5437. // thereof), the constructor selected to copy/move that member is
  5438. // trivial
  5439. //
  5440. // C++11 [class.copy]p12, C++11 [class.copy]p25:
  5441. // A [default constructor or destructor] is trivial if
  5442. // -- for all of the non-static data members of its class that are of class
  5443. // type (or array thereof), each such class has a trivial [default
  5444. // constructor or destructor]
  5445. if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
  5446. return false;
  5447. // C++11 [class.dtor]p5:
  5448. // A destructor is trivial if [...]
  5449. // -- the destructor is not virtual
  5450. if (CSM == CXXDestructor && MD->isVirtual()) {
  5451. if (Diagnose)
  5452. Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
  5453. return false;
  5454. }
  5455. // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
  5456. // A [special member] for class X is trivial if [...]
  5457. // -- class X has no virtual functions and no virtual base classes
  5458. if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
  5459. if (!Diagnose)
  5460. return false;
  5461. if (RD->getNumVBases()) {
  5462. // Check for virtual bases. We already know that the corresponding
  5463. // member in all bases is trivial, so vbases must all be direct.
  5464. CXXBaseSpecifier &BS = *RD->vbases_begin();
  5465. assert(BS.isVirtual());
  5466. Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
  5467. return false;
  5468. }
  5469. // Must have a virtual method.
  5470. for (const auto *MI : RD->methods()) {
  5471. if (MI->isVirtual()) {
  5472. SourceLocation MLoc = MI->getLocStart();
  5473. Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
  5474. return false;
  5475. }
  5476. }
  5477. llvm_unreachable("dynamic class with no vbases and no virtual functions");
  5478. }
  5479. // Looks like it's trivial!
  5480. return true;
  5481. }
  5482. /// \brief Data used with FindHiddenVirtualMethod
  5483. namespace {
  5484. struct FindHiddenVirtualMethodData {
  5485. Sema *S;
  5486. CXXMethodDecl *Method;
  5487. llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
  5488. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  5489. };
  5490. }
  5491. /// \brief Check whether any most overriden method from MD in Methods
  5492. static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
  5493. const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  5494. if (MD->size_overridden_methods() == 0)
  5495. return Methods.count(MD->getCanonicalDecl());
  5496. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5497. E = MD->end_overridden_methods();
  5498. I != E; ++I)
  5499. if (CheckMostOverridenMethods(*I, Methods))
  5500. return true;
  5501. return false;
  5502. }
  5503. /// \brief Member lookup function that determines whether a given C++
  5504. /// method overloads virtual methods in a base class without overriding any,
  5505. /// to be used with CXXRecordDecl::lookupInBases().
  5506. static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
  5507. CXXBasePath &Path,
  5508. void *UserData) {
  5509. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  5510. FindHiddenVirtualMethodData &Data
  5511. = *static_cast<FindHiddenVirtualMethodData*>(UserData);
  5512. DeclarationName Name = Data.Method->getDeclName();
  5513. assert(Name.getNameKind() == DeclarationName::Identifier);
  5514. bool foundSameNameMethod = false;
  5515. SmallVector<CXXMethodDecl *, 8> overloadedMethods;
  5516. for (Path.Decls = BaseRecord->lookup(Name);
  5517. !Path.Decls.empty();
  5518. Path.Decls = Path.Decls.slice(1)) {
  5519. NamedDecl *D = Path.Decls.front();
  5520. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5521. MD = MD->getCanonicalDecl();
  5522. foundSameNameMethod = true;
  5523. // Interested only in hidden virtual methods.
  5524. if (!MD->isVirtual())
  5525. continue;
  5526. // If the method we are checking overrides a method from its base
  5527. // don't warn about the other overloaded methods. Clang deviates from GCC
  5528. // by only diagnosing overloads of inherited virtual functions that do not
  5529. // override any other virtual functions in the base. GCC's
  5530. // -Woverloaded-virtual diagnoses any derived function hiding a virtual
  5531. // function from a base class. These cases may be better served by a
  5532. // warning (not specific to virtual functions) on call sites when the call
  5533. // would select a different function from the base class, were it visible.
  5534. // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
  5535. if (!Data.S->IsOverload(Data.Method, MD, false))
  5536. return true;
  5537. // Collect the overload only if its hidden.
  5538. if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
  5539. overloadedMethods.push_back(MD);
  5540. }
  5541. }
  5542. if (foundSameNameMethod)
  5543. Data.OverloadedMethods.append(overloadedMethods.begin(),
  5544. overloadedMethods.end());
  5545. return foundSameNameMethod;
  5546. }
  5547. /// \brief Add the most overriden methods from MD to Methods
  5548. static void AddMostOverridenMethods(const CXXMethodDecl *MD,
  5549. llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
  5550. if (MD->size_overridden_methods() == 0)
  5551. Methods.insert(MD->getCanonicalDecl());
  5552. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5553. E = MD->end_overridden_methods();
  5554. I != E; ++I)
  5555. AddMostOverridenMethods(*I, Methods);
  5556. }
  5557. /// \brief Check if a method overloads virtual methods in a base class without
  5558. /// overriding any.
  5559. void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
  5560. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  5561. if (!MD->getDeclName().isIdentifier())
  5562. return;
  5563. CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
  5564. /*bool RecordPaths=*/false,
  5565. /*bool DetectVirtual=*/false);
  5566. FindHiddenVirtualMethodData Data;
  5567. Data.Method = MD;
  5568. Data.S = this;
  5569. // Keep the base methods that were overriden or introduced in the subclass
  5570. // by 'using' in a set. A base method not in this set is hidden.
  5571. CXXRecordDecl *DC = MD->getParent();
  5572. DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
  5573. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  5574. NamedDecl *ND = *I;
  5575. if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
  5576. ND = shad->getTargetDecl();
  5577. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  5578. AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
  5579. }
  5580. if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
  5581. OverloadedMethods = Data.OverloadedMethods;
  5582. }
  5583. void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
  5584. SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
  5585. for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
  5586. CXXMethodDecl *overloadedMD = OverloadedMethods[i];
  5587. PartialDiagnostic PD = PDiag(
  5588. diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
  5589. HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
  5590. Diag(overloadedMD->getLocation(), PD);
  5591. }
  5592. }
  5593. /// \brief Diagnose methods which overload virtual methods in a base class
  5594. /// without overriding any.
  5595. void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
  5596. if (MD->isInvalidDecl())
  5597. return;
  5598. if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
  5599. return;
  5600. SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
  5601. FindHiddenVirtualMethods(MD, OverloadedMethods);
  5602. if (!OverloadedMethods.empty()) {
  5603. Diag(MD->getLocation(), diag::warn_overloaded_virtual)
  5604. << MD << (OverloadedMethods.size() > 1);
  5605. NoteHiddenVirtualMethods(MD, OverloadedMethods);
  5606. }
  5607. }
  5608. void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
  5609. Decl *TagDecl,
  5610. SourceLocation LBrac,
  5611. SourceLocation RBrac,
  5612. AttributeList *AttrList) {
  5613. if (!TagDecl)
  5614. return;
  5615. AdjustDeclIfTemplate(TagDecl);
  5616. for (const AttributeList* l = AttrList; l; l = l->getNext()) {
  5617. if (l->getKind() != AttributeList::AT_Visibility)
  5618. continue;
  5619. l->setInvalid();
  5620. Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
  5621. l->getName();
  5622. }
  5623. ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
  5624. // strict aliasing violation!
  5625. reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
  5626. FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
  5627. CheckCompletedCXXClass(
  5628. dyn_cast_or_null<CXXRecordDecl>(TagDecl));
  5629. }
  5630. /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
  5631. /// special functions, such as the default constructor, copy
  5632. /// constructor, or destructor, to the given C++ class (C++
  5633. /// [special]p1). This routine can only be executed just before the
  5634. /// definition of the class is complete.
  5635. void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
  5636. if (!ClassDecl->hasUserDeclaredConstructor())
  5637. ++ASTContext::NumImplicitDefaultConstructors;
  5638. if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
  5639. ++ASTContext::NumImplicitCopyConstructors;
  5640. // If the properties or semantics of the copy constructor couldn't be
  5641. // determined while the class was being declared, force a declaration
  5642. // of it now.
  5643. if (ClassDecl->needsOverloadResolutionForCopyConstructor())
  5644. DeclareImplicitCopyConstructor(ClassDecl);
  5645. }
  5646. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
  5647. ++ASTContext::NumImplicitMoveConstructors;
  5648. if (ClassDecl->needsOverloadResolutionForMoveConstructor())
  5649. DeclareImplicitMoveConstructor(ClassDecl);
  5650. }
  5651. if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
  5652. ++ASTContext::NumImplicitCopyAssignmentOperators;
  5653. // If we have a dynamic class, then the copy assignment operator may be
  5654. // virtual, so we have to declare it immediately. This ensures that, e.g.,
  5655. // it shows up in the right place in the vtable and that we diagnose
  5656. // problems with the implicit exception specification.
  5657. if (ClassDecl->isDynamicClass() ||
  5658. ClassDecl->needsOverloadResolutionForCopyAssignment())
  5659. DeclareImplicitCopyAssignment(ClassDecl);
  5660. }
  5661. if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
  5662. ++ASTContext::NumImplicitMoveAssignmentOperators;
  5663. // Likewise for the move assignment operator.
  5664. if (ClassDecl->isDynamicClass() ||
  5665. ClassDecl->needsOverloadResolutionForMoveAssignment())
  5666. DeclareImplicitMoveAssignment(ClassDecl);
  5667. }
  5668. if (!ClassDecl->hasUserDeclaredDestructor()) {
  5669. ++ASTContext::NumImplicitDestructors;
  5670. // If we have a dynamic class, then the destructor may be virtual, so we
  5671. // have to declare the destructor immediately. This ensures that, e.g., it
  5672. // shows up in the right place in the vtable and that we diagnose problems
  5673. // with the implicit exception specification.
  5674. if (ClassDecl->isDynamicClass() ||
  5675. ClassDecl->needsOverloadResolutionForDestructor())
  5676. DeclareImplicitDestructor(ClassDecl);
  5677. }
  5678. }
  5679. unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
  5680. if (!D)
  5681. return 0;
  5682. // The order of template parameters is not important here. All names
  5683. // get added to the same scope.
  5684. SmallVector<TemplateParameterList *, 4> ParameterLists;
  5685. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  5686. D = TD->getTemplatedDecl();
  5687. if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
  5688. ParameterLists.push_back(PSD->getTemplateParameters());
  5689. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  5690. for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
  5691. ParameterLists.push_back(DD->getTemplateParameterList(i));
  5692. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  5693. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  5694. ParameterLists.push_back(FTD->getTemplateParameters());
  5695. }
  5696. }
  5697. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  5698. for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
  5699. ParameterLists.push_back(TD->getTemplateParameterList(i));
  5700. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
  5701. if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
  5702. ParameterLists.push_back(CTD->getTemplateParameters());
  5703. }
  5704. }
  5705. unsigned Count = 0;
  5706. for (TemplateParameterList *Params : ParameterLists) {
  5707. if (Params->size() > 0)
  5708. // Ignore explicit specializations; they don't contribute to the template
  5709. // depth.
  5710. ++Count;
  5711. for (NamedDecl *Param : *Params) {
  5712. if (Param->getDeclName()) {
  5713. S->AddDecl(Param);
  5714. IdResolver.AddDecl(Param);
  5715. }
  5716. }
  5717. }
  5718. return Count;
  5719. }
  5720. void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  5721. if (!RecordD) return;
  5722. AdjustDeclIfTemplate(RecordD);
  5723. CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
  5724. PushDeclContext(S, Record);
  5725. }
  5726. void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
  5727. if (!RecordD) return;
  5728. PopDeclContext();
  5729. }
  5730. /// This is used to implement the constant expression evaluation part of the
  5731. /// attribute enable_if extension. There is nothing in standard C++ which would
  5732. /// require reentering parameters.
  5733. void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
  5734. if (!Param)
  5735. return;
  5736. S->AddDecl(Param);
  5737. if (Param->getDeclName())
  5738. IdResolver.AddDecl(Param);
  5739. }
  5740. /// ActOnStartDelayedCXXMethodDeclaration - We have completed
  5741. /// parsing a top-level (non-nested) C++ class, and we are now
  5742. /// parsing those parts of the given Method declaration that could
  5743. /// not be parsed earlier (C++ [class.mem]p2), such as default
  5744. /// arguments. This action should enter the scope of the given
  5745. /// Method declaration as if we had just parsed the qualified method
  5746. /// name. However, it should not bring the parameters into scope;
  5747. /// that will be performed by ActOnDelayedCXXMethodParameter.
  5748. void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  5749. }
  5750. /// ActOnDelayedCXXMethodParameter - We've already started a delayed
  5751. /// C++ method declaration. We're (re-)introducing the given
  5752. /// function parameter into scope for use in parsing later parts of
  5753. /// the method declaration. For example, we could see an
  5754. /// ActOnParamDefaultArgument event for this parameter.
  5755. void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
  5756. if (!ParamD)
  5757. return;
  5758. ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
  5759. // If this parameter has an unparsed default argument, clear it out
  5760. // to make way for the parsed default argument.
  5761. if (Param->hasUnparsedDefaultArg())
  5762. Param->setDefaultArg(nullptr);
  5763. S->AddDecl(Param);
  5764. if (Param->getDeclName())
  5765. IdResolver.AddDecl(Param);
  5766. }
  5767. /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
  5768. /// processing the delayed method declaration for Method. The method
  5769. /// declaration is now considered finished. There may be a separate
  5770. /// ActOnStartOfFunctionDef action later (not necessarily
  5771. /// immediately!) for this method, if it was also defined inside the
  5772. /// class body.
  5773. void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
  5774. if (!MethodD)
  5775. return;
  5776. AdjustDeclIfTemplate(MethodD);
  5777. FunctionDecl *Method = cast<FunctionDecl>(MethodD);
  5778. // Now that we have our default arguments, check the constructor
  5779. // again. It could produce additional diagnostics or affect whether
  5780. // the class has implicitly-declared destructors, among other
  5781. // things.
  5782. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
  5783. CheckConstructor(Constructor);
  5784. // Check the default arguments, which we may have added.
  5785. if (!Method->isInvalidDecl())
  5786. CheckCXXDefaultArguments(Method);
  5787. }
  5788. /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
  5789. /// the well-formedness of the constructor declarator @p D with type @p
  5790. /// R. If there are any errors in the declarator, this routine will
  5791. /// emit diagnostics and set the invalid bit to true. In any case, the type
  5792. /// will be updated to reflect a well-formed type for the constructor and
  5793. /// returned.
  5794. QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
  5795. StorageClass &SC) {
  5796. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  5797. // C++ [class.ctor]p3:
  5798. // A constructor shall not be virtual (10.3) or static (9.4). A
  5799. // constructor can be invoked for a const, volatile or const
  5800. // volatile object. A constructor shall not be declared const,
  5801. // volatile, or const volatile (9.3.2).
  5802. if (isVirtual) {
  5803. if (!D.isInvalidType())
  5804. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  5805. << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
  5806. << SourceRange(D.getIdentifierLoc());
  5807. D.setInvalidType();
  5808. }
  5809. if (SC == SC_Static) {
  5810. if (!D.isInvalidType())
  5811. Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
  5812. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  5813. << SourceRange(D.getIdentifierLoc());
  5814. D.setInvalidType();
  5815. SC = SC_None;
  5816. }
  5817. if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  5818. diagnoseIgnoredQualifiers(
  5819. diag::err_constructor_return_type, TypeQuals, SourceLocation(),
  5820. D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
  5821. D.getDeclSpec().getRestrictSpecLoc(),
  5822. D.getDeclSpec().getAtomicSpecLoc());
  5823. D.setInvalidType();
  5824. }
  5825. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  5826. if (FTI.TypeQuals != 0) {
  5827. if (FTI.TypeQuals & Qualifiers::Const)
  5828. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  5829. << "const" << SourceRange(D.getIdentifierLoc());
  5830. if (FTI.TypeQuals & Qualifiers::Volatile)
  5831. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  5832. << "volatile" << SourceRange(D.getIdentifierLoc());
  5833. if (FTI.TypeQuals & Qualifiers::Restrict)
  5834. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
  5835. << "restrict" << SourceRange(D.getIdentifierLoc());
  5836. D.setInvalidType();
  5837. }
  5838. // C++0x [class.ctor]p4:
  5839. // A constructor shall not be declared with a ref-qualifier.
  5840. if (FTI.hasRefQualifier()) {
  5841. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
  5842. << FTI.RefQualifierIsLValueRef
  5843. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  5844. D.setInvalidType();
  5845. }
  5846. // Rebuild the function type "R" without any type qualifiers (in
  5847. // case any of the errors above fired) and with "void" as the
  5848. // return type, since constructors don't have return types.
  5849. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  5850. if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
  5851. return R;
  5852. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  5853. EPI.TypeQuals = 0;
  5854. EPI.RefQualifier = RQ_None;
  5855. return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI, None); // HLSL Change - constructors members are all-in params
  5856. }
  5857. /// CheckConstructor - Checks a fully-formed constructor for
  5858. /// well-formedness, issuing any diagnostics required. Returns true if
  5859. /// the constructor declarator is invalid.
  5860. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
  5861. CXXRecordDecl *ClassDecl
  5862. = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
  5863. if (!ClassDecl)
  5864. return Constructor->setInvalidDecl();
  5865. // C++ [class.copy]p3:
  5866. // A declaration of a constructor for a class X is ill-formed if
  5867. // its first parameter is of type (optionally cv-qualified) X and
  5868. // either there are no other parameters or else all other
  5869. // parameters have default arguments.
  5870. if (!Constructor->isInvalidDecl() &&
  5871. ((Constructor->getNumParams() == 1) ||
  5872. (Constructor->getNumParams() > 1 &&
  5873. Constructor->getParamDecl(1)->hasDefaultArg())) &&
  5874. Constructor->getTemplateSpecializationKind()
  5875. != TSK_ImplicitInstantiation) {
  5876. QualType ParamType = Constructor->getParamDecl(0)->getType();
  5877. QualType ClassTy = Context.getTagDeclType(ClassDecl);
  5878. if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
  5879. SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
  5880. const char *ConstRef
  5881. = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
  5882. : " const &";
  5883. Diag(ParamLoc, diag::err_constructor_byvalue_arg)
  5884. << FixItHint::CreateInsertion(ParamLoc, ConstRef);
  5885. // FIXME: Rather that making the constructor invalid, we should endeavor
  5886. // to fix the type.
  5887. Constructor->setInvalidDecl();
  5888. }
  5889. }
  5890. }
  5891. /// CheckDestructor - Checks a fully-formed destructor definition for
  5892. /// well-formedness, issuing any diagnostics required. Returns true
  5893. /// on error.
  5894. bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
  5895. CXXRecordDecl *RD = Destructor->getParent();
  5896. if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
  5897. SourceLocation Loc;
  5898. if (!Destructor->isImplicit())
  5899. Loc = Destructor->getLocation();
  5900. else
  5901. Loc = RD->getLocation();
  5902. // If we have a virtual destructor, look up the deallocation function
  5903. FunctionDecl *OperatorDelete = nullptr;
  5904. DeclarationName Name =
  5905. Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  5906. if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
  5907. return true;
  5908. // If there's no class-specific operator delete, look up the global
  5909. // non-array delete.
  5910. if (!OperatorDelete)
  5911. OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
  5912. MarkFunctionReferenced(Loc, OperatorDelete);
  5913. Destructor->setOperatorDelete(OperatorDelete);
  5914. }
  5915. return false;
  5916. }
  5917. /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
  5918. /// the well-formednes of the destructor declarator @p D with type @p
  5919. /// R. If there are any errors in the declarator, this routine will
  5920. /// emit diagnostics and set the declarator to invalid. Even if this happens,
  5921. /// will be updated to reflect a well-formed type for the destructor and
  5922. /// returned.
  5923. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
  5924. StorageClass& SC) {
  5925. // C++ [class.dtor]p1:
  5926. // [...] A typedef-name that names a class is a class-name
  5927. // (7.1.3); however, a typedef-name that names a class shall not
  5928. // be used as the identifier in the declarator for a destructor
  5929. // declaration.
  5930. QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
  5931. if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
  5932. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  5933. << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
  5934. else if (const TemplateSpecializationType *TST =
  5935. DeclaratorType->getAs<TemplateSpecializationType>())
  5936. if (TST->isTypeAlias())
  5937. Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
  5938. << DeclaratorType << 1;
  5939. // C++ [class.dtor]p2:
  5940. // A destructor is used to destroy objects of its class type. A
  5941. // destructor takes no parameters, and no return type can be
  5942. // specified for it (not even void). The address of a destructor
  5943. // shall not be taken. A destructor shall not be static. A
  5944. // destructor can be invoked for a const, volatile or const
  5945. // volatile object. A destructor shall not be declared const,
  5946. // volatile or const volatile (9.3.2).
  5947. if (SC == SC_Static) {
  5948. if (!D.isInvalidType())
  5949. Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
  5950. << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  5951. << SourceRange(D.getIdentifierLoc())
  5952. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5953. SC = SC_None;
  5954. }
  5955. if (!D.isInvalidType()) {
  5956. // Destructors don't have return types, but the parser will
  5957. // happily parse something like:
  5958. //
  5959. // class X {
  5960. // float ~X();
  5961. // };
  5962. //
  5963. // The return type will be eliminated later.
  5964. if (D.getDeclSpec().hasTypeSpecifier())
  5965. Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
  5966. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  5967. << SourceRange(D.getIdentifierLoc());
  5968. else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
  5969. diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
  5970. SourceLocation(),
  5971. D.getDeclSpec().getConstSpecLoc(),
  5972. D.getDeclSpec().getVolatileSpecLoc(),
  5973. D.getDeclSpec().getRestrictSpecLoc(),
  5974. D.getDeclSpec().getAtomicSpecLoc());
  5975. D.setInvalidType();
  5976. }
  5977. }
  5978. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  5979. if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
  5980. if (FTI.TypeQuals & Qualifiers::Const)
  5981. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  5982. << "const" << SourceRange(D.getIdentifierLoc());
  5983. if (FTI.TypeQuals & Qualifiers::Volatile)
  5984. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  5985. << "volatile" << SourceRange(D.getIdentifierLoc());
  5986. if (FTI.TypeQuals & Qualifiers::Restrict)
  5987. Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
  5988. << "restrict" << SourceRange(D.getIdentifierLoc());
  5989. D.setInvalidType();
  5990. }
  5991. // C++0x [class.dtor]p2:
  5992. // A destructor shall not be declared with a ref-qualifier.
  5993. if (FTI.hasRefQualifier()) {
  5994. Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
  5995. << FTI.RefQualifierIsLValueRef
  5996. << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
  5997. D.setInvalidType();
  5998. }
  5999. // Make sure we don't have any parameters.
  6000. if (FTIHasNonVoidParameters(FTI)) {
  6001. Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
  6002. // Delete the parameters.
  6003. FTI.freeParams();
  6004. D.setInvalidType();
  6005. }
  6006. // Make sure the destructor isn't variadic.
  6007. if (FTI.isVariadic) {
  6008. Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
  6009. D.setInvalidType();
  6010. }
  6011. // Rebuild the function type "R" without any type qualifiers or
  6012. // parameters (in case any of the errors above fired) and with
  6013. // "void" as the return type, since destructors don't have return
  6014. // types.
  6015. if (!D.isInvalidType())
  6016. return R;
  6017. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6018. FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
  6019. EPI.Variadic = false;
  6020. EPI.TypeQuals = 0;
  6021. EPI.RefQualifier = RQ_None;
  6022. return Context.getFunctionType(Context.VoidTy, None, EPI, None); // HLSL Change - no destructor args
  6023. }
  6024. static void extendLeft(SourceRange &R, const SourceRange &Before) {
  6025. if (Before.isInvalid())
  6026. return;
  6027. R.setBegin(Before.getBegin());
  6028. if (R.getEnd().isInvalid())
  6029. R.setEnd(Before.getEnd());
  6030. }
  6031. static void extendRight(SourceRange &R, const SourceRange &After) {
  6032. if (After.isInvalid())
  6033. return;
  6034. if (R.getBegin().isInvalid())
  6035. R.setBegin(After.getBegin());
  6036. R.setEnd(After.getEnd());
  6037. }
  6038. /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
  6039. /// well-formednes of the conversion function declarator @p D with
  6040. /// type @p R. If there are any errors in the declarator, this routine
  6041. /// will emit diagnostics and return true. Otherwise, it will return
  6042. /// false. Either way, the type @p R will be updated to reflect a
  6043. /// well-formed type for the conversion operator.
  6044. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
  6045. StorageClass& SC) {
  6046. // C++ [class.conv.fct]p1:
  6047. // Neither parameter types nor return type can be specified. The
  6048. // type of a conversion function (8.3.5) is "function taking no
  6049. // parameter returning conversion-type-id."
  6050. if (SC == SC_Static) {
  6051. if (!D.isInvalidType())
  6052. Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
  6053. << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
  6054. << D.getName().getSourceRange();
  6055. D.setInvalidType();
  6056. SC = SC_None;
  6057. }
  6058. TypeSourceInfo *ConvTSI = nullptr;
  6059. QualType ConvType =
  6060. GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
  6061. if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
  6062. // Conversion functions don't have return types, but the parser will
  6063. // happily parse something like:
  6064. //
  6065. // class X {
  6066. // float operator bool();
  6067. // };
  6068. //
  6069. // The return type will be changed later anyway.
  6070. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
  6071. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  6072. << SourceRange(D.getIdentifierLoc());
  6073. D.setInvalidType();
  6074. }
  6075. const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
  6076. // Make sure we don't have any parameters.
  6077. if (Proto->getNumParams() > 0) {
  6078. Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
  6079. // Delete the parameters.
  6080. D.getFunctionTypeInfo().freeParams();
  6081. D.setInvalidType();
  6082. } else if (Proto->isVariadic()) {
  6083. Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
  6084. D.setInvalidType();
  6085. }
  6086. // Diagnose "&operator bool()" and other such nonsense. This
  6087. // is actually a gcc extension which we don't support.
  6088. if (Proto->getReturnType() != ConvType) {
  6089. bool NeedsTypedef = false;
  6090. SourceRange Before, After;
  6091. // Walk the chunks and extract information on them for our diagnostic.
  6092. bool PastFunctionChunk = false;
  6093. for (auto &Chunk : D.type_objects()) {
  6094. switch (Chunk.Kind) {
  6095. case DeclaratorChunk::Function:
  6096. if (!PastFunctionChunk) {
  6097. if (Chunk.Fun.HasTrailingReturnType) {
  6098. TypeSourceInfo *TRT = nullptr;
  6099. GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
  6100. if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
  6101. }
  6102. PastFunctionChunk = true;
  6103. break;
  6104. }
  6105. // Fall through.
  6106. case DeclaratorChunk::Array:
  6107. NeedsTypedef = true;
  6108. extendRight(After, Chunk.getSourceRange());
  6109. break;
  6110. case DeclaratorChunk::Pointer:
  6111. case DeclaratorChunk::BlockPointer:
  6112. case DeclaratorChunk::Reference:
  6113. case DeclaratorChunk::MemberPointer:
  6114. extendLeft(Before, Chunk.getSourceRange());
  6115. break;
  6116. case DeclaratorChunk::Paren:
  6117. extendLeft(Before, Chunk.Loc);
  6118. extendRight(After, Chunk.EndLoc);
  6119. break;
  6120. }
  6121. }
  6122. SourceLocation Loc = Before.isValid() ? Before.getBegin() :
  6123. After.isValid() ? After.getBegin() :
  6124. D.getIdentifierLoc();
  6125. auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
  6126. DB << Before << After;
  6127. if (!NeedsTypedef) {
  6128. DB << /*don't need a typedef*/0;
  6129. // If we can provide a correct fix-it hint, do so.
  6130. if (After.isInvalid() && ConvTSI) {
  6131. SourceLocation InsertLoc =
  6132. PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
  6133. DB << FixItHint::CreateInsertion(InsertLoc, " ")
  6134. << FixItHint::CreateInsertionFromRange(
  6135. InsertLoc, CharSourceRange::getTokenRange(Before))
  6136. << FixItHint::CreateRemoval(Before);
  6137. }
  6138. } else if (!Proto->getReturnType()->isDependentType()) {
  6139. DB << /*typedef*/1 << Proto->getReturnType();
  6140. } else if (getLangOpts().CPlusPlus11) {
  6141. DB << /*alias template*/2 << Proto->getReturnType();
  6142. } else {
  6143. DB << /*might not be fixable*/3;
  6144. }
  6145. // Recover by incorporating the other type chunks into the result type.
  6146. // Note, this does *not* change the name of the function. This is compatible
  6147. // with the GCC extension:
  6148. // struct S { &operator int(); } s;
  6149. // int &r = s.operator int(); // ok in GCC
  6150. // S::operator int&() {} // error in GCC, function name is 'operator int'.
  6151. ConvType = Proto->getReturnType();
  6152. }
  6153. // C++ [class.conv.fct]p4:
  6154. // The conversion-type-id shall not represent a function type nor
  6155. // an array type.
  6156. if (ConvType->isArrayType()) {
  6157. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
  6158. ConvType = Context.getPointerType(ConvType);
  6159. D.setInvalidType();
  6160. } else if (ConvType->isFunctionType()) {
  6161. Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
  6162. ConvType = Context.getPointerType(ConvType);
  6163. D.setInvalidType();
  6164. }
  6165. // Rebuild the function type "R" without any parameters (in case any
  6166. // of the errors above fired) and with the conversion type as the
  6167. // return type.
  6168. if (D.isInvalidType())
  6169. R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo(), None); // HLSL Change
  6170. // C++0x explicit conversion operators.
  6171. if (D.getDeclSpec().isExplicitSpecified())
  6172. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6173. getLangOpts().CPlusPlus11 ?
  6174. diag::warn_cxx98_compat_explicit_conversion_functions :
  6175. diag::ext_explicit_conversion_functions)
  6176. << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
  6177. }
  6178. /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
  6179. /// the declaration of the given C++ conversion function. This routine
  6180. /// is responsible for recording the conversion function in the C++
  6181. /// class, if possible.
  6182. Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
  6183. assert(Conversion && "Expected to receive a conversion function declaration");
  6184. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
  6185. // Make sure we aren't redeclaring the conversion function.
  6186. QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
  6187. // C++ [class.conv.fct]p1:
  6188. // [...] A conversion function is never used to convert a
  6189. // (possibly cv-qualified) object to the (possibly cv-qualified)
  6190. // same object type (or a reference to it), to a (possibly
  6191. // cv-qualified) base class of that type (or a reference to it),
  6192. // or to (possibly cv-qualified) void.
  6193. // FIXME: Suppress this warning if the conversion function ends up being a
  6194. // virtual function that overrides a virtual function in a base class.
  6195. QualType ClassType
  6196. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  6197. if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
  6198. ConvType = ConvTypeRef->getPointeeType();
  6199. if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
  6200. Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  6201. /* Suppress diagnostics for instantiations. */;
  6202. else if (ConvType->isRecordType()) {
  6203. ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
  6204. if (ConvType == ClassType)
  6205. Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
  6206. << ClassType;
  6207. else if (IsDerivedFrom(ClassType, ConvType))
  6208. Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
  6209. << ClassType << ConvType;
  6210. } else if (ConvType->isVoidType()) {
  6211. Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
  6212. << ClassType << ConvType;
  6213. }
  6214. if (FunctionTemplateDecl *ConversionTemplate
  6215. = Conversion->getDescribedFunctionTemplate())
  6216. return ConversionTemplate;
  6217. return Conversion;
  6218. }
  6219. //===----------------------------------------------------------------------===//
  6220. // Namespace Handling
  6221. //===----------------------------------------------------------------------===//
  6222. /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
  6223. /// reopened.
  6224. static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
  6225. SourceLocation Loc,
  6226. IdentifierInfo *II, bool *IsInline,
  6227. NamespaceDecl *PrevNS) {
  6228. assert(*IsInline != PrevNS->isInline());
  6229. // HACK: Work around a bug in libstdc++4.6's <atomic>, where
  6230. // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
  6231. // inline namespaces, with the intention of bringing names into namespace std.
  6232. //
  6233. // We support this just well enough to get that case working; this is not
  6234. // sufficient to support reopening namespaces as inline in general.
  6235. if (*IsInline && II && II->getName().startswith("__atomic") &&
  6236. S.getSourceManager().isInSystemHeader(Loc)) {
  6237. // Mark all prior declarations of the namespace as inline.
  6238. for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
  6239. NS = NS->getPreviousDecl())
  6240. NS->setInline(*IsInline);
  6241. // Patch up the lookup table for the containing namespace. This isn't really
  6242. // correct, but it's good enough for this particular case.
  6243. for (auto *I : PrevNS->decls())
  6244. if (auto *ND = dyn_cast<NamedDecl>(I))
  6245. PrevNS->getParent()->makeDeclVisibleInContext(ND);
  6246. return;
  6247. }
  6248. if (PrevNS->isInline())
  6249. // The user probably just forgot the 'inline', so suggest that it
  6250. // be added back.
  6251. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
  6252. << FixItHint::CreateInsertion(KeywordLoc, "inline ");
  6253. else
  6254. S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
  6255. S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
  6256. *IsInline = PrevNS->isInline();
  6257. }
  6258. /// ActOnStartNamespaceDef - This is called at the start of a namespace
  6259. /// definition.
  6260. Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
  6261. SourceLocation InlineLoc,
  6262. SourceLocation NamespaceLoc,
  6263. SourceLocation IdentLoc,
  6264. IdentifierInfo *II,
  6265. SourceLocation LBrace,
  6266. AttributeList *AttrList) {
  6267. SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
  6268. // For anonymous namespace, take the location of the left brace.
  6269. SourceLocation Loc = II ? IdentLoc : LBrace;
  6270. bool IsInline = InlineLoc.isValid();
  6271. bool IsInvalid = false;
  6272. bool IsStd = false;
  6273. bool AddToKnown = false;
  6274. Scope *DeclRegionScope = NamespcScope->getParent();
  6275. NamespaceDecl *PrevNS = nullptr;
  6276. if (II) {
  6277. // C++ [namespace.def]p2:
  6278. // The identifier in an original-namespace-definition shall not
  6279. // have been previously defined in the declarative region in
  6280. // which the original-namespace-definition appears. The
  6281. // identifier in an original-namespace-definition is the name of
  6282. // the namespace. Subsequently in that declarative region, it is
  6283. // treated as an original-namespace-name.
  6284. //
  6285. // Since namespace names are unique in their scope, and we don't
  6286. // look through using directives, just look for any ordinary names.
  6287. const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
  6288. Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
  6289. Decl::IDNS_Namespace;
  6290. NamedDecl *PrevDecl = nullptr;
  6291. DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
  6292. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
  6293. ++I) {
  6294. if ((*I)->getIdentifierNamespace() & IDNS) {
  6295. PrevDecl = *I;
  6296. break;
  6297. }
  6298. }
  6299. PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
  6300. if (PrevNS) {
  6301. // This is an extended namespace definition.
  6302. if (IsInline != PrevNS->isInline())
  6303. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
  6304. &IsInline, PrevNS);
  6305. } else if (PrevDecl) {
  6306. // This is an invalid name redefinition.
  6307. Diag(Loc, diag::err_redefinition_different_kind)
  6308. << II;
  6309. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  6310. IsInvalid = true;
  6311. // Continue on to push Namespc as current DeclContext and return it.
  6312. } else if (II->isStr("std") &&
  6313. CurContext->getRedeclContext()->isTranslationUnit()) {
  6314. // This is the first "real" definition of the namespace "std", so update
  6315. // our cache of the "std" namespace to point at this definition.
  6316. PrevNS = getStdNamespace();
  6317. IsStd = true;
  6318. AddToKnown = !IsInline;
  6319. } else {
  6320. // We've seen this namespace for the first time.
  6321. AddToKnown = !IsInline;
  6322. }
  6323. } else {
  6324. // Anonymous namespaces.
  6325. // Determine whether the parent already has an anonymous namespace.
  6326. DeclContext *Parent = CurContext->getRedeclContext();
  6327. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  6328. PrevNS = TU->getAnonymousNamespace();
  6329. } else {
  6330. NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
  6331. PrevNS = ND->getAnonymousNamespace();
  6332. }
  6333. if (PrevNS && IsInline != PrevNS->isInline())
  6334. DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
  6335. &IsInline, PrevNS);
  6336. }
  6337. NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
  6338. StartLoc, Loc, II, PrevNS);
  6339. if (IsInvalid)
  6340. Namespc->setInvalidDecl();
  6341. ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
  6342. // FIXME: Should we be merging attributes?
  6343. if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
  6344. PushNamespaceVisibilityAttr(Attr, Loc);
  6345. if (IsStd)
  6346. StdNamespace = Namespc;
  6347. if (AddToKnown)
  6348. KnownNamespaces[Namespc] = false;
  6349. if (II) {
  6350. PushOnScopeChains(Namespc, DeclRegionScope);
  6351. } else {
  6352. // Link the anonymous namespace into its parent.
  6353. DeclContext *Parent = CurContext->getRedeclContext();
  6354. if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
  6355. TU->setAnonymousNamespace(Namespc);
  6356. } else {
  6357. cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
  6358. }
  6359. CurContext->addDecl(Namespc);
  6360. // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
  6361. // behaves as if it were replaced by
  6362. // namespace unique { /* empty body */ }
  6363. // using namespace unique;
  6364. // namespace unique { namespace-body }
  6365. // where all occurrences of 'unique' in a translation unit are
  6366. // replaced by the same identifier and this identifier differs
  6367. // from all other identifiers in the entire program.
  6368. // We just create the namespace with an empty name and then add an
  6369. // implicit using declaration, just like the standard suggests.
  6370. //
  6371. // CodeGen enforces the "universally unique" aspect by giving all
  6372. // declarations semantically contained within an anonymous
  6373. // namespace internal linkage.
  6374. if (!PrevNS) {
  6375. UsingDirectiveDecl* UD
  6376. = UsingDirectiveDecl::Create(Context, Parent,
  6377. /* 'using' */ LBrace,
  6378. /* 'namespace' */ SourceLocation(),
  6379. /* qualifier */ NestedNameSpecifierLoc(),
  6380. /* identifier */ SourceLocation(),
  6381. Namespc,
  6382. /* Ancestor */ Parent);
  6383. UD->setImplicit();
  6384. Parent->addDecl(UD);
  6385. }
  6386. }
  6387. ActOnDocumentableDecl(Namespc);
  6388. // Although we could have an invalid decl (i.e. the namespace name is a
  6389. // redefinition), push it as current DeclContext and try to continue parsing.
  6390. // FIXME: We should be able to push Namespc here, so that the each DeclContext
  6391. // for the namespace has the declarations that showed up in that particular
  6392. // namespace definition.
  6393. PushDeclContext(NamespcScope, Namespc);
  6394. return Namespc;
  6395. }
  6396. /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
  6397. /// is a namespace alias, returns the namespace it points to.
  6398. static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
  6399. if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
  6400. return AD->getNamespace();
  6401. return dyn_cast_or_null<NamespaceDecl>(D);
  6402. }
  6403. /// ActOnFinishNamespaceDef - This callback is called after a namespace is
  6404. /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
  6405. void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
  6406. NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
  6407. assert(Namespc && "Invalid parameter, expected NamespaceDecl");
  6408. Namespc->setRBraceLoc(RBrace);
  6409. PopDeclContext();
  6410. if (Namespc->hasAttr<VisibilityAttr>())
  6411. PopPragmaVisibility(true, RBrace);
  6412. }
  6413. CXXRecordDecl *Sema::getStdBadAlloc() const {
  6414. return cast_or_null<CXXRecordDecl>(
  6415. StdBadAlloc.get(Context.getExternalSource()));
  6416. }
  6417. NamespaceDecl *Sema::getStdNamespace() const {
  6418. return cast_or_null<NamespaceDecl>(
  6419. StdNamespace.get(Context.getExternalSource()));
  6420. }
  6421. /// \brief Retrieve the special "std" namespace, which may require us to
  6422. /// implicitly define the namespace.
  6423. NamespaceDecl *Sema::getOrCreateStdNamespace() {
  6424. if (!StdNamespace) {
  6425. // The "std" namespace has not yet been defined, so build one implicitly.
  6426. StdNamespace = NamespaceDecl::Create(Context,
  6427. Context.getTranslationUnitDecl(),
  6428. /*Inline=*/false,
  6429. SourceLocation(), SourceLocation(),
  6430. &PP.getIdentifierTable().get("std"),
  6431. /*PrevDecl=*/nullptr);
  6432. getStdNamespace()->setImplicit(true);
  6433. }
  6434. return getStdNamespace();
  6435. }
  6436. bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
  6437. assert(getLangOpts().CPlusPlus &&
  6438. "Looking for std::initializer_list outside of C++.");
  6439. // We're looking for implicit instantiations of
  6440. // template <typename E> class std::initializer_list.
  6441. if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
  6442. return false;
  6443. ClassTemplateDecl *Template = nullptr;
  6444. const TemplateArgument *Arguments = nullptr;
  6445. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  6446. ClassTemplateSpecializationDecl *Specialization =
  6447. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  6448. if (!Specialization)
  6449. return false;
  6450. Template = Specialization->getSpecializedTemplate();
  6451. Arguments = Specialization->getTemplateArgs().data();
  6452. } else if (const TemplateSpecializationType *TST =
  6453. Ty->getAs<TemplateSpecializationType>()) {
  6454. Template = dyn_cast_or_null<ClassTemplateDecl>(
  6455. TST->getTemplateName().getAsTemplateDecl());
  6456. Arguments = TST->getArgs();
  6457. }
  6458. if (!Template)
  6459. return false;
  6460. if (!StdInitializerList) {
  6461. // Haven't recognized std::initializer_list yet, maybe this is it.
  6462. CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
  6463. if (TemplateClass->getIdentifier() !=
  6464. &PP.getIdentifierTable().get("initializer_list") ||
  6465. !getStdNamespace()->InEnclosingNamespaceSetOf(
  6466. TemplateClass->getDeclContext()))
  6467. return false;
  6468. // This is a template called std::initializer_list, but is it the right
  6469. // template?
  6470. TemplateParameterList *Params = Template->getTemplateParameters();
  6471. if (Params->getMinRequiredArguments() != 1)
  6472. return false;
  6473. if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
  6474. return false;
  6475. // It's the right template.
  6476. StdInitializerList = Template;
  6477. }
  6478. if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
  6479. return false;
  6480. // This is an instance of std::initializer_list. Find the argument type.
  6481. if (Element)
  6482. *Element = Arguments[0].getAsType();
  6483. return true;
  6484. }
  6485. static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
  6486. NamespaceDecl *Std = S.getStdNamespace();
  6487. if (!Std) {
  6488. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  6489. return nullptr;
  6490. }
  6491. LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
  6492. Loc, Sema::LookupOrdinaryName);
  6493. if (!S.LookupQualifiedName(Result, Std)) {
  6494. S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
  6495. return nullptr;
  6496. }
  6497. ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
  6498. if (!Template) {
  6499. Result.suppressDiagnostics();
  6500. // We found something weird. Complain about the first thing we found.
  6501. NamedDecl *Found = *Result.begin();
  6502. S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
  6503. return nullptr;
  6504. }
  6505. // We found some template called std::initializer_list. Now verify that it's
  6506. // correct.
  6507. TemplateParameterList *Params = Template->getTemplateParameters();
  6508. if (Params->getMinRequiredArguments() != 1 ||
  6509. !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
  6510. S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
  6511. return nullptr;
  6512. }
  6513. return Template;
  6514. }
  6515. QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
  6516. if (!StdInitializerList) {
  6517. StdInitializerList = LookupStdInitializerList(*this, Loc);
  6518. if (!StdInitializerList)
  6519. return QualType();
  6520. }
  6521. TemplateArgumentListInfo Args(Loc, Loc);
  6522. Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
  6523. Context.getTrivialTypeSourceInfo(Element,
  6524. Loc)));
  6525. return Context.getCanonicalType(
  6526. CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
  6527. }
  6528. bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
  6529. // C++ [dcl.init.list]p2:
  6530. // A constructor is an initializer-list constructor if its first parameter
  6531. // is of type std::initializer_list<E> or reference to possibly cv-qualified
  6532. // std::initializer_list<E> for some type E, and either there are no other
  6533. // parameters or else all other parameters have default arguments.
  6534. if (Ctor->getNumParams() < 1 ||
  6535. (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
  6536. return false;
  6537. QualType ArgType = Ctor->getParamDecl(0)->getType();
  6538. if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
  6539. ArgType = RT->getPointeeType().getUnqualifiedType();
  6540. return isStdInitializerList(ArgType, nullptr);
  6541. }
  6542. /// \brief Determine whether a using statement is in a context where it will be
  6543. /// apply in all contexts.
  6544. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
  6545. switch (CurContext->getDeclKind()) {
  6546. case Decl::TranslationUnit:
  6547. return true;
  6548. case Decl::LinkageSpec:
  6549. return IsUsingDirectiveInToplevelContext(CurContext->getParent());
  6550. default:
  6551. return false;
  6552. }
  6553. }
  6554. namespace {
  6555. // Callback to only accept typo corrections that are namespaces.
  6556. class NamespaceValidatorCCC : public CorrectionCandidateCallback {
  6557. public:
  6558. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6559. if (NamedDecl *ND = candidate.getCorrectionDecl())
  6560. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  6561. return false;
  6562. }
  6563. };
  6564. }
  6565. static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
  6566. CXXScopeSpec &SS,
  6567. SourceLocation IdentLoc,
  6568. IdentifierInfo *Ident) {
  6569. R.clear();
  6570. if (TypoCorrection Corrected =
  6571. S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
  6572. llvm::make_unique<NamespaceValidatorCCC>(),
  6573. Sema::CTK_ErrorRecovery)) {
  6574. if (DeclContext *DC = S.computeDeclContext(SS, false)) {
  6575. std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
  6576. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  6577. Ident->getName().equals(CorrectedStr);
  6578. S.diagnoseTypo(Corrected,
  6579. S.PDiag(diag::err_using_directive_member_suggest)
  6580. << Ident << DC << DroppedSpecifier << SS.getRange(),
  6581. S.PDiag(diag::note_namespace_defined_here));
  6582. } else {
  6583. S.diagnoseTypo(Corrected,
  6584. S.PDiag(diag::err_using_directive_suggest) << Ident,
  6585. S.PDiag(diag::note_namespace_defined_here));
  6586. }
  6587. R.addDecl(Corrected.getCorrectionDecl());
  6588. return true;
  6589. }
  6590. return false;
  6591. }
  6592. Decl *Sema::ActOnUsingDirective(Scope *S,
  6593. SourceLocation UsingLoc,
  6594. SourceLocation NamespcLoc,
  6595. CXXScopeSpec &SS,
  6596. SourceLocation IdentLoc,
  6597. IdentifierInfo *NamespcName,
  6598. AttributeList *AttrList) {
  6599. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  6600. assert(NamespcName && "Invalid NamespcName.");
  6601. assert(IdentLoc.isValid() && "Invalid NamespceName location.");
  6602. // This can only happen along a recovery path.
  6603. while (S->getFlags() & Scope::TemplateParamScope)
  6604. S = S->getParent();
  6605. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  6606. UsingDirectiveDecl *UDir = nullptr;
  6607. NestedNameSpecifier *Qualifier = nullptr;
  6608. if (SS.isSet())
  6609. Qualifier = SS.getScopeRep();
  6610. // Lookup namespace name.
  6611. LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
  6612. LookupParsedName(R, S, &SS);
  6613. if (R.isAmbiguous())
  6614. return nullptr;
  6615. if (R.empty()) {
  6616. R.clear();
  6617. // Allow "using namespace std;" or "using namespace ::std;" even if
  6618. // "std" hasn't been defined yet, for GCC compatibility.
  6619. if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
  6620. NamespcName->isStr("std")) {
  6621. Diag(IdentLoc, diag::ext_using_undefined_std);
  6622. R.addDecl(getOrCreateStdNamespace());
  6623. R.resolveKind();
  6624. }
  6625. // Otherwise, attempt typo correction.
  6626. else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
  6627. }
  6628. if (!R.empty()) {
  6629. NamedDecl *Named = R.getFoundDecl();
  6630. assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
  6631. && "expected namespace decl");
  6632. // The use of a nested name specifier may trigger deprecation warnings.
  6633. DiagnoseUseOfDecl(Named, IdentLoc);
  6634. // C++ [namespace.udir]p1:
  6635. // A using-directive specifies that the names in the nominated
  6636. // namespace can be used in the scope in which the
  6637. // using-directive appears after the using-directive. During
  6638. // unqualified name lookup (3.4.1), the names appear as if they
  6639. // were declared in the nearest enclosing namespace which
  6640. // contains both the using-directive and the nominated
  6641. // namespace. [Note: in this context, "contains" means "contains
  6642. // directly or indirectly". ]
  6643. // Find enclosing context containing both using-directive and
  6644. // nominated namespace.
  6645. NamespaceDecl *NS = getNamespaceDecl(Named);
  6646. DeclContext *CommonAncestor = cast<DeclContext>(NS);
  6647. while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
  6648. CommonAncestor = CommonAncestor->getParent();
  6649. UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
  6650. SS.getWithLocInContext(Context),
  6651. IdentLoc, Named, CommonAncestor);
  6652. if (IsUsingDirectiveInToplevelContext(CurContext) &&
  6653. !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
  6654. Diag(IdentLoc, diag::warn_using_directive_in_header);
  6655. }
  6656. PushUsingDirective(S, UDir);
  6657. } else {
  6658. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  6659. }
  6660. if (UDir)
  6661. ProcessDeclAttributeList(S, UDir, AttrList);
  6662. return UDir;
  6663. }
  6664. void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
  6665. // If the scope has an associated entity and the using directive is at
  6666. // namespace or translation unit scope, add the UsingDirectiveDecl into
  6667. // its lookup structure so qualified name lookup can find it.
  6668. DeclContext *Ctx = S->getEntity();
  6669. if (Ctx && !Ctx->isFunctionOrMethod())
  6670. Ctx->addDecl(UDir);
  6671. else
  6672. // Otherwise, it is at block scope. The using-directives will affect lookup
  6673. // only to the end of the scope.
  6674. S->PushUsingDirective(UDir);
  6675. }
  6676. Decl *Sema::ActOnUsingDeclaration(Scope *S,
  6677. AccessSpecifier AS,
  6678. bool HasUsingKeyword,
  6679. SourceLocation UsingLoc,
  6680. CXXScopeSpec &SS,
  6681. UnqualifiedId &Name,
  6682. AttributeList *AttrList,
  6683. bool HasTypenameKeyword,
  6684. SourceLocation TypenameLoc) {
  6685. assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
  6686. switch (Name.getKind()) {
  6687. case UnqualifiedId::IK_ImplicitSelfParam:
  6688. case UnqualifiedId::IK_Identifier:
  6689. case UnqualifiedId::IK_OperatorFunctionId:
  6690. case UnqualifiedId::IK_LiteralOperatorId:
  6691. case UnqualifiedId::IK_ConversionFunctionId:
  6692. break;
  6693. case UnqualifiedId::IK_ConstructorName:
  6694. case UnqualifiedId::IK_ConstructorTemplateId:
  6695. // C++11 inheriting constructors.
  6696. Diag(Name.getLocStart(),
  6697. getLangOpts().CPlusPlus11 ?
  6698. diag::warn_cxx98_compat_using_decl_constructor :
  6699. diag::err_using_decl_constructor)
  6700. << SS.getRange();
  6701. if (getLangOpts().CPlusPlus11) break;
  6702. return nullptr;
  6703. case UnqualifiedId::IK_DestructorName:
  6704. Diag(Name.getLocStart(), diag::err_using_decl_destructor)
  6705. << SS.getRange();
  6706. return nullptr;
  6707. case UnqualifiedId::IK_TemplateId:
  6708. Diag(Name.getLocStart(), diag::err_using_decl_template_id)
  6709. << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
  6710. return nullptr;
  6711. }
  6712. DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
  6713. DeclarationName TargetName = TargetNameInfo.getName();
  6714. if (!TargetName)
  6715. return nullptr;
  6716. // Warn about access declarations.
  6717. if (!HasUsingKeyword) {
  6718. Diag(Name.getLocStart(),
  6719. getLangOpts().CPlusPlus11 ? diag::err_access_decl
  6720. : diag::warn_access_decl_deprecated)
  6721. << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
  6722. }
  6723. if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
  6724. DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
  6725. return nullptr;
  6726. NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
  6727. TargetNameInfo, AttrList,
  6728. /* IsInstantiation */ false,
  6729. HasTypenameKeyword, TypenameLoc);
  6730. if (UD)
  6731. PushOnScopeChains(UD, S, /*AddToContext*/ false);
  6732. return UD;
  6733. }
  6734. /// \brief Determine whether a using declaration considers the given
  6735. /// declarations as "equivalent", e.g., if they are redeclarations of
  6736. /// the same entity or are both typedefs of the same type.
  6737. static bool
  6738. IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
  6739. if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
  6740. return true;
  6741. if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
  6742. if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
  6743. return Context.hasSameType(TD1->getUnderlyingType(),
  6744. TD2->getUnderlyingType());
  6745. return false;
  6746. }
  6747. /// Determines whether to create a using shadow decl for a particular
  6748. /// decl, given the set of decls existing prior to this using lookup.
  6749. bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
  6750. const LookupResult &Previous,
  6751. UsingShadowDecl *&PrevShadow) {
  6752. // Diagnose finding a decl which is not from a base class of the
  6753. // current class. We do this now because there are cases where this
  6754. // function will silently decide not to build a shadow decl, which
  6755. // will pre-empt further diagnostics.
  6756. //
  6757. // We don't need to do this in C++0x because we do the check once on
  6758. // the qualifier.
  6759. //
  6760. // FIXME: diagnose the following if we care enough:
  6761. // struct A { int foo; };
  6762. // struct B : A { using A::foo; };
  6763. // template <class T> struct C : A {};
  6764. // template <class T> struct D : C<T> { using B::foo; } // <---
  6765. // This is invalid (during instantiation) in C++03 because B::foo
  6766. // resolves to the using decl in B, which is not a base class of D<T>.
  6767. // We can't diagnose it immediately because C<T> is an unknown
  6768. // specialization. The UsingShadowDecl in D<T> then points directly
  6769. // to A::foo, which will look well-formed when we instantiate.
  6770. // The right solution is to not collapse the shadow-decl chain.
  6771. if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
  6772. DeclContext *OrigDC = Orig->getDeclContext();
  6773. // Handle enums and anonymous structs.
  6774. if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
  6775. CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
  6776. while (OrigRec->isAnonymousStructOrUnion())
  6777. OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
  6778. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
  6779. if (OrigDC == CurContext) {
  6780. Diag(Using->getLocation(),
  6781. diag::err_using_decl_nested_name_specifier_is_current_class)
  6782. << Using->getQualifierLoc().getSourceRange();
  6783. Diag(Orig->getLocation(), diag::note_using_decl_target);
  6784. return true;
  6785. }
  6786. Diag(Using->getQualifierLoc().getBeginLoc(),
  6787. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  6788. << Using->getQualifier()
  6789. << cast<CXXRecordDecl>(CurContext)
  6790. << Using->getQualifierLoc().getSourceRange();
  6791. Diag(Orig->getLocation(), diag::note_using_decl_target);
  6792. return true;
  6793. }
  6794. }
  6795. if (Previous.empty()) return false;
  6796. NamedDecl *Target = Orig;
  6797. if (isa<UsingShadowDecl>(Target))
  6798. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  6799. // If the target happens to be one of the previous declarations, we
  6800. // don't have a conflict.
  6801. //
  6802. // FIXME: but we might be increasing its access, in which case we
  6803. // should redeclare it.
  6804. NamedDecl *NonTag = nullptr, *Tag = nullptr;
  6805. bool FoundEquivalentDecl = false;
  6806. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6807. I != E; ++I) {
  6808. NamedDecl *D = (*I)->getUnderlyingDecl();
  6809. if (IsEquivalentForUsingDecl(Context, D, Target)) {
  6810. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
  6811. PrevShadow = Shadow;
  6812. FoundEquivalentDecl = true;
  6813. }
  6814. (isa<TagDecl>(D) ? Tag : NonTag) = D;
  6815. }
  6816. if (FoundEquivalentDecl)
  6817. return false;
  6818. if (FunctionDecl *FD = Target->getAsFunction()) {
  6819. NamedDecl *OldDecl = nullptr;
  6820. switch (CheckOverload(nullptr, FD, Previous, OldDecl,
  6821. /*IsForUsingDecl*/ true)) {
  6822. case Ovl_Overload:
  6823. return false;
  6824. case Ovl_NonFunction:
  6825. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6826. break;
  6827. // We found a decl with the exact signature.
  6828. case Ovl_Match:
  6829. // If we're in a record, we want to hide the target, so we
  6830. // return true (without a diagnostic) to tell the caller not to
  6831. // build a shadow decl.
  6832. if (CurContext->isRecord())
  6833. return true;
  6834. // If we're not in a record, this is an error.
  6835. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6836. break;
  6837. }
  6838. Diag(Target->getLocation(), diag::note_using_decl_target);
  6839. Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
  6840. return true;
  6841. }
  6842. // Target is not a function.
  6843. if (isa<TagDecl>(Target)) {
  6844. // No conflict between a tag and a non-tag.
  6845. if (!Tag) return false;
  6846. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6847. Diag(Target->getLocation(), diag::note_using_decl_target);
  6848. Diag(Tag->getLocation(), diag::note_using_decl_conflict);
  6849. return true;
  6850. }
  6851. // No conflict between a tag and a non-tag.
  6852. if (!NonTag) return false;
  6853. Diag(Using->getLocation(), diag::err_using_decl_conflict);
  6854. Diag(Target->getLocation(), diag::note_using_decl_target);
  6855. Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
  6856. return true;
  6857. }
  6858. /// Builds a shadow declaration corresponding to a 'using' declaration.
  6859. UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
  6860. UsingDecl *UD,
  6861. NamedDecl *Orig,
  6862. UsingShadowDecl *PrevDecl) {
  6863. // If we resolved to another shadow declaration, just coalesce them.
  6864. NamedDecl *Target = Orig;
  6865. if (isa<UsingShadowDecl>(Target)) {
  6866. Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
  6867. assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
  6868. }
  6869. UsingShadowDecl *Shadow
  6870. = UsingShadowDecl::Create(Context, CurContext,
  6871. UD->getLocation(), UD, Target);
  6872. UD->addShadowDecl(Shadow);
  6873. Shadow->setAccess(UD->getAccess());
  6874. if (Orig->isInvalidDecl() || UD->isInvalidDecl())
  6875. Shadow->setInvalidDecl();
  6876. Shadow->setPreviousDecl(PrevDecl);
  6877. if (S)
  6878. PushOnScopeChains(Shadow, S);
  6879. else
  6880. CurContext->addDecl(Shadow);
  6881. return Shadow;
  6882. }
  6883. /// Hides a using shadow declaration. This is required by the current
  6884. /// using-decl implementation when a resolvable using declaration in a
  6885. /// class is followed by a declaration which would hide or override
  6886. /// one or more of the using decl's targets; for example:
  6887. ///
  6888. /// struct Base { void foo(int); };
  6889. /// struct Derived : Base {
  6890. /// using Base::foo;
  6891. /// void foo(int);
  6892. /// };
  6893. ///
  6894. /// The governing language is C++03 [namespace.udecl]p12:
  6895. ///
  6896. /// When a using-declaration brings names from a base class into a
  6897. /// derived class scope, member functions in the derived class
  6898. /// override and/or hide member functions with the same name and
  6899. /// parameter types in a base class (rather than conflicting).
  6900. ///
  6901. /// There are two ways to implement this:
  6902. /// (1) optimistically create shadow decls when they're not hidden
  6903. /// by existing declarations, or
  6904. /// (2) don't create any shadow decls (or at least don't make them
  6905. /// visible) until we've fully parsed/instantiated the class.
  6906. /// The problem with (1) is that we might have to retroactively remove
  6907. /// a shadow decl, which requires several O(n) operations because the
  6908. /// decl structures are (very reasonably) not designed for removal.
  6909. /// (2) avoids this but is very fiddly and phase-dependent.
  6910. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
  6911. if (Shadow->getDeclName().getNameKind() ==
  6912. DeclarationName::CXXConversionFunctionName)
  6913. cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
  6914. // Remove it from the DeclContext...
  6915. Shadow->getDeclContext()->removeDecl(Shadow);
  6916. // ...and the scope, if applicable...
  6917. if (S) {
  6918. S->RemoveDecl(Shadow);
  6919. IdResolver.RemoveDecl(Shadow);
  6920. }
  6921. // ...and the using decl.
  6922. Shadow->getUsingDecl()->removeShadowDecl(Shadow);
  6923. // TODO: complain somehow if Shadow was used. It shouldn't
  6924. // be possible for this to happen, because...?
  6925. }
  6926. /// Find the base specifier for a base class with the given type.
  6927. static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
  6928. QualType DesiredBase,
  6929. bool &AnyDependentBases) {
  6930. // Check whether the named type is a direct base class.
  6931. CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
  6932. for (auto &Base : Derived->bases()) {
  6933. CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
  6934. if (CanonicalDesiredBase == BaseType)
  6935. return &Base;
  6936. if (BaseType->isDependentType())
  6937. AnyDependentBases = true;
  6938. }
  6939. return nullptr;
  6940. }
  6941. namespace {
  6942. class UsingValidatorCCC : public CorrectionCandidateCallback {
  6943. public:
  6944. UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
  6945. NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
  6946. : HasTypenameKeyword(HasTypenameKeyword),
  6947. IsInstantiation(IsInstantiation), OldNNS(NNS),
  6948. RequireMemberOf(RequireMemberOf) {}
  6949. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  6950. NamedDecl *ND = Candidate.getCorrectionDecl();
  6951. // Keywords are not valid here.
  6952. if (!ND || isa<NamespaceDecl>(ND))
  6953. return false;
  6954. // Completely unqualified names are invalid for a 'using' declaration.
  6955. if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
  6956. return false;
  6957. if (RequireMemberOf) {
  6958. auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
  6959. if (FoundRecord && FoundRecord->isInjectedClassName()) {
  6960. // No-one ever wants a using-declaration to name an injected-class-name
  6961. // of a base class, unless they're declaring an inheriting constructor.
  6962. ASTContext &Ctx = ND->getASTContext();
  6963. if (!Ctx.getLangOpts().CPlusPlus11)
  6964. return false;
  6965. QualType FoundType = Ctx.getRecordType(FoundRecord);
  6966. // Check that the injected-class-name is named as a member of its own
  6967. // type; we don't want to suggest 'using Derived::Base;', since that
  6968. // means something else.
  6969. NestedNameSpecifier *Specifier =
  6970. Candidate.WillReplaceSpecifier()
  6971. ? Candidate.getCorrectionSpecifier()
  6972. : OldNNS;
  6973. if (!Specifier->getAsType() ||
  6974. !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
  6975. return false;
  6976. // Check that this inheriting constructor declaration actually names a
  6977. // direct base class of the current class.
  6978. bool AnyDependentBases = false;
  6979. if (!findDirectBaseWithType(RequireMemberOf,
  6980. Ctx.getRecordType(FoundRecord),
  6981. AnyDependentBases) &&
  6982. !AnyDependentBases)
  6983. return false;
  6984. } else {
  6985. auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
  6986. if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
  6987. return false;
  6988. // FIXME: Check that the base class member is accessible?
  6989. }
  6990. }
  6991. if (isa<TypeDecl>(ND))
  6992. return HasTypenameKeyword || !IsInstantiation;
  6993. return !HasTypenameKeyword;
  6994. }
  6995. private:
  6996. bool HasTypenameKeyword;
  6997. bool IsInstantiation;
  6998. NestedNameSpecifier *OldNNS;
  6999. CXXRecordDecl *RequireMemberOf;
  7000. };
  7001. } // end anonymous namespace
  7002. /// Builds a using declaration.
  7003. ///
  7004. /// \param IsInstantiation - Whether this call arises from an
  7005. /// instantiation of an unresolved using declaration. We treat
  7006. /// the lookup differently for these declarations.
  7007. NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
  7008. SourceLocation UsingLoc,
  7009. CXXScopeSpec &SS,
  7010. DeclarationNameInfo NameInfo,
  7011. AttributeList *AttrList,
  7012. bool IsInstantiation,
  7013. bool HasTypenameKeyword,
  7014. SourceLocation TypenameLoc) {
  7015. assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
  7016. SourceLocation IdentLoc = NameInfo.getLoc();
  7017. assert(IdentLoc.isValid() && "Invalid TargetName location.");
  7018. // FIXME: We ignore attributes for now.
  7019. if (SS.isEmpty()) {
  7020. Diag(IdentLoc, diag::err_using_requires_qualname);
  7021. return nullptr;
  7022. }
  7023. // Do the redeclaration lookup in the current scope.
  7024. LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
  7025. ForRedeclaration);
  7026. Previous.setHideTags(false);
  7027. if (S) {
  7028. LookupName(Previous, S);
  7029. // It is really dumb that we have to do this.
  7030. LookupResult::Filter F = Previous.makeFilter();
  7031. while (F.hasNext()) {
  7032. NamedDecl *D = F.next();
  7033. if (!isDeclInScope(D, CurContext, S))
  7034. F.erase();
  7035. // If we found a local extern declaration that's not ordinarily visible,
  7036. // and this declaration is being added to a non-block scope, ignore it.
  7037. // We're only checking for scope conflicts here, not also for violations
  7038. // of the linkage rules.
  7039. else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
  7040. !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
  7041. F.erase();
  7042. }
  7043. F.done();
  7044. } else {
  7045. assert(IsInstantiation && "no scope in non-instantiation");
  7046. assert(CurContext->isRecord() && "scope not record in instantiation");
  7047. LookupQualifiedName(Previous, CurContext);
  7048. }
  7049. // Check for invalid redeclarations.
  7050. if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
  7051. SS, IdentLoc, Previous))
  7052. return nullptr;
  7053. // Check for bad qualifiers.
  7054. if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
  7055. return nullptr;
  7056. DeclContext *LookupContext = computeDeclContext(SS);
  7057. NamedDecl *D;
  7058. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  7059. if (!LookupContext) {
  7060. if (HasTypenameKeyword) {
  7061. // FIXME: not all declaration name kinds are legal here
  7062. D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
  7063. UsingLoc, TypenameLoc,
  7064. QualifierLoc,
  7065. IdentLoc, NameInfo.getName());
  7066. } else {
  7067. D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
  7068. QualifierLoc, NameInfo);
  7069. }
  7070. D->setAccess(AS);
  7071. CurContext->addDecl(D);
  7072. return D;
  7073. }
  7074. auto Build = [&](bool Invalid) {
  7075. UsingDecl *UD =
  7076. UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
  7077. HasTypenameKeyword);
  7078. UD->setAccess(AS);
  7079. CurContext->addDecl(UD);
  7080. UD->setInvalidDecl(Invalid);
  7081. return UD;
  7082. };
  7083. auto BuildInvalid = [&]{ return Build(true); };
  7084. auto BuildValid = [&]{ return Build(false); };
  7085. if (RequireCompleteDeclContext(SS, LookupContext))
  7086. return BuildInvalid();
  7087. // Look up the target name.
  7088. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  7089. // Unlike most lookups, we don't always want to hide tag
  7090. // declarations: tag names are visible through the using declaration
  7091. // even if hidden by ordinary names, *except* in a dependent context
  7092. // where it's important for the sanity of two-phase lookup.
  7093. if (!IsInstantiation)
  7094. R.setHideTags(false);
  7095. // For the purposes of this lookup, we have a base object type
  7096. // equal to that of the current context.
  7097. if (CurContext->isRecord()) {
  7098. R.setBaseObjectType(
  7099. Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
  7100. }
  7101. LookupQualifiedName(R, LookupContext);
  7102. // Try to correct typos if possible. If constructor name lookup finds no
  7103. // results, that means the named class has no explicit constructors, and we
  7104. // suppressed declaring implicit ones (probably because it's dependent or
  7105. // invalid).
  7106. if (R.empty() &&
  7107. NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
  7108. if (TypoCorrection Corrected = CorrectTypo(
  7109. R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
  7110. llvm::make_unique<UsingValidatorCCC>(
  7111. HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
  7112. dyn_cast<CXXRecordDecl>(CurContext)),
  7113. CTK_ErrorRecovery)) {
  7114. // We reject any correction for which ND would be NULL.
  7115. NamedDecl *ND = Corrected.getCorrectionDecl();
  7116. // We reject candidates where DroppedSpecifier == true, hence the
  7117. // literal '0' below.
  7118. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  7119. << NameInfo.getName() << LookupContext << 0
  7120. << SS.getRange());
  7121. // If we corrected to an inheriting constructor, handle it as one.
  7122. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  7123. if (RD && RD->isInjectedClassName()) {
  7124. // Fix up the information we'll use to build the using declaration.
  7125. if (Corrected.WillReplaceSpecifier()) {
  7126. NestedNameSpecifierLocBuilder Builder;
  7127. Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  7128. QualifierLoc.getSourceRange());
  7129. QualifierLoc = Builder.getWithLocInContext(Context);
  7130. }
  7131. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  7132. Context.getCanonicalType(Context.getRecordType(RD))));
  7133. NameInfo.setNamedTypeInfo(nullptr);
  7134. for (auto *Ctor : LookupConstructors(RD))
  7135. R.addDecl(Ctor);
  7136. } else {
  7137. // FIXME: Pick up all the declarations if we found an overloaded function.
  7138. R.addDecl(ND);
  7139. }
  7140. } else {
  7141. Diag(IdentLoc, diag::err_no_member)
  7142. << NameInfo.getName() << LookupContext << SS.getRange();
  7143. return BuildInvalid();
  7144. }
  7145. }
  7146. if (R.isAmbiguous())
  7147. return BuildInvalid();
  7148. if (HasTypenameKeyword) {
  7149. // If we asked for a typename and got a non-type decl, error out.
  7150. if (!R.getAsSingle<TypeDecl>()) {
  7151. Diag(IdentLoc, diag::err_using_typename_non_type);
  7152. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  7153. Diag((*I)->getUnderlyingDecl()->getLocation(),
  7154. diag::note_using_decl_target);
  7155. return BuildInvalid();
  7156. }
  7157. } else {
  7158. // If we asked for a non-typename and we got a type, error out,
  7159. // but only if this is an instantiation of an unresolved using
  7160. // decl. Otherwise just silently find the type name.
  7161. if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
  7162. Diag(IdentLoc, diag::err_using_dependent_value_is_type);
  7163. Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
  7164. return BuildInvalid();
  7165. }
  7166. }
  7167. // C++0x N2914 [namespace.udecl]p6:
  7168. // A using-declaration shall not name a namespace.
  7169. if (R.getAsSingle<NamespaceDecl>()) {
  7170. Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
  7171. << SS.getRange();
  7172. return BuildInvalid();
  7173. }
  7174. UsingDecl *UD = BuildValid();
  7175. // The normal rules do not apply to inheriting constructor declarations.
  7176. if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
  7177. // Suppress access diagnostics; the access check is instead performed at the
  7178. // point of use for an inheriting constructor.
  7179. R.suppressDiagnostics();
  7180. CheckInheritingConstructorUsingDecl(UD);
  7181. return UD;
  7182. }
  7183. // Otherwise, look up the target name.
  7184. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  7185. UsingShadowDecl *PrevDecl = nullptr;
  7186. if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
  7187. BuildUsingShadowDecl(S, UD, *I, PrevDecl);
  7188. }
  7189. return UD;
  7190. }
  7191. /// Additional checks for a using declaration referring to a constructor name.
  7192. bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
  7193. assert(!UD->hasTypename() && "expecting a constructor name");
  7194. const Type *SourceType = UD->getQualifier()->getAsType();
  7195. assert(SourceType &&
  7196. "Using decl naming constructor doesn't have type in scope spec.");
  7197. CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
  7198. // Check whether the named type is a direct base class.
  7199. bool AnyDependentBases = false;
  7200. auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
  7201. AnyDependentBases);
  7202. if (!Base && !AnyDependentBases) {
  7203. Diag(UD->getUsingLoc(),
  7204. diag::err_using_decl_constructor_not_in_direct_base)
  7205. << UD->getNameInfo().getSourceRange()
  7206. << QualType(SourceType, 0) << TargetClass;
  7207. UD->setInvalidDecl();
  7208. return true;
  7209. }
  7210. if (Base)
  7211. Base->setInheritConstructors();
  7212. return false;
  7213. }
  7214. /// Checks that the given using declaration is not an invalid
  7215. /// redeclaration. Note that this is checking only for the using decl
  7216. /// itself, not for any ill-formedness among the UsingShadowDecls.
  7217. bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
  7218. bool HasTypenameKeyword,
  7219. const CXXScopeSpec &SS,
  7220. SourceLocation NameLoc,
  7221. const LookupResult &Prev) {
  7222. // C++03 [namespace.udecl]p8:
  7223. // C++0x [namespace.udecl]p10:
  7224. // A using-declaration is a declaration and can therefore be used
  7225. // repeatedly where (and only where) multiple declarations are
  7226. // allowed.
  7227. //
  7228. // That's in non-member contexts.
  7229. if (!CurContext->getRedeclContext()->isRecord())
  7230. return false;
  7231. NestedNameSpecifier *Qual = SS.getScopeRep();
  7232. for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
  7233. NamedDecl *D = *I;
  7234. bool DTypename;
  7235. NestedNameSpecifier *DQual;
  7236. if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
  7237. DTypename = UD->hasTypename();
  7238. DQual = UD->getQualifier();
  7239. } else if (UnresolvedUsingValueDecl *UD
  7240. = dyn_cast<UnresolvedUsingValueDecl>(D)) {
  7241. DTypename = false;
  7242. DQual = UD->getQualifier();
  7243. } else if (UnresolvedUsingTypenameDecl *UD
  7244. = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
  7245. DTypename = true;
  7246. DQual = UD->getQualifier();
  7247. } else continue;
  7248. // using decls differ if one says 'typename' and the other doesn't.
  7249. // FIXME: non-dependent using decls?
  7250. if (HasTypenameKeyword != DTypename) continue;
  7251. // using decls differ if they name different scopes (but note that
  7252. // template instantiation can cause this check to trigger when it
  7253. // didn't before instantiation).
  7254. if (Context.getCanonicalNestedNameSpecifier(Qual) !=
  7255. Context.getCanonicalNestedNameSpecifier(DQual))
  7256. continue;
  7257. Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
  7258. Diag(D->getLocation(), diag::note_using_decl) << 1;
  7259. return true;
  7260. }
  7261. return false;
  7262. }
  7263. /// Checks that the given nested-name qualifier used in a using decl
  7264. /// in the current context is appropriately related to the current
  7265. /// scope. If an error is found, diagnoses it and returns true.
  7266. bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
  7267. const CXXScopeSpec &SS,
  7268. const DeclarationNameInfo &NameInfo,
  7269. SourceLocation NameLoc) {
  7270. DeclContext *NamedContext = computeDeclContext(SS);
  7271. if (!CurContext->isRecord()) {
  7272. // C++03 [namespace.udecl]p3:
  7273. // C++0x [namespace.udecl]p8:
  7274. // A using-declaration for a class member shall be a member-declaration.
  7275. // If we weren't able to compute a valid scope, it must be a
  7276. // dependent class scope.
  7277. if (!NamedContext || NamedContext->isRecord()) {
  7278. auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
  7279. if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
  7280. RD = nullptr;
  7281. Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
  7282. << SS.getRange();
  7283. // If we have a complete, non-dependent source type, try to suggest a
  7284. // way to get the same effect.
  7285. if (!RD)
  7286. return true;
  7287. // Find what this using-declaration was referring to.
  7288. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  7289. R.setHideTags(false);
  7290. R.suppressDiagnostics();
  7291. LookupQualifiedName(R, RD);
  7292. if (R.getAsSingle<TypeDecl>()) {
  7293. if (getLangOpts().CPlusPlus11) {
  7294. // Convert 'using X::Y;' to 'using Y = X::Y;'.
  7295. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
  7296. << 0 // alias declaration
  7297. << FixItHint::CreateInsertion(SS.getBeginLoc(),
  7298. NameInfo.getName().getAsString() +
  7299. " = ");
  7300. } else {
  7301. // Convert 'using X::Y;' to 'typedef X::Y Y;'.
  7302. SourceLocation InsertLoc =
  7303. PP.getLocForEndOfToken(NameInfo.getLocEnd());
  7304. Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
  7305. << 1 // typedef declaration
  7306. << FixItHint::CreateReplacement(UsingLoc, "typedef")
  7307. << FixItHint::CreateInsertion(
  7308. InsertLoc, " " + NameInfo.getName().getAsString());
  7309. }
  7310. } else if (R.getAsSingle<VarDecl>()) {
  7311. // Don't provide a fixit outside C++11 mode; we don't want to suggest
  7312. // repeating the type of the static data member here.
  7313. FixItHint FixIt;
  7314. if (getLangOpts().CPlusPlus11) {
  7315. // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
  7316. FixIt = FixItHint::CreateReplacement(
  7317. UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
  7318. }
  7319. Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
  7320. << 2 // reference declaration
  7321. << FixIt;
  7322. }
  7323. return true;
  7324. }
  7325. // Otherwise, everything is known to be fine.
  7326. return false;
  7327. }
  7328. // The current scope is a record.
  7329. // If the named context is dependent, we can't decide much.
  7330. if (!NamedContext) {
  7331. // FIXME: in C++0x, we can diagnose if we can prove that the
  7332. // nested-name-specifier does not refer to a base class, which is
  7333. // still possible in some cases.
  7334. // Otherwise we have to conservatively report that things might be
  7335. // okay.
  7336. return false;
  7337. }
  7338. if (!NamedContext->isRecord()) {
  7339. // Ideally this would point at the last name in the specifier,
  7340. // but we don't have that level of source info.
  7341. Diag(SS.getRange().getBegin(),
  7342. diag::err_using_decl_nested_name_specifier_is_not_class)
  7343. << SS.getScopeRep() << SS.getRange();
  7344. return true;
  7345. }
  7346. if (!NamedContext->isDependentContext() &&
  7347. RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
  7348. return true;
  7349. if (getLangOpts().CPlusPlus11) {
  7350. // C++0x [namespace.udecl]p3:
  7351. // In a using-declaration used as a member-declaration, the
  7352. // nested-name-specifier shall name a base class of the class
  7353. // being defined.
  7354. if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
  7355. cast<CXXRecordDecl>(NamedContext))) {
  7356. if (CurContext == NamedContext) {
  7357. Diag(NameLoc,
  7358. diag::err_using_decl_nested_name_specifier_is_current_class)
  7359. << SS.getRange();
  7360. return true;
  7361. }
  7362. Diag(SS.getRange().getBegin(),
  7363. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  7364. << SS.getScopeRep()
  7365. << cast<CXXRecordDecl>(CurContext)
  7366. << SS.getRange();
  7367. return true;
  7368. }
  7369. return false;
  7370. }
  7371. // C++03 [namespace.udecl]p4:
  7372. // A using-declaration used as a member-declaration shall refer
  7373. // to a member of a base class of the class being defined [etc.].
  7374. // Salient point: SS doesn't have to name a base class as long as
  7375. // lookup only finds members from base classes. Therefore we can
  7376. // diagnose here only if we can prove that that can't happen,
  7377. // i.e. if the class hierarchies provably don't intersect.
  7378. // TODO: it would be nice if "definitely valid" results were cached
  7379. // in the UsingDecl and UsingShadowDecl so that these checks didn't
  7380. // need to be repeated.
  7381. struct UserData {
  7382. llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
  7383. static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
  7384. UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
  7385. Data->Bases.insert(Base);
  7386. return true;
  7387. }
  7388. bool hasDependentBases(const CXXRecordDecl *Class) {
  7389. return !Class->forallBases(collect, this);
  7390. }
  7391. /// Returns true if the base is dependent or is one of the
  7392. /// accumulated base classes.
  7393. static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
  7394. UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
  7395. return !Data->Bases.count(Base);
  7396. }
  7397. bool mightShareBases(const CXXRecordDecl *Class) {
  7398. return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
  7399. }
  7400. };
  7401. UserData Data;
  7402. // Returns false if we find a dependent base.
  7403. if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
  7404. return false;
  7405. // Returns false if the class has a dependent base or if it or one
  7406. // of its bases is present in the base set of the current context.
  7407. if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
  7408. return false;
  7409. Diag(SS.getRange().getBegin(),
  7410. diag::err_using_decl_nested_name_specifier_is_not_base_class)
  7411. << SS.getScopeRep()
  7412. << cast<CXXRecordDecl>(CurContext)
  7413. << SS.getRange();
  7414. return true;
  7415. }
  7416. Decl *Sema::ActOnAliasDeclaration(Scope *S,
  7417. AccessSpecifier AS,
  7418. MultiTemplateParamsArg TemplateParamLists,
  7419. SourceLocation UsingLoc,
  7420. UnqualifiedId &Name,
  7421. AttributeList *AttrList,
  7422. TypeResult Type,
  7423. Decl *DeclFromDeclSpec) {
  7424. // Skip up to the relevant declaration scope.
  7425. while (S->getFlags() & Scope::TemplateParamScope)
  7426. S = S->getParent();
  7427. assert((S->getFlags() & Scope::DeclScope) &&
  7428. "got alias-declaration outside of declaration scope");
  7429. if (Type.isInvalid())
  7430. return nullptr;
  7431. bool Invalid = false;
  7432. DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
  7433. TypeSourceInfo *TInfo = nullptr;
  7434. GetTypeFromParser(Type.get(), &TInfo);
  7435. if (DiagnoseClassNameShadow(CurContext, NameInfo))
  7436. return nullptr;
  7437. if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
  7438. UPPC_DeclarationType)) {
  7439. Invalid = true;
  7440. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  7441. TInfo->getTypeLoc().getBeginLoc());
  7442. }
  7443. LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
  7444. LookupName(Previous, S);
  7445. // Warn about shadowing the name of a template parameter.
  7446. if (Previous.isSingleResult() &&
  7447. Previous.getFoundDecl()->isTemplateParameter()) {
  7448. DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
  7449. Previous.clear();
  7450. }
  7451. assert(Name.Kind == UnqualifiedId::IK_Identifier &&
  7452. "name in alias declaration must be an identifier");
  7453. TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
  7454. Name.StartLocation,
  7455. Name.Identifier, TInfo);
  7456. NewTD->setAccess(AS);
  7457. if (Invalid)
  7458. NewTD->setInvalidDecl();
  7459. ProcessDeclAttributeList(S, NewTD, AttrList);
  7460. CheckTypedefForVariablyModifiedType(S, NewTD);
  7461. Invalid |= NewTD->isInvalidDecl();
  7462. bool Redeclaration = false;
  7463. NamedDecl *NewND;
  7464. if (TemplateParamLists.size()) {
  7465. TypeAliasTemplateDecl *OldDecl = nullptr;
  7466. TemplateParameterList *OldTemplateParams = nullptr;
  7467. if (TemplateParamLists.size() != 1) {
  7468. Diag(UsingLoc, diag::err_alias_template_extra_headers)
  7469. << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
  7470. TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
  7471. }
  7472. TemplateParameterList *TemplateParams = TemplateParamLists[0];
  7473. // Only consider previous declarations in the same scope.
  7474. FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
  7475. /*ExplicitInstantiationOrSpecialization*/false);
  7476. if (!Previous.empty()) {
  7477. Redeclaration = true;
  7478. OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
  7479. if (!OldDecl && !Invalid) {
  7480. Diag(UsingLoc, diag::err_redefinition_different_kind)
  7481. << Name.Identifier;
  7482. NamedDecl *OldD = Previous.getRepresentativeDecl();
  7483. if (OldD->getLocation().isValid())
  7484. Diag(OldD->getLocation(), diag::note_previous_definition);
  7485. Invalid = true;
  7486. }
  7487. if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
  7488. if (TemplateParameterListsAreEqual(TemplateParams,
  7489. OldDecl->getTemplateParameters(),
  7490. /*Complain=*/true,
  7491. TPL_TemplateMatch))
  7492. OldTemplateParams = OldDecl->getTemplateParameters();
  7493. else
  7494. Invalid = true;
  7495. TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
  7496. if (!Invalid &&
  7497. !Context.hasSameType(OldTD->getUnderlyingType(),
  7498. NewTD->getUnderlyingType())) {
  7499. // FIXME: The C++0x standard does not clearly say this is ill-formed,
  7500. // but we can't reasonably accept it.
  7501. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
  7502. << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
  7503. if (OldTD->getLocation().isValid())
  7504. Diag(OldTD->getLocation(), diag::note_previous_definition);
  7505. Invalid = true;
  7506. }
  7507. }
  7508. }
  7509. // Merge any previous default template arguments into our parameters,
  7510. // and check the parameter list.
  7511. if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
  7512. TPC_TypeAliasTemplate))
  7513. return nullptr;
  7514. TypeAliasTemplateDecl *NewDecl =
  7515. TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
  7516. Name.Identifier, TemplateParams,
  7517. NewTD);
  7518. NewTD->setDescribedAliasTemplate(NewDecl);
  7519. NewDecl->setAccess(AS);
  7520. if (Invalid)
  7521. NewDecl->setInvalidDecl();
  7522. else if (OldDecl)
  7523. NewDecl->setPreviousDecl(OldDecl);
  7524. NewND = NewDecl;
  7525. } else {
  7526. if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
  7527. setTagNameForLinkagePurposes(TD, NewTD);
  7528. handleTagNumbering(TD, S);
  7529. }
  7530. ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
  7531. NewND = NewTD;
  7532. }
  7533. if (!Redeclaration)
  7534. PushOnScopeChains(NewND, S);
  7535. ActOnDocumentableDecl(NewND);
  7536. return NewND;
  7537. }
  7538. Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
  7539. SourceLocation AliasLoc,
  7540. IdentifierInfo *Alias, CXXScopeSpec &SS,
  7541. SourceLocation IdentLoc,
  7542. IdentifierInfo *Ident) {
  7543. // Lookup the namespace name.
  7544. LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
  7545. LookupParsedName(R, S, &SS);
  7546. if (R.isAmbiguous())
  7547. return nullptr;
  7548. if (R.empty()) {
  7549. if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
  7550. Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
  7551. return nullptr;
  7552. }
  7553. }
  7554. assert(!R.isAmbiguous() && !R.empty());
  7555. // Check if we have a previous declaration with the same name.
  7556. NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
  7557. ForRedeclaration);
  7558. if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
  7559. PrevDecl = nullptr;
  7560. NamedDecl *ND = R.getFoundDecl();
  7561. if (PrevDecl) {
  7562. if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
  7563. // We already have an alias with the same name that points to the same
  7564. // namespace; check that it matches.
  7565. if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
  7566. Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
  7567. << Alias;
  7568. Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
  7569. << AD->getNamespace();
  7570. return nullptr;
  7571. }
  7572. } else {
  7573. unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
  7574. ? diag::err_redefinition
  7575. : diag::err_redefinition_different_kind;
  7576. Diag(AliasLoc, DiagID) << Alias;
  7577. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7578. return nullptr;
  7579. }
  7580. }
  7581. // The use of a nested name specifier may trigger deprecation warnings.
  7582. DiagnoseUseOfDecl(ND, IdentLoc);
  7583. NamespaceAliasDecl *AliasDecl =
  7584. NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
  7585. Alias, SS.getWithLocInContext(Context),
  7586. IdentLoc, ND);
  7587. if (PrevDecl)
  7588. AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
  7589. PushOnScopeChains(AliasDecl, S);
  7590. return AliasDecl;
  7591. }
  7592. Sema::ImplicitExceptionSpecification
  7593. Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
  7594. CXXMethodDecl *MD) {
  7595. CXXRecordDecl *ClassDecl = MD->getParent();
  7596. // C++ [except.spec]p14:
  7597. // An implicitly declared special member function (Clause 12) shall have an
  7598. // exception-specification. [...]
  7599. ImplicitExceptionSpecification ExceptSpec(*this);
  7600. if (ClassDecl->isInvalidDecl())
  7601. return ExceptSpec;
  7602. // Direct base-class constructors.
  7603. for (const auto &B : ClassDecl->bases()) {
  7604. if (B.isVirtual()) // Handled below.
  7605. continue;
  7606. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7607. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7608. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7609. // If this is a deleted function, add it anyway. This might be conformant
  7610. // with the standard. This might not. I'm not sure. It might not matter.
  7611. if (Constructor)
  7612. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7613. }
  7614. }
  7615. // Virtual base-class constructors.
  7616. for (const auto &B : ClassDecl->vbases()) {
  7617. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7618. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7619. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7620. // If this is a deleted function, add it anyway. This might be conformant
  7621. // with the standard. This might not. I'm not sure. It might not matter.
  7622. if (Constructor)
  7623. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7624. }
  7625. }
  7626. // Field constructors.
  7627. for (const auto *F : ClassDecl->fields()) {
  7628. if (F->hasInClassInitializer()) {
  7629. if (Expr *E = F->getInClassInitializer())
  7630. ExceptSpec.CalledExpr(E);
  7631. } else if (const RecordType *RecordTy
  7632. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  7633. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  7634. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  7635. // If this is a deleted function, add it anyway. This might be conformant
  7636. // with the standard. This might not. I'm not sure. It might not matter.
  7637. // In particular, the problem is that this function never gets called. It
  7638. // might just be ill-formed because this function attempts to refer to
  7639. // a deleted function here.
  7640. if (Constructor)
  7641. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  7642. }
  7643. }
  7644. return ExceptSpec;
  7645. }
  7646. Sema::ImplicitExceptionSpecification
  7647. Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
  7648. CXXRecordDecl *ClassDecl = CD->getParent();
  7649. // C++ [except.spec]p14:
  7650. // An inheriting constructor [...] shall have an exception-specification. [...]
  7651. ImplicitExceptionSpecification ExceptSpec(*this);
  7652. if (ClassDecl->isInvalidDecl())
  7653. return ExceptSpec;
  7654. // Inherited constructor.
  7655. const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
  7656. const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
  7657. // FIXME: Copying or moving the parameters could add extra exceptions to the
  7658. // set, as could the default arguments for the inherited constructor. This
  7659. // will be addressed when we implement the resolution of core issue 1351.
  7660. ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
  7661. // Direct base-class constructors.
  7662. for (const auto &B : ClassDecl->bases()) {
  7663. if (B.isVirtual()) // Handled below.
  7664. continue;
  7665. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7666. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7667. if (BaseClassDecl == InheritedDecl)
  7668. continue;
  7669. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7670. if (Constructor)
  7671. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7672. }
  7673. }
  7674. // Virtual base-class constructors.
  7675. for (const auto &B : ClassDecl->vbases()) {
  7676. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  7677. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  7678. if (BaseClassDecl == InheritedDecl)
  7679. continue;
  7680. CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
  7681. if (Constructor)
  7682. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  7683. }
  7684. }
  7685. // Field constructors.
  7686. for (const auto *F : ClassDecl->fields()) {
  7687. if (F->hasInClassInitializer()) {
  7688. if (Expr *E = F->getInClassInitializer())
  7689. ExceptSpec.CalledExpr(E);
  7690. } else if (const RecordType *RecordTy
  7691. = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
  7692. CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  7693. CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
  7694. if (Constructor)
  7695. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  7696. }
  7697. }
  7698. return ExceptSpec;
  7699. }
  7700. namespace {
  7701. /// RAII object to register a special member as being currently declared.
  7702. struct DeclaringSpecialMember {
  7703. Sema &S;
  7704. Sema::SpecialMemberDecl D;
  7705. bool WasAlreadyBeingDeclared;
  7706. DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
  7707. : S(S), D(RD, CSM) {
  7708. WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
  7709. if (WasAlreadyBeingDeclared)
  7710. // This almost never happens, but if it does, ensure that our cache
  7711. // doesn't contain a stale result.
  7712. S.SpecialMemberCache.clear();
  7713. // FIXME: Register a note to be produced if we encounter an error while
  7714. // declaring the special member.
  7715. }
  7716. ~DeclaringSpecialMember() {
  7717. if (!WasAlreadyBeingDeclared)
  7718. S.SpecialMembersBeingDeclared.erase(D);
  7719. }
  7720. /// \brief Are we already trying to declare this special member?
  7721. bool isAlreadyBeingDeclared() const {
  7722. return WasAlreadyBeingDeclared;
  7723. }
  7724. };
  7725. }
  7726. CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
  7727. CXXRecordDecl *ClassDecl) {
  7728. // C++ [class.ctor]p5:
  7729. // A default constructor for a class X is a constructor of class X
  7730. // that can be called without an argument. If there is no
  7731. // user-declared constructor for class X, a default constructor is
  7732. // implicitly declared. An implicitly-declared default constructor
  7733. // is an inline public member of its class.
  7734. assert(ClassDecl->needsImplicitDefaultConstructor() &&
  7735. "Should not build implicit default constructor!");
  7736. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
  7737. if (DSM.isAlreadyBeingDeclared())
  7738. return nullptr;
  7739. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  7740. CXXDefaultConstructor,
  7741. false);
  7742. // Create the actual constructor declaration.
  7743. CanQualType ClassType
  7744. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  7745. SourceLocation ClassLoc = ClassDecl->getLocation();
  7746. DeclarationName Name
  7747. = Context.DeclarationNames.getCXXConstructorName(ClassType);
  7748. DeclarationNameInfo NameInfo(Name, ClassLoc);
  7749. CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
  7750. Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
  7751. /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
  7752. /*isImplicitlyDeclared=*/true, Constexpr);
  7753. DefaultCon->setAccess(AS_public);
  7754. DefaultCon->setDefaulted();
  7755. if (getLangOpts().CUDA) {
  7756. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
  7757. DefaultCon,
  7758. /* ConstRHS */ false,
  7759. /* Diagnose */ false);
  7760. }
  7761. // Build an exception specification pointing back at this constructor.
  7762. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
  7763. DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change - add param mods
  7764. // We don't need to use SpecialMemberIsTrivial here; triviality for default
  7765. // constructors is easy to compute.
  7766. DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
  7767. if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
  7768. SetDeclDeleted(DefaultCon, ClassLoc);
  7769. // Note that we have declared this constructor.
  7770. ++ASTContext::NumImplicitDefaultConstructorsDeclared;
  7771. if (Scope *S = getScopeForContext(ClassDecl))
  7772. PushOnScopeChains(DefaultCon, S, false);
  7773. ClassDecl->addDecl(DefaultCon);
  7774. return DefaultCon;
  7775. }
  7776. void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
  7777. CXXConstructorDecl *Constructor) {
  7778. assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
  7779. !Constructor->doesThisDeclarationHaveABody() &&
  7780. !Constructor->isDeleted()) &&
  7781. "DefineImplicitDefaultConstructor - call it for implicit default ctor");
  7782. CXXRecordDecl *ClassDecl = Constructor->getParent();
  7783. assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
  7784. SynthesizedFunctionScope Scope(*this, Constructor);
  7785. DiagnosticErrorTrap Trap(Diags);
  7786. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
  7787. Trap.hasErrorOccurred()) {
  7788. Diag(CurrentLocation, diag::note_member_synthesized_at)
  7789. << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
  7790. Constructor->setInvalidDecl();
  7791. return;
  7792. }
  7793. // The exception specification is needed because we are defining the
  7794. // function.
  7795. ResolveExceptionSpec(CurrentLocation,
  7796. Constructor->getType()->castAs<FunctionProtoType>());
  7797. SourceLocation Loc = Constructor->getLocEnd().isValid()
  7798. ? Constructor->getLocEnd()
  7799. : Constructor->getLocation();
  7800. Constructor->setBody(new (Context) CompoundStmt(Loc));
  7801. Constructor->markUsed(Context);
  7802. MarkVTableUsed(CurrentLocation, ClassDecl);
  7803. if (ASTMutationListener *L = getASTMutationListener()) {
  7804. L->CompletedImplicitDefinition(Constructor);
  7805. }
  7806. DiagnoseUninitializedFields(*this, Constructor);
  7807. }
  7808. void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
  7809. // Perform any delayed checks on exception specifications.
  7810. CheckDelayedMemberExceptionSpecs();
  7811. }
  7812. namespace {
  7813. /// Information on inheriting constructors to declare.
  7814. class InheritingConstructorInfo {
  7815. public:
  7816. InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
  7817. : SemaRef(SemaRef), Derived(Derived) {
  7818. // Mark the constructors that we already have in the derived class.
  7819. //
  7820. // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
  7821. // unless there is a user-declared constructor with the same signature in
  7822. // the class where the using-declaration appears.
  7823. visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
  7824. }
  7825. void inheritAll(CXXRecordDecl *RD) {
  7826. visitAll(RD, &InheritingConstructorInfo::inherit);
  7827. }
  7828. private:
  7829. /// Information about an inheriting constructor.
  7830. struct InheritingConstructor {
  7831. InheritingConstructor()
  7832. : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
  7833. /// If \c true, a constructor with this signature is already declared
  7834. /// in the derived class.
  7835. bool DeclaredInDerived;
  7836. /// The constructor which is inherited.
  7837. const CXXConstructorDecl *BaseCtor;
  7838. /// The derived constructor we declared.
  7839. CXXConstructorDecl *DerivedCtor;
  7840. };
  7841. /// Inheriting constructors with a given canonical type. There can be at
  7842. /// most one such non-template constructor, and any number of templated
  7843. /// constructors.
  7844. struct InheritingConstructorsForType {
  7845. InheritingConstructor NonTemplate;
  7846. SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
  7847. Templates;
  7848. InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
  7849. if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
  7850. TemplateParameterList *ParamList = FTD->getTemplateParameters();
  7851. for (unsigned I = 0, N = Templates.size(); I != N; ++I)
  7852. if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
  7853. false, S.TPL_TemplateMatch))
  7854. return Templates[I].second;
  7855. Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
  7856. return Templates.back().second;
  7857. }
  7858. return NonTemplate;
  7859. }
  7860. };
  7861. /// Get or create the inheriting constructor record for a constructor.
  7862. InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
  7863. QualType CtorType) {
  7864. return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
  7865. .getEntry(SemaRef, Ctor);
  7866. }
  7867. typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
  7868. /// Process all constructors for a class.
  7869. void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
  7870. for (const auto *Ctor : RD->ctors())
  7871. (this->*Callback)(Ctor);
  7872. for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
  7873. I(RD->decls_begin()), E(RD->decls_end());
  7874. I != E; ++I) {
  7875. const FunctionDecl *FD = (*I)->getTemplatedDecl();
  7876. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  7877. (this->*Callback)(CD);
  7878. }
  7879. }
  7880. /// Note that a constructor (or constructor template) was declared in Derived.
  7881. void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
  7882. getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
  7883. }
  7884. /// Inherit a single constructor.
  7885. void inherit(const CXXConstructorDecl *Ctor) {
  7886. const FunctionProtoType *CtorType =
  7887. Ctor->getType()->castAs<FunctionProtoType>();
  7888. ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
  7889. FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
  7890. SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
  7891. // Core issue (no number yet): the ellipsis is always discarded.
  7892. if (EPI.Variadic) {
  7893. SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
  7894. SemaRef.Diag(Ctor->getLocation(),
  7895. diag::note_using_decl_constructor_ellipsis);
  7896. EPI.Variadic = false;
  7897. }
  7898. // Declare a constructor for each number of parameters.
  7899. //
  7900. // C++11 [class.inhctor]p1:
  7901. // The candidate set of inherited constructors from the class X named in
  7902. // the using-declaration consists of [... modulo defects ...] for each
  7903. // constructor or constructor template of X, the set of constructors or
  7904. // constructor templates that results from omitting any ellipsis parameter
  7905. // specification and successively omitting parameters with a default
  7906. // argument from the end of the parameter-type-list
  7907. unsigned MinParams = minParamsToInherit(Ctor);
  7908. unsigned Params = Ctor->getNumParams();
  7909. if (Params >= MinParams) {
  7910. do
  7911. declareCtor(UsingLoc, Ctor,
  7912. SemaRef.Context.getFunctionType(
  7913. Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI, None)); // HLSL Change - add param mods
  7914. while (Params > MinParams &&
  7915. Ctor->getParamDecl(--Params)->hasDefaultArg());
  7916. }
  7917. }
  7918. /// Find the using-declaration which specified that we should inherit the
  7919. /// constructors of \p Base.
  7920. SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
  7921. // No fancy lookup required; just look for the base constructor name
  7922. // directly within the derived class.
  7923. ASTContext &Context = SemaRef.Context;
  7924. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
  7925. Context.getCanonicalType(Context.getRecordType(Base)));
  7926. DeclContext::lookup_result Decls = Derived->lookup(Name);
  7927. return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
  7928. }
  7929. unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
  7930. // C++11 [class.inhctor]p3:
  7931. // [F]or each constructor template in the candidate set of inherited
  7932. // constructors, a constructor template is implicitly declared
  7933. if (Ctor->getDescribedFunctionTemplate())
  7934. return 0;
  7935. // For each non-template constructor in the candidate set of inherited
  7936. // constructors other than a constructor having no parameters or a
  7937. // copy/move constructor having a single parameter, a constructor is
  7938. // implicitly declared [...]
  7939. if (Ctor->getNumParams() == 0)
  7940. return 1;
  7941. if (Ctor->isCopyOrMoveConstructor())
  7942. return 2;
  7943. // Per discussion on core reflector, never inherit a constructor which
  7944. // would become a default, copy, or move constructor of Derived either.
  7945. const ParmVarDecl *PD = Ctor->getParamDecl(0);
  7946. const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
  7947. return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
  7948. }
  7949. /// Declare a single inheriting constructor, inheriting the specified
  7950. /// constructor, with the given type.
  7951. void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
  7952. QualType DerivedType) {
  7953. InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
  7954. // C++11 [class.inhctor]p3:
  7955. // ... a constructor is implicitly declared with the same constructor
  7956. // characteristics unless there is a user-declared constructor with
  7957. // the same signature in the class where the using-declaration appears
  7958. if (Entry.DeclaredInDerived)
  7959. return;
  7960. // C++11 [class.inhctor]p7:
  7961. // If two using-declarations declare inheriting constructors with the
  7962. // same signature, the program is ill-formed
  7963. if (Entry.DerivedCtor) {
  7964. if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
  7965. // Only diagnose this once per constructor.
  7966. if (Entry.DerivedCtor->isInvalidDecl())
  7967. return;
  7968. Entry.DerivedCtor->setInvalidDecl();
  7969. SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
  7970. SemaRef.Diag(BaseCtor->getLocation(),
  7971. diag::note_using_decl_constructor_conflict_current_ctor);
  7972. SemaRef.Diag(Entry.BaseCtor->getLocation(),
  7973. diag::note_using_decl_constructor_conflict_previous_ctor);
  7974. SemaRef.Diag(Entry.DerivedCtor->getLocation(),
  7975. diag::note_using_decl_constructor_conflict_previous_using);
  7976. } else {
  7977. // Core issue (no number): if the same inheriting constructor is
  7978. // produced by multiple base class constructors from the same base
  7979. // class, the inheriting constructor is defined as deleted.
  7980. SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
  7981. }
  7982. return;
  7983. }
  7984. ASTContext &Context = SemaRef.Context;
  7985. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
  7986. Context.getCanonicalType(Context.getRecordType(Derived)));
  7987. DeclarationNameInfo NameInfo(Name, UsingLoc);
  7988. TemplateParameterList *TemplateParams = nullptr;
  7989. if (const FunctionTemplateDecl *FTD =
  7990. BaseCtor->getDescribedFunctionTemplate()) {
  7991. TemplateParams = FTD->getTemplateParameters();
  7992. // We're reusing template parameters from a different DeclContext. This
  7993. // is questionable at best, but works out because the template depth in
  7994. // both places is guaranteed to be 0.
  7995. // FIXME: Rebuild the template parameters in the new context, and
  7996. // transform the function type to refer to them.
  7997. }
  7998. // Build type source info pointing at the using-declaration. This is
  7999. // required by template instantiation.
  8000. TypeSourceInfo *TInfo =
  8001. Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
  8002. FunctionProtoTypeLoc ProtoLoc =
  8003. TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
  8004. CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
  8005. Context, Derived, UsingLoc, NameInfo, DerivedType,
  8006. TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
  8007. /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
  8008. // Build an unevaluated exception specification for this constructor.
  8009. const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
  8010. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8011. EPI.ExceptionSpec.Type = EST_Unevaluated;
  8012. EPI.ExceptionSpec.SourceDecl = DerivedCtor;
  8013. DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
  8014. FPT->getParamTypes(), EPI, None)); // HLSL Change - add param mods
  8015. // Build the parameter declarations.
  8016. SmallVector<ParmVarDecl *, 16> ParamDecls;
  8017. for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
  8018. TypeSourceInfo *TInfo =
  8019. Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
  8020. ParmVarDecl *PD = ParmVarDecl::Create(
  8021. Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
  8022. FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
  8023. PD->setScopeInfo(0, I);
  8024. PD->setImplicit();
  8025. ParamDecls.push_back(PD);
  8026. ProtoLoc.setParam(I, PD);
  8027. }
  8028. // Set up the new constructor.
  8029. DerivedCtor->setAccess(BaseCtor->getAccess());
  8030. DerivedCtor->setParams(ParamDecls);
  8031. DerivedCtor->setInheritedConstructor(BaseCtor);
  8032. if (BaseCtor->isDeleted())
  8033. SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
  8034. // If this is a constructor template, build the template declaration.
  8035. if (TemplateParams) {
  8036. FunctionTemplateDecl *DerivedTemplate =
  8037. FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
  8038. TemplateParams, DerivedCtor);
  8039. DerivedTemplate->setAccess(BaseCtor->getAccess());
  8040. DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
  8041. Derived->addDecl(DerivedTemplate);
  8042. } else {
  8043. Derived->addDecl(DerivedCtor);
  8044. }
  8045. Entry.BaseCtor = BaseCtor;
  8046. Entry.DerivedCtor = DerivedCtor;
  8047. }
  8048. Sema &SemaRef;
  8049. CXXRecordDecl *Derived;
  8050. typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
  8051. MapType Map;
  8052. };
  8053. }
  8054. void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
  8055. // Defer declaring the inheriting constructors until the class is
  8056. // instantiated.
  8057. if (ClassDecl->isDependentContext())
  8058. return;
  8059. // Find base classes from which we might inherit constructors.
  8060. SmallVector<CXXRecordDecl*, 4> InheritedBases;
  8061. for (const auto &BaseIt : ClassDecl->bases())
  8062. if (BaseIt.getInheritConstructors())
  8063. InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
  8064. // Go no further if we're not inheriting any constructors.
  8065. if (InheritedBases.empty())
  8066. return;
  8067. // Declare the inherited constructors.
  8068. InheritingConstructorInfo ICI(*this, ClassDecl);
  8069. for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
  8070. ICI.inheritAll(InheritedBases[I]);
  8071. }
  8072. void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
  8073. CXXConstructorDecl *Constructor) {
  8074. CXXRecordDecl *ClassDecl = Constructor->getParent();
  8075. assert(Constructor->getInheritedConstructor() &&
  8076. !Constructor->doesThisDeclarationHaveABody() &&
  8077. !Constructor->isDeleted());
  8078. SynthesizedFunctionScope Scope(*this, Constructor);
  8079. DiagnosticErrorTrap Trap(Diags);
  8080. if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
  8081. Trap.hasErrorOccurred()) {
  8082. Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
  8083. << Context.getTagDeclType(ClassDecl);
  8084. Constructor->setInvalidDecl();
  8085. return;
  8086. }
  8087. SourceLocation Loc = Constructor->getLocation();
  8088. Constructor->setBody(new (Context) CompoundStmt(Loc));
  8089. Constructor->markUsed(Context);
  8090. MarkVTableUsed(CurrentLocation, ClassDecl);
  8091. if (ASTMutationListener *L = getASTMutationListener()) {
  8092. L->CompletedImplicitDefinition(Constructor);
  8093. }
  8094. }
  8095. Sema::ImplicitExceptionSpecification
  8096. Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
  8097. CXXRecordDecl *ClassDecl = MD->getParent();
  8098. // C++ [except.spec]p14:
  8099. // An implicitly declared special member function (Clause 12) shall have
  8100. // an exception-specification.
  8101. ImplicitExceptionSpecification ExceptSpec(*this);
  8102. if (ClassDecl->isInvalidDecl())
  8103. return ExceptSpec;
  8104. // Direct base-class destructors.
  8105. for (const auto &B : ClassDecl->bases()) {
  8106. if (B.isVirtual()) // Handled below.
  8107. continue;
  8108. if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
  8109. ExceptSpec.CalledDecl(B.getLocStart(),
  8110. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  8111. }
  8112. // Virtual base-class destructors.
  8113. for (const auto &B : ClassDecl->vbases()) {
  8114. if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
  8115. ExceptSpec.CalledDecl(B.getLocStart(),
  8116. LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
  8117. }
  8118. // Field destructors.
  8119. for (const auto *F : ClassDecl->fields()) {
  8120. if (const RecordType *RecordTy
  8121. = Context.getBaseElementType(F->getType())->getAs<RecordType>())
  8122. ExceptSpec.CalledDecl(F->getLocation(),
  8123. LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
  8124. }
  8125. return ExceptSpec;
  8126. }
  8127. CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
  8128. // C++ [class.dtor]p2:
  8129. // If a class has no user-declared destructor, a destructor is
  8130. // declared implicitly. An implicitly-declared destructor is an
  8131. // inline public member of its class.
  8132. assert(ClassDecl->needsImplicitDestructor());
  8133. DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
  8134. if (DSM.isAlreadyBeingDeclared())
  8135. return nullptr;
  8136. // Create the actual destructor declaration.
  8137. CanQualType ClassType
  8138. = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
  8139. SourceLocation ClassLoc = ClassDecl->getLocation();
  8140. DeclarationName Name
  8141. = Context.DeclarationNames.getCXXDestructorName(ClassType);
  8142. DeclarationNameInfo NameInfo(Name, ClassLoc);
  8143. CXXDestructorDecl *Destructor
  8144. = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
  8145. QualType(), nullptr, /*isInline=*/true,
  8146. /*isImplicitlyDeclared=*/true);
  8147. Destructor->setAccess(AS_public);
  8148. Destructor->setDefaulted();
  8149. if (getLangOpts().CUDA) {
  8150. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
  8151. Destructor,
  8152. /* ConstRHS */ false,
  8153. /* Diagnose */ false);
  8154. }
  8155. // Build an exception specification pointing back at this destructor.
  8156. FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
  8157. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change
  8158. AddOverriddenMethods(ClassDecl, Destructor);
  8159. // We don't need to use SpecialMemberIsTrivial here; triviality for
  8160. // destructors is easy to compute.
  8161. Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
  8162. if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
  8163. SetDeclDeleted(Destructor, ClassLoc);
  8164. // Note that we have declared this destructor.
  8165. ++ASTContext::NumImplicitDestructorsDeclared;
  8166. // Introduce this destructor into its scope.
  8167. if (Scope *S = getScopeForContext(ClassDecl))
  8168. PushOnScopeChains(Destructor, S, false);
  8169. ClassDecl->addDecl(Destructor);
  8170. return Destructor;
  8171. }
  8172. void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
  8173. CXXDestructorDecl *Destructor) {
  8174. assert((Destructor->isDefaulted() &&
  8175. !Destructor->doesThisDeclarationHaveABody() &&
  8176. !Destructor->isDeleted()) &&
  8177. "DefineImplicitDestructor - call it for implicit default dtor");
  8178. CXXRecordDecl *ClassDecl = Destructor->getParent();
  8179. assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
  8180. if (Destructor->isInvalidDecl())
  8181. return;
  8182. SynthesizedFunctionScope Scope(*this, Destructor);
  8183. DiagnosticErrorTrap Trap(Diags);
  8184. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  8185. Destructor->getParent());
  8186. if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
  8187. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8188. << CXXDestructor << Context.getTagDeclType(ClassDecl);
  8189. Destructor->setInvalidDecl();
  8190. return;
  8191. }
  8192. // The exception specification is needed because we are defining the
  8193. // function.
  8194. ResolveExceptionSpec(CurrentLocation,
  8195. Destructor->getType()->castAs<FunctionProtoType>());
  8196. SourceLocation Loc = Destructor->getLocEnd().isValid()
  8197. ? Destructor->getLocEnd()
  8198. : Destructor->getLocation();
  8199. Destructor->setBody(new (Context) CompoundStmt(Loc));
  8200. Destructor->markUsed(Context);
  8201. MarkVTableUsed(CurrentLocation, ClassDecl);
  8202. if (ASTMutationListener *L = getASTMutationListener()) {
  8203. L->CompletedImplicitDefinition(Destructor);
  8204. }
  8205. }
  8206. /// \brief Perform any semantic analysis which needs to be delayed until all
  8207. /// pending class member declarations have been parsed.
  8208. void Sema::ActOnFinishCXXMemberDecls() {
  8209. // If the context is an invalid C++ class, just suppress these checks.
  8210. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
  8211. if (Record->isInvalidDecl()) {
  8212. DelayedDefaultedMemberExceptionSpecs.clear();
  8213. DelayedExceptionSpecChecks.clear();
  8214. return;
  8215. }
  8216. }
  8217. }
  8218. static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
  8219. // Don't do anything for template patterns.
  8220. if (Class->getDescribedClassTemplate())
  8221. return;
  8222. for (Decl *Member : Class->decls()) {
  8223. auto *CD = dyn_cast<CXXConstructorDecl>(Member);
  8224. if (!CD) {
  8225. // Recurse on nested classes.
  8226. if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
  8227. getDefaultArgExprsForConstructors(S, NestedRD);
  8228. continue;
  8229. } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
  8230. continue;
  8231. }
  8232. for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
  8233. // Skip any default arguments that we've already instantiated.
  8234. if (S.Context.getDefaultArgExprForConstructor(CD, I))
  8235. continue;
  8236. Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
  8237. CD->getParamDecl(I)).get();
  8238. S.DiscardCleanupsInEvaluationContext();
  8239. S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
  8240. }
  8241. }
  8242. }
  8243. void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
  8244. auto *RD = dyn_cast<CXXRecordDecl>(D);
  8245. // Default constructors that are annotated with __declspec(dllexport) which
  8246. // have default arguments or don't use the standard calling convention are
  8247. // wrapped with a thunk called the default constructor closure.
  8248. if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
  8249. getDefaultArgExprsForConstructors(*this, RD);
  8250. }
  8251. void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
  8252. CXXDestructorDecl *Destructor) {
  8253. assert(getLangOpts().CPlusPlus11 &&
  8254. "adjusting dtor exception specs was introduced in c++11");
  8255. // C++11 [class.dtor]p3:
  8256. // A declaration of a destructor that does not have an exception-
  8257. // specification is implicitly considered to have the same exception-
  8258. // specification as an implicit declaration.
  8259. const FunctionProtoType *DtorType = Destructor->getType()->
  8260. getAs<FunctionProtoType>();
  8261. if (DtorType->hasExceptionSpec())
  8262. return;
  8263. // Replace the destructor's type, building off the existing one. Fortunately,
  8264. // the only thing of interest in the destructor type is its extended info.
  8265. // The return and arguments are fixed.
  8266. FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
  8267. EPI.ExceptionSpec.Type = EST_Unevaluated;
  8268. EPI.ExceptionSpec.SourceDecl = Destructor;
  8269. Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI, None)); // HLSL Change - add param mods
  8270. // FIXME: If the destructor has a body that could throw, and the newly created
  8271. // spec doesn't allow exceptions, we should emit a warning, because this
  8272. // change in behavior can break conforming C++03 programs at runtime.
  8273. // However, we don't have a body or an exception specification yet, so it
  8274. // needs to be done somewhere else.
  8275. }
  8276. namespace {
  8277. /// \brief An abstract base class for all helper classes used in building the
  8278. // copy/move operators. These classes serve as factory functions and help us
  8279. // avoid using the same Expr* in the AST twice.
  8280. class ExprBuilder {
  8281. ExprBuilder(const ExprBuilder&) = delete;
  8282. ExprBuilder &operator=(const ExprBuilder&) = delete;
  8283. protected:
  8284. static Expr *assertNotNull(Expr *E) {
  8285. assert(E && "Expression construction must not fail.");
  8286. return E;
  8287. }
  8288. public:
  8289. ExprBuilder() {}
  8290. virtual ~ExprBuilder() {}
  8291. virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
  8292. };
  8293. class RefBuilder: public ExprBuilder {
  8294. VarDecl *Var;
  8295. QualType VarType;
  8296. public:
  8297. Expr *build(Sema &S, SourceLocation Loc) const override {
  8298. return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
  8299. }
  8300. RefBuilder(VarDecl *Var, QualType VarType)
  8301. : Var(Var), VarType(VarType) {}
  8302. };
  8303. class ThisBuilder: public ExprBuilder {
  8304. public:
  8305. Expr *build(Sema &S, SourceLocation Loc) const override {
  8306. return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
  8307. }
  8308. };
  8309. class CastBuilder: public ExprBuilder {
  8310. const ExprBuilder &Builder;
  8311. QualType Type;
  8312. ExprValueKind Kind;
  8313. const CXXCastPath &Path;
  8314. public:
  8315. Expr *build(Sema &S, SourceLocation Loc) const override {
  8316. return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
  8317. CK_UncheckedDerivedToBase, Kind,
  8318. &Path).get());
  8319. }
  8320. CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
  8321. const CXXCastPath &Path)
  8322. : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
  8323. };
  8324. class DerefBuilder: public ExprBuilder {
  8325. const ExprBuilder &Builder;
  8326. public:
  8327. Expr *build(Sema &S, SourceLocation Loc) const override {
  8328. return assertNotNull(
  8329. S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
  8330. }
  8331. DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  8332. };
  8333. class MemberBuilder: public ExprBuilder {
  8334. const ExprBuilder &Builder;
  8335. QualType Type;
  8336. CXXScopeSpec SS;
  8337. bool IsArrow;
  8338. LookupResult &MemberLookup;
  8339. public:
  8340. Expr *build(Sema &S, SourceLocation Loc) const override {
  8341. return assertNotNull(S.BuildMemberReferenceExpr(
  8342. Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
  8343. nullptr, MemberLookup, nullptr).get());
  8344. }
  8345. MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
  8346. LookupResult &MemberLookup)
  8347. : Builder(Builder), Type(Type), IsArrow(IsArrow),
  8348. MemberLookup(MemberLookup) {}
  8349. };
  8350. class MoveCastBuilder: public ExprBuilder {
  8351. const ExprBuilder &Builder;
  8352. public:
  8353. Expr *build(Sema &S, SourceLocation Loc) const override {
  8354. return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
  8355. }
  8356. MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  8357. };
  8358. class LvalueConvBuilder: public ExprBuilder {
  8359. const ExprBuilder &Builder;
  8360. public:
  8361. Expr *build(Sema &S, SourceLocation Loc) const override {
  8362. return assertNotNull(
  8363. S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
  8364. }
  8365. LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
  8366. };
  8367. class SubscriptBuilder: public ExprBuilder {
  8368. const ExprBuilder &Base;
  8369. const ExprBuilder &Index;
  8370. public:
  8371. Expr *build(Sema &S, SourceLocation Loc) const override {
  8372. return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
  8373. Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
  8374. }
  8375. SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
  8376. : Base(Base), Index(Index) {}
  8377. };
  8378. } // end anonymous namespace
  8379. /// When generating a defaulted copy or move assignment operator, if a field
  8380. /// should be copied with __builtin_memcpy rather than via explicit assignments,
  8381. /// do so. This optimization only applies for arrays of scalars, and for arrays
  8382. /// of class type where the selected copy/move-assignment operator is trivial.
  8383. static StmtResult
  8384. buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
  8385. const ExprBuilder &ToB, const ExprBuilder &FromB) {
  8386. // Compute the size of the memory buffer to be copied.
  8387. QualType SizeType = S.Context.getSizeType();
  8388. llvm::APInt Size(S.Context.getTypeSize(SizeType),
  8389. S.Context.getTypeSizeInChars(T).getQuantity());
  8390. // Take the address of the field references for "from" and "to". We
  8391. // directly construct UnaryOperators here because semantic analysis
  8392. // does not permit us to take the address of an xvalue.
  8393. Expr *From = FromB.build(S, Loc);
  8394. From = new (S.Context) UnaryOperator(From, UO_AddrOf,
  8395. S.Context.getPointerType(From->getType()),
  8396. VK_RValue, OK_Ordinary, Loc);
  8397. Expr *To = ToB.build(S, Loc);
  8398. To = new (S.Context) UnaryOperator(To, UO_AddrOf,
  8399. S.Context.getPointerType(To->getType()),
  8400. VK_RValue, OK_Ordinary, Loc);
  8401. const Type *E = T->getBaseElementTypeUnsafe();
  8402. bool NeedsCollectableMemCpy =
  8403. E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
  8404. // Create a reference to the __builtin_objc_memmove_collectable function
  8405. StringRef MemCpyName = NeedsCollectableMemCpy ?
  8406. "__builtin_objc_memmove_collectable" :
  8407. "__builtin_memcpy";
  8408. LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
  8409. Sema::LookupOrdinaryName);
  8410. S.LookupName(R, S.TUScope, true);
  8411. FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
  8412. if (!MemCpy)
  8413. // Something went horribly wrong earlier, and we will have complained
  8414. // about it.
  8415. return StmtError();
  8416. ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
  8417. VK_RValue, Loc, nullptr);
  8418. assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
  8419. Expr *CallArgs[] = {
  8420. To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
  8421. };
  8422. ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
  8423. Loc, CallArgs, Loc);
  8424. assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
  8425. return Call.getAs<Stmt>();
  8426. }
  8427. /// \brief Builds a statement that copies/moves the given entity from \p From to
  8428. /// \c To.
  8429. ///
  8430. /// This routine is used to copy/move the members of a class with an
  8431. /// implicitly-declared copy/move assignment operator. When the entities being
  8432. /// copied are arrays, this routine builds for loops to copy them.
  8433. ///
  8434. /// \param S The Sema object used for type-checking.
  8435. ///
  8436. /// \param Loc The location where the implicit copy/move is being generated.
  8437. ///
  8438. /// \param T The type of the expressions being copied/moved. Both expressions
  8439. /// must have this type.
  8440. ///
  8441. /// \param To The expression we are copying/moving to.
  8442. ///
  8443. /// \param From The expression we are copying/moving from.
  8444. ///
  8445. /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
  8446. /// Otherwise, it's a non-static member subobject.
  8447. ///
  8448. /// \param Copying Whether we're copying or moving.
  8449. ///
  8450. /// \param Depth Internal parameter recording the depth of the recursion.
  8451. ///
  8452. /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
  8453. /// if a memcpy should be used instead.
  8454. static StmtResult
  8455. buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
  8456. const ExprBuilder &To, const ExprBuilder &From,
  8457. bool CopyingBaseSubobject, bool Copying,
  8458. unsigned Depth = 0) {
  8459. // C++11 [class.copy]p28:
  8460. // Each subobject is assigned in the manner appropriate to its type:
  8461. //
  8462. // - if the subobject is of class type, as if by a call to operator= with
  8463. // the subobject as the object expression and the corresponding
  8464. // subobject of x as a single function argument (as if by explicit
  8465. // qualification; that is, ignoring any possible virtual overriding
  8466. // functions in more derived classes);
  8467. //
  8468. // C++03 [class.copy]p13:
  8469. // - if the subobject is of class type, the copy assignment operator for
  8470. // the class is used (as if by explicit qualification; that is,
  8471. // ignoring any possible virtual overriding functions in more derived
  8472. // classes);
  8473. if (const RecordType *RecordTy = T->getAs<RecordType>()) {
  8474. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
  8475. // Look for operator=.
  8476. DeclarationName Name
  8477. = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  8478. LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
  8479. S.LookupQualifiedName(OpLookup, ClassDecl, false);
  8480. // Prior to C++11, filter out any result that isn't a copy/move-assignment
  8481. // operator.
  8482. if (!S.getLangOpts().CPlusPlus11) {
  8483. LookupResult::Filter F = OpLookup.makeFilter();
  8484. while (F.hasNext()) {
  8485. NamedDecl *D = F.next();
  8486. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  8487. if (Method->isCopyAssignmentOperator() ||
  8488. (!Copying && Method->isMoveAssignmentOperator()))
  8489. continue;
  8490. F.erase();
  8491. }
  8492. F.done();
  8493. }
  8494. // Suppress the protected check (C++ [class.protected]) for each of the
  8495. // assignment operators we found. This strange dance is required when
  8496. // we're assigning via a base classes's copy-assignment operator. To
  8497. // ensure that we're getting the right base class subobject (without
  8498. // ambiguities), we need to cast "this" to that subobject type; to
  8499. // ensure that we don't go through the virtual call mechanism, we need
  8500. // to qualify the operator= name with the base class (see below). However,
  8501. // this means that if the base class has a protected copy assignment
  8502. // operator, the protected member access check will fail. So, we
  8503. // rewrite "protected" access to "public" access in this case, since we
  8504. // know by construction that we're calling from a derived class.
  8505. if (CopyingBaseSubobject) {
  8506. for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
  8507. L != LEnd; ++L) {
  8508. if (L.getAccess() == AS_protected)
  8509. L.setAccess(AS_public);
  8510. }
  8511. }
  8512. // Create the nested-name-specifier that will be used to qualify the
  8513. // reference to operator=; this is required to suppress the virtual
  8514. // call mechanism.
  8515. CXXScopeSpec SS;
  8516. const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
  8517. SS.MakeTrivial(S.Context,
  8518. NestedNameSpecifier::Create(S.Context, nullptr, false,
  8519. CanonicalT),
  8520. Loc);
  8521. // Create the reference to operator=.
  8522. ExprResult OpEqualRef
  8523. = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
  8524. SS, /*TemplateKWLoc=*/SourceLocation(),
  8525. /*FirstQualifierInScope=*/nullptr,
  8526. OpLookup,
  8527. /*TemplateArgs=*/nullptr,
  8528. /*SuppressQualifierCheck=*/true);
  8529. if (OpEqualRef.isInvalid())
  8530. return StmtError();
  8531. // Build the call to the assignment operator.
  8532. Expr *FromInst = From.build(S, Loc);
  8533. ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
  8534. OpEqualRef.getAs<Expr>(),
  8535. Loc, FromInst, Loc);
  8536. if (Call.isInvalid())
  8537. return StmtError();
  8538. // If we built a call to a trivial 'operator=' while copying an array,
  8539. // bail out. We'll replace the whole shebang with a memcpy.
  8540. CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
  8541. if (CE && CE->getMethodDecl()->isTrivial() && Depth)
  8542. return StmtResult((Stmt*)nullptr);
  8543. // Convert to an expression-statement, and clean up any produced
  8544. // temporaries.
  8545. return S.ActOnExprStmt(Call);
  8546. }
  8547. // - if the subobject is of scalar type, the built-in assignment
  8548. // operator is used.
  8549. const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
  8550. if (!ArrayTy) {
  8551. ExprResult Assignment = S.CreateBuiltinBinOp(
  8552. Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
  8553. if (Assignment.isInvalid())
  8554. return StmtError();
  8555. return S.ActOnExprStmt(Assignment);
  8556. }
  8557. // - if the subobject is an array, each element is assigned, in the
  8558. // manner appropriate to the element type;
  8559. // Construct a loop over the array bounds, e.g.,
  8560. //
  8561. // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
  8562. //
  8563. // that will copy each of the array elements.
  8564. QualType SizeType = S.Context.getSizeType();
  8565. // Create the iteration variable.
  8566. IdentifierInfo *IterationVarName = nullptr;
  8567. {
  8568. SmallString<8> Str;
  8569. llvm::raw_svector_ostream OS(Str);
  8570. OS << "__i" << Depth;
  8571. IterationVarName = &S.Context.Idents.get(OS.str());
  8572. }
  8573. VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
  8574. IterationVarName, SizeType,
  8575. S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
  8576. SC_None);
  8577. // Initialize the iteration variable to zero.
  8578. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
  8579. IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
  8580. // Creates a reference to the iteration variable.
  8581. RefBuilder IterationVarRef(IterationVar, SizeType);
  8582. LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
  8583. // Create the DeclStmt that holds the iteration variable.
  8584. Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
  8585. // Subscript the "from" and "to" expressions with the iteration variable.
  8586. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
  8587. MoveCastBuilder FromIndexMove(FromIndexCopy);
  8588. const ExprBuilder *FromIndex;
  8589. if (Copying)
  8590. FromIndex = &FromIndexCopy;
  8591. else
  8592. FromIndex = &FromIndexMove;
  8593. SubscriptBuilder ToIndex(To, IterationVarRefRVal);
  8594. // Build the copy/move for an individual element of the array.
  8595. StmtResult Copy =
  8596. buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
  8597. ToIndex, *FromIndex, CopyingBaseSubobject,
  8598. Copying, Depth + 1);
  8599. // Bail out if copying fails or if we determined that we should use memcpy.
  8600. if (Copy.isInvalid() || !Copy.get())
  8601. return Copy;
  8602. // Create the comparison against the array bound.
  8603. llvm::APInt Upper
  8604. = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
  8605. Expr *Comparison
  8606. = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
  8607. IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
  8608. BO_NE, S.Context.BoolTy,
  8609. VK_RValue, OK_Ordinary, Loc, false);
  8610. // Create the pre-increment of the iteration variable.
  8611. Expr *Increment
  8612. = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
  8613. SizeType, VK_LValue, OK_Ordinary, Loc);
  8614. // Construct the loop that copies all elements of this array.
  8615. return S.ActOnForStmt(Loc, Loc, InitStmt,
  8616. S.MakeFullExpr(Comparison),
  8617. nullptr, S.MakeFullDiscardedValueExpr(Increment),
  8618. Loc, Copy.get());
  8619. }
  8620. static StmtResult
  8621. buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
  8622. const ExprBuilder &To, const ExprBuilder &From,
  8623. bool CopyingBaseSubobject, bool Copying) {
  8624. // Maybe we should use a memcpy?
  8625. if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
  8626. T.isTriviallyCopyableType(S.Context))
  8627. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  8628. StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
  8629. CopyingBaseSubobject,
  8630. Copying, 0));
  8631. // If we ended up picking a trivial assignment operator for an array of a
  8632. // non-trivially-copyable class type, just emit a memcpy.
  8633. if (!Result.isInvalid() && !Result.get())
  8634. return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
  8635. return Result;
  8636. }
  8637. Sema::ImplicitExceptionSpecification
  8638. Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
  8639. CXXRecordDecl *ClassDecl = MD->getParent();
  8640. ImplicitExceptionSpecification ExceptSpec(*this);
  8641. if (ClassDecl->isInvalidDecl())
  8642. return ExceptSpec;
  8643. const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
  8644. assert(T->getNumParams() == 1 && "not a copy assignment op");
  8645. unsigned ArgQuals =
  8646. T->getParamType(0).getNonReferenceType().getCVRQualifiers();
  8647. // C++ [except.spec]p14:
  8648. // An implicitly declared special member function (Clause 12) shall have an
  8649. // exception-specification. [...]
  8650. // It is unspecified whether or not an implicit copy assignment operator
  8651. // attempts to deduplicate calls to assignment operators of virtual bases are
  8652. // made. As such, this exception specification is effectively unspecified.
  8653. // Based on a similar decision made for constness in C++0x, we're erring on
  8654. // the side of assuming such calls to be made regardless of whether they
  8655. // actually happen.
  8656. for (const auto &Base : ClassDecl->bases()) {
  8657. if (Base.isVirtual())
  8658. continue;
  8659. CXXRecordDecl *BaseClassDecl
  8660. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8661. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  8662. ArgQuals, false, 0))
  8663. ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
  8664. }
  8665. for (const auto &Base : ClassDecl->vbases()) {
  8666. CXXRecordDecl *BaseClassDecl
  8667. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8668. if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
  8669. ArgQuals, false, 0))
  8670. ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
  8671. }
  8672. for (const auto *Field : ClassDecl->fields()) {
  8673. QualType FieldType = Context.getBaseElementType(Field->getType());
  8674. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  8675. if (CXXMethodDecl *CopyAssign =
  8676. LookupCopyingAssignment(FieldClassDecl,
  8677. ArgQuals | FieldType.getCVRQualifiers(),
  8678. false, 0))
  8679. ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
  8680. }
  8681. }
  8682. return ExceptSpec;
  8683. }
  8684. CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
  8685. // Note: The following rules are largely analoguous to the copy
  8686. // constructor rules. Note that virtual bases are not taken into account
  8687. // for determining the argument type of the operator. Note also that
  8688. // operators taking an object instead of a reference are allowed.
  8689. assert(ClassDecl->needsImplicitCopyAssignment());
  8690. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
  8691. if (DSM.isAlreadyBeingDeclared())
  8692. return nullptr;
  8693. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  8694. QualType RetType = Context.getLValueReferenceType(ArgType);
  8695. bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
  8696. if (Const)
  8697. ArgType = ArgType.withConst();
  8698. ArgType = Context.getLValueReferenceType(ArgType);
  8699. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  8700. CXXCopyAssignment,
  8701. Const);
  8702. // An implicitly-declared copy assignment operator is an inline public
  8703. // member of its class.
  8704. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  8705. SourceLocation ClassLoc = ClassDecl->getLocation();
  8706. DeclarationNameInfo NameInfo(Name, ClassLoc);
  8707. CXXMethodDecl *CopyAssignment =
  8708. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  8709. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  8710. /*isInline=*/true, Constexpr, SourceLocation());
  8711. CopyAssignment->setAccess(AS_public);
  8712. CopyAssignment->setDefaulted();
  8713. CopyAssignment->setImplicit();
  8714. if (getLangOpts().CUDA) {
  8715. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
  8716. CopyAssignment,
  8717. /* ConstRHS */ Const,
  8718. /* Diagnose */ false);
  8719. }
  8720. // Build an exception specification pointing back at this member.
  8721. FunctionProtoType::ExtProtoInfo EPI =
  8722. getImplicitMethodEPI(*this, CopyAssignment);
  8723. CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI, None)); // HLSL Change - add param mods
  8724. // Add the parameter to the operator.
  8725. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
  8726. ClassLoc, ClassLoc,
  8727. /*Id=*/nullptr, ArgType,
  8728. /*TInfo=*/nullptr, SC_None,
  8729. nullptr);
  8730. CopyAssignment->setParams(FromParam);
  8731. AddOverriddenMethods(ClassDecl, CopyAssignment);
  8732. CopyAssignment->setTrivial(
  8733. ClassDecl->needsOverloadResolutionForCopyAssignment()
  8734. ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
  8735. : ClassDecl->hasTrivialCopyAssignment());
  8736. if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
  8737. SetDeclDeleted(CopyAssignment, ClassLoc);
  8738. // Note that we have added this copy-assignment operator.
  8739. ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  8740. if (Scope *S = getScopeForContext(ClassDecl))
  8741. PushOnScopeChains(CopyAssignment, S, false);
  8742. ClassDecl->addDecl(CopyAssignment);
  8743. return CopyAssignment;
  8744. }
  8745. /// Diagnose an implicit copy operation for a class which is odr-used, but
  8746. /// which is deprecated because the class has a user-declared copy constructor,
  8747. /// copy assignment operator, or destructor.
  8748. static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
  8749. SourceLocation UseLoc) {
  8750. assert(CopyOp->isImplicit());
  8751. CXXRecordDecl *RD = CopyOp->getParent();
  8752. CXXMethodDecl *UserDeclaredOperation = nullptr;
  8753. // In Microsoft mode, assignment operations don't affect constructors and
  8754. // vice versa.
  8755. if (RD->hasUserDeclaredDestructor()) {
  8756. UserDeclaredOperation = RD->getDestructor();
  8757. } else if (!isa<CXXConstructorDecl>(CopyOp) &&
  8758. RD->hasUserDeclaredCopyConstructor() &&
  8759. !S.getLangOpts().MSVCCompat) {
  8760. // Find any user-declared copy constructor.
  8761. for (auto *I : RD->ctors()) {
  8762. if (I->isCopyConstructor()) {
  8763. UserDeclaredOperation = I;
  8764. break;
  8765. }
  8766. }
  8767. assert(UserDeclaredOperation);
  8768. } else if (isa<CXXConstructorDecl>(CopyOp) &&
  8769. RD->hasUserDeclaredCopyAssignment() &&
  8770. !S.getLangOpts().MSVCCompat) {
  8771. // Find any user-declared move assignment operator.
  8772. for (auto *I : RD->methods()) {
  8773. if (I->isCopyAssignmentOperator()) {
  8774. UserDeclaredOperation = I;
  8775. break;
  8776. }
  8777. }
  8778. assert(UserDeclaredOperation);
  8779. }
  8780. if (UserDeclaredOperation) {
  8781. S.Diag(UserDeclaredOperation->getLocation(),
  8782. diag::warn_deprecated_copy_operation)
  8783. << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
  8784. << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
  8785. S.Diag(UseLoc, diag::note_member_synthesized_at)
  8786. << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
  8787. : Sema::CXXCopyAssignment)
  8788. << RD;
  8789. }
  8790. }
  8791. void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
  8792. CXXMethodDecl *CopyAssignOperator) {
  8793. assert((CopyAssignOperator->isDefaulted() &&
  8794. CopyAssignOperator->isOverloadedOperator() &&
  8795. CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
  8796. !CopyAssignOperator->doesThisDeclarationHaveABody() &&
  8797. !CopyAssignOperator->isDeleted()) &&
  8798. "DefineImplicitCopyAssignment called for wrong function");
  8799. CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
  8800. if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
  8801. CopyAssignOperator->setInvalidDecl();
  8802. return;
  8803. }
  8804. // C++11 [class.copy]p18:
  8805. // The [definition of an implicitly declared copy assignment operator] is
  8806. // deprecated if the class has a user-declared copy constructor or a
  8807. // user-declared destructor.
  8808. if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
  8809. diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
  8810. CopyAssignOperator->markUsed(Context);
  8811. SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
  8812. DiagnosticErrorTrap Trap(Diags);
  8813. // C++0x [class.copy]p30:
  8814. // The implicitly-defined or explicitly-defaulted copy assignment operator
  8815. // for a non-union class X performs memberwise copy assignment of its
  8816. // subobjects. The direct base classes of X are assigned first, in the
  8817. // order of their declaration in the base-specifier-list, and then the
  8818. // immediate non-static data members of X are assigned, in the order in
  8819. // which they were declared in the class definition.
  8820. // The statements that form the synthesized function body.
  8821. SmallVector<Stmt*, 8> Statements;
  8822. // The parameter for the "other" object, which we are copying from.
  8823. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
  8824. Qualifiers OtherQuals = Other->getType().getQualifiers();
  8825. QualType OtherRefType = Other->getType();
  8826. if (const LValueReferenceType *OtherRef
  8827. = OtherRefType->getAs<LValueReferenceType>()) {
  8828. OtherRefType = OtherRef->getPointeeType();
  8829. OtherQuals = OtherRefType.getQualifiers();
  8830. }
  8831. // Our location for everything implicitly-generated.
  8832. SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
  8833. ? CopyAssignOperator->getLocEnd()
  8834. : CopyAssignOperator->getLocation();
  8835. // Builds a DeclRefExpr for the "other" object.
  8836. RefBuilder OtherRef(Other, OtherRefType);
  8837. // Builds the "this" pointer.
  8838. ThisBuilder This;
  8839. // Assign base classes.
  8840. bool Invalid = false;
  8841. for (auto &Base : ClassDecl->bases()) {
  8842. // Form the assignment:
  8843. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
  8844. QualType BaseType = Base.getType().getUnqualifiedType();
  8845. if (!BaseType->isRecordType()) {
  8846. Invalid = true;
  8847. continue;
  8848. }
  8849. CXXCastPath BasePath;
  8850. BasePath.push_back(&Base);
  8851. // Construct the "from" expression, which is an implicit cast to the
  8852. // appropriately-qualified base type.
  8853. CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
  8854. VK_LValue, BasePath);
  8855. // Dereference "this".
  8856. DerefBuilder DerefThis(This);
  8857. CastBuilder To(DerefThis,
  8858. Context.getCVRQualifiedType(
  8859. BaseType, CopyAssignOperator->getTypeQualifiers()),
  8860. VK_LValue, BasePath);
  8861. // Build the copy.
  8862. StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
  8863. To, From,
  8864. /*CopyingBaseSubobject=*/true,
  8865. /*Copying=*/true);
  8866. if (Copy.isInvalid()) {
  8867. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8868. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8869. CopyAssignOperator->setInvalidDecl();
  8870. return;
  8871. }
  8872. // Success! Record the copy.
  8873. Statements.push_back(Copy.getAs<Expr>());
  8874. }
  8875. // Assign non-static members.
  8876. for (auto *Field : ClassDecl->fields()) {
  8877. // FIXME: We should form some kind of AST representation for the implied
  8878. // memcpy in a union copy operation.
  8879. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  8880. continue;
  8881. if (Field->isInvalidDecl()) {
  8882. Invalid = true;
  8883. continue;
  8884. }
  8885. // Check for members of reference type; we can't copy those.
  8886. if (Field->getType()->isReferenceType()) {
  8887. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  8888. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  8889. Diag(Field->getLocation(), diag::note_declared_at);
  8890. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8891. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8892. Invalid = true;
  8893. continue;
  8894. }
  8895. // Check for members of const-qualified, non-class type.
  8896. QualType BaseType = Context.getBaseElementType(Field->getType());
  8897. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  8898. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  8899. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  8900. Diag(Field->getLocation(), diag::note_declared_at);
  8901. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8902. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8903. Invalid = true;
  8904. continue;
  8905. }
  8906. // Suppress assigning zero-width bitfields.
  8907. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  8908. continue;
  8909. QualType FieldType = Field->getType().getNonReferenceType();
  8910. if (FieldType->isIncompleteArrayType()) {
  8911. assert(ClassDecl->hasFlexibleArrayMember() &&
  8912. "Incomplete array type is not valid");
  8913. continue;
  8914. }
  8915. // Build references to the field in the object we're copying from and to.
  8916. CXXScopeSpec SS; // Intentionally empty
  8917. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  8918. LookupMemberName);
  8919. MemberLookup.addDecl(Field);
  8920. MemberLookup.resolveKind();
  8921. MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
  8922. MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
  8923. // Build the copy of this field.
  8924. StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
  8925. To, From,
  8926. /*CopyingBaseSubobject=*/false,
  8927. /*Copying=*/true);
  8928. if (Copy.isInvalid()) {
  8929. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8930. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8931. CopyAssignOperator->setInvalidDecl();
  8932. return;
  8933. }
  8934. // Success! Record the copy.
  8935. Statements.push_back(Copy.getAs<Stmt>());
  8936. }
  8937. if (!Invalid) {
  8938. // Add a "return *this;"
  8939. ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  8940. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  8941. if (Return.isInvalid())
  8942. Invalid = true;
  8943. else {
  8944. Statements.push_back(Return.getAs<Stmt>());
  8945. if (Trap.hasErrorOccurred()) {
  8946. Diag(CurrentLocation, diag::note_member_synthesized_at)
  8947. << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
  8948. Invalid = true;
  8949. }
  8950. }
  8951. }
  8952. // The exception specification is needed because we are defining the
  8953. // function.
  8954. ResolveExceptionSpec(CurrentLocation,
  8955. CopyAssignOperator->getType()->castAs<FunctionProtoType>());
  8956. if (Invalid) {
  8957. CopyAssignOperator->setInvalidDecl();
  8958. return;
  8959. }
  8960. StmtResult Body;
  8961. {
  8962. CompoundScopeRAII CompoundScope(*this);
  8963. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  8964. /*isStmtExpr=*/false);
  8965. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  8966. }
  8967. CopyAssignOperator->setBody(Body.getAs<Stmt>());
  8968. if (ASTMutationListener *L = getASTMutationListener()) {
  8969. L->CompletedImplicitDefinition(CopyAssignOperator);
  8970. }
  8971. }
  8972. Sema::ImplicitExceptionSpecification
  8973. Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
  8974. CXXRecordDecl *ClassDecl = MD->getParent();
  8975. ImplicitExceptionSpecification ExceptSpec(*this);
  8976. if (ClassDecl->isInvalidDecl())
  8977. return ExceptSpec;
  8978. // C++0x [except.spec]p14:
  8979. // An implicitly declared special member function (Clause 12) shall have an
  8980. // exception-specification. [...]
  8981. // It is unspecified whether or not an implicit move assignment operator
  8982. // attempts to deduplicate calls to assignment operators of virtual bases are
  8983. // made. As such, this exception specification is effectively unspecified.
  8984. // Based on a similar decision made for constness in C++0x, we're erring on
  8985. // the side of assuming such calls to be made regardless of whether they
  8986. // actually happen.
  8987. // Note that a move constructor is not implicitly declared when there are
  8988. // virtual bases, but it can still be user-declared and explicitly defaulted.
  8989. for (const auto &Base : ClassDecl->bases()) {
  8990. if (Base.isVirtual())
  8991. continue;
  8992. CXXRecordDecl *BaseClassDecl
  8993. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  8994. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  8995. 0, false, 0))
  8996. ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
  8997. }
  8998. for (const auto &Base : ClassDecl->vbases()) {
  8999. CXXRecordDecl *BaseClassDecl
  9000. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9001. if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
  9002. 0, false, 0))
  9003. ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
  9004. }
  9005. for (const auto *Field : ClassDecl->fields()) {
  9006. QualType FieldType = Context.getBaseElementType(Field->getType());
  9007. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  9008. if (CXXMethodDecl *MoveAssign =
  9009. LookupMovingAssignment(FieldClassDecl,
  9010. FieldType.getCVRQualifiers(),
  9011. false, 0))
  9012. ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
  9013. }
  9014. }
  9015. return ExceptSpec;
  9016. }
  9017. CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
  9018. assert(ClassDecl->needsImplicitMoveAssignment());
  9019. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
  9020. if (DSM.isAlreadyBeingDeclared())
  9021. return nullptr;
  9022. // Note: The following rules are largely analoguous to the move
  9023. // constructor rules.
  9024. QualType ArgType = Context.getTypeDeclType(ClassDecl);
  9025. QualType RetType = Context.getLValueReferenceType(ArgType);
  9026. ArgType = Context.getRValueReferenceType(ArgType);
  9027. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9028. CXXMoveAssignment,
  9029. false);
  9030. // An implicitly-declared move assignment operator is an inline public
  9031. // member of its class.
  9032. DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  9033. SourceLocation ClassLoc = ClassDecl->getLocation();
  9034. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9035. CXXMethodDecl *MoveAssignment =
  9036. CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
  9037. /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
  9038. /*isInline=*/true, Constexpr, SourceLocation());
  9039. MoveAssignment->setAccess(AS_public);
  9040. MoveAssignment->setDefaulted();
  9041. MoveAssignment->setImplicit();
  9042. if (getLangOpts().CUDA) {
  9043. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
  9044. MoveAssignment,
  9045. /* ConstRHS */ false,
  9046. /* Diagnose */ false);
  9047. }
  9048. // Build an exception specification pointing back at this member.
  9049. FunctionProtoType::ExtProtoInfo EPI =
  9050. getImplicitMethodEPI(*this, MoveAssignment);
  9051. MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI, None)); // HLSL Change - add param mods
  9052. // Add the parameter to the operator.
  9053. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
  9054. ClassLoc, ClassLoc,
  9055. /*Id=*/nullptr, ArgType,
  9056. /*TInfo=*/nullptr, SC_None,
  9057. nullptr);
  9058. MoveAssignment->setParams(FromParam);
  9059. AddOverriddenMethods(ClassDecl, MoveAssignment);
  9060. MoveAssignment->setTrivial(
  9061. ClassDecl->needsOverloadResolutionForMoveAssignment()
  9062. ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
  9063. : ClassDecl->hasTrivialMoveAssignment());
  9064. if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
  9065. ClassDecl->setImplicitMoveAssignmentIsDeleted();
  9066. SetDeclDeleted(MoveAssignment, ClassLoc);
  9067. }
  9068. // Note that we have added this copy-assignment operator.
  9069. ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  9070. if (Scope *S = getScopeForContext(ClassDecl))
  9071. PushOnScopeChains(MoveAssignment, S, false);
  9072. ClassDecl->addDecl(MoveAssignment);
  9073. return MoveAssignment;
  9074. }
  9075. /// Check if we're implicitly defining a move assignment operator for a class
  9076. /// with virtual bases. Such a move assignment might move-assign the virtual
  9077. /// base multiple times.
  9078. static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
  9079. SourceLocation CurrentLocation) {
  9080. assert(!Class->isDependentContext() && "should not define dependent move");
  9081. // Only a virtual base could get implicitly move-assigned multiple times.
  9082. // Only a non-trivial move assignment can observe this. We only want to
  9083. // diagnose if we implicitly define an assignment operator that assigns
  9084. // two base classes, both of which move-assign the same virtual base.
  9085. if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
  9086. Class->getNumBases() < 2)
  9087. return;
  9088. llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
  9089. typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
  9090. VBaseMap VBases;
  9091. for (auto &BI : Class->bases()) {
  9092. Worklist.push_back(&BI);
  9093. while (!Worklist.empty()) {
  9094. CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
  9095. CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
  9096. // If the base has no non-trivial move assignment operators,
  9097. // we don't care about moves from it.
  9098. if (!Base->hasNonTrivialMoveAssignment())
  9099. continue;
  9100. // If there's nothing virtual here, skip it.
  9101. if (!BaseSpec->isVirtual() && !Base->getNumVBases())
  9102. continue;
  9103. // If we're not actually going to call a move assignment for this base,
  9104. // or the selected move assignment is trivial, skip it.
  9105. Sema::SpecialMemberOverloadResult *SMOR =
  9106. S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
  9107. /*ConstArg*/false, /*VolatileArg*/false,
  9108. /*RValueThis*/true, /*ConstThis*/false,
  9109. /*VolatileThis*/false);
  9110. if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
  9111. !SMOR->getMethod()->isMoveAssignmentOperator())
  9112. continue;
  9113. if (BaseSpec->isVirtual()) {
  9114. // We're going to move-assign this virtual base, and its move
  9115. // assignment operator is not trivial. If this can happen for
  9116. // multiple distinct direct bases of Class, diagnose it. (If it
  9117. // only happens in one base, we'll diagnose it when synthesizing
  9118. // that base class's move assignment operator.)
  9119. CXXBaseSpecifier *&Existing =
  9120. VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
  9121. .first->second;
  9122. if (Existing && Existing != &BI) {
  9123. S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
  9124. << Class << Base;
  9125. S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
  9126. << (Base->getCanonicalDecl() ==
  9127. Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  9128. << Base << Existing->getType() << Existing->getSourceRange();
  9129. S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
  9130. << (Base->getCanonicalDecl() ==
  9131. BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
  9132. << Base << BI.getType() << BaseSpec->getSourceRange();
  9133. // Only diagnose each vbase once.
  9134. Existing = nullptr;
  9135. }
  9136. } else {
  9137. // Only walk over bases that have defaulted move assignment operators.
  9138. // We assume that any user-provided move assignment operator handles
  9139. // the multiple-moves-of-vbase case itself somehow.
  9140. if (!SMOR->getMethod()->isDefaulted())
  9141. continue;
  9142. // We're going to move the base classes of Base. Add them to the list.
  9143. for (auto &BI : Base->bases())
  9144. Worklist.push_back(&BI);
  9145. }
  9146. }
  9147. }
  9148. }
  9149. void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
  9150. CXXMethodDecl *MoveAssignOperator) {
  9151. assert((MoveAssignOperator->isDefaulted() &&
  9152. MoveAssignOperator->isOverloadedOperator() &&
  9153. MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
  9154. !MoveAssignOperator->doesThisDeclarationHaveABody() &&
  9155. !MoveAssignOperator->isDeleted()) &&
  9156. "DefineImplicitMoveAssignment called for wrong function");
  9157. CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
  9158. if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
  9159. MoveAssignOperator->setInvalidDecl();
  9160. return;
  9161. }
  9162. MoveAssignOperator->markUsed(Context);
  9163. SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
  9164. DiagnosticErrorTrap Trap(Diags);
  9165. // C++0x [class.copy]p28:
  9166. // The implicitly-defined or move assignment operator for a non-union class
  9167. // X performs memberwise move assignment of its subobjects. The direct base
  9168. // classes of X are assigned first, in the order of their declaration in the
  9169. // base-specifier-list, and then the immediate non-static data members of X
  9170. // are assigned, in the order in which they were declared in the class
  9171. // definition.
  9172. // Issue a warning if our implicit move assignment operator will move
  9173. // from a virtual base more than once.
  9174. checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
  9175. // The statements that form the synthesized function body.
  9176. SmallVector<Stmt*, 8> Statements;
  9177. // The parameter for the "other" object, which we are move from.
  9178. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
  9179. QualType OtherRefType = Other->getType()->
  9180. getAs<RValueReferenceType>()->getPointeeType();
  9181. assert(!OtherRefType.getQualifiers() &&
  9182. "Bad argument type of defaulted move assignment");
  9183. // Our location for everything implicitly-generated.
  9184. SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
  9185. ? MoveAssignOperator->getLocEnd()
  9186. : MoveAssignOperator->getLocation();
  9187. // Builds a reference to the "other" object.
  9188. RefBuilder OtherRef(Other, OtherRefType);
  9189. // Cast to rvalue.
  9190. MoveCastBuilder MoveOther(OtherRef);
  9191. // Builds the "this" pointer.
  9192. ThisBuilder This;
  9193. // Assign base classes.
  9194. bool Invalid = false;
  9195. for (auto &Base : ClassDecl->bases()) {
  9196. // C++11 [class.copy]p28:
  9197. // It is unspecified whether subobjects representing virtual base classes
  9198. // are assigned more than once by the implicitly-defined copy assignment
  9199. // operator.
  9200. // FIXME: Do not assign to a vbase that will be assigned by some other base
  9201. // class. For a move-assignment, this can result in the vbase being moved
  9202. // multiple times.
  9203. // Form the assignment:
  9204. // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
  9205. QualType BaseType = Base.getType().getUnqualifiedType();
  9206. if (!BaseType->isRecordType()) {
  9207. Invalid = true;
  9208. continue;
  9209. }
  9210. CXXCastPath BasePath;
  9211. BasePath.push_back(&Base);
  9212. // Construct the "from" expression, which is an implicit cast to the
  9213. // appropriately-qualified base type.
  9214. CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
  9215. // Dereference "this".
  9216. DerefBuilder DerefThis(This);
  9217. // Implicitly cast "this" to the appropriately-qualified base type.
  9218. CastBuilder To(DerefThis,
  9219. Context.getCVRQualifiedType(
  9220. BaseType, MoveAssignOperator->getTypeQualifiers()),
  9221. VK_LValue, BasePath);
  9222. // Build the move.
  9223. StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
  9224. To, From,
  9225. /*CopyingBaseSubobject=*/true,
  9226. /*Copying=*/false);
  9227. if (Move.isInvalid()) {
  9228. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9229. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9230. MoveAssignOperator->setInvalidDecl();
  9231. return;
  9232. }
  9233. // Success! Record the move.
  9234. Statements.push_back(Move.getAs<Expr>());
  9235. }
  9236. // Assign non-static members.
  9237. for (auto *Field : ClassDecl->fields()) {
  9238. // FIXME: We should form some kind of AST representation for the implied
  9239. // memcpy in a union copy operation.
  9240. if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
  9241. continue;
  9242. if (Field->isInvalidDecl()) {
  9243. Invalid = true;
  9244. continue;
  9245. }
  9246. // Check for members of reference type; we can't move those.
  9247. if (Field->getType()->isReferenceType()) {
  9248. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  9249. << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
  9250. Diag(Field->getLocation(), diag::note_declared_at);
  9251. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9252. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9253. Invalid = true;
  9254. continue;
  9255. }
  9256. // Check for members of const-qualified, non-class type.
  9257. QualType BaseType = Context.getBaseElementType(Field->getType());
  9258. if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
  9259. Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
  9260. << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
  9261. Diag(Field->getLocation(), diag::note_declared_at);
  9262. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9263. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9264. Invalid = true;
  9265. continue;
  9266. }
  9267. // Suppress assigning zero-width bitfields.
  9268. if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
  9269. continue;
  9270. QualType FieldType = Field->getType().getNonReferenceType();
  9271. if (FieldType->isIncompleteArrayType()) {
  9272. assert(ClassDecl->hasFlexibleArrayMember() &&
  9273. "Incomplete array type is not valid");
  9274. continue;
  9275. }
  9276. // Build references to the field in the object we're copying from and to.
  9277. LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
  9278. LookupMemberName);
  9279. MemberLookup.addDecl(Field);
  9280. MemberLookup.resolveKind();
  9281. MemberBuilder From(MoveOther, OtherRefType,
  9282. /*IsArrow=*/false, MemberLookup);
  9283. MemberBuilder To(This, getCurrentThisType(),
  9284. /*IsArrow=*/true, MemberLookup);
  9285. assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
  9286. "Member reference with rvalue base must be rvalue except for reference "
  9287. "members, which aren't allowed for move assignment.");
  9288. // Build the move of this field.
  9289. StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
  9290. To, From,
  9291. /*CopyingBaseSubobject=*/false,
  9292. /*Copying=*/false);
  9293. if (Move.isInvalid()) {
  9294. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9295. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9296. MoveAssignOperator->setInvalidDecl();
  9297. return;
  9298. }
  9299. // Success! Record the copy.
  9300. Statements.push_back(Move.getAs<Stmt>());
  9301. }
  9302. if (!Invalid) {
  9303. // Add a "return *this;"
  9304. ExprResult ThisObj =
  9305. CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
  9306. StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
  9307. if (Return.isInvalid())
  9308. Invalid = true;
  9309. else {
  9310. Statements.push_back(Return.getAs<Stmt>());
  9311. if (Trap.hasErrorOccurred()) {
  9312. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9313. << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
  9314. Invalid = true;
  9315. }
  9316. }
  9317. }
  9318. // The exception specification is needed because we are defining the
  9319. // function.
  9320. ResolveExceptionSpec(CurrentLocation,
  9321. MoveAssignOperator->getType()->castAs<FunctionProtoType>());
  9322. if (Invalid) {
  9323. MoveAssignOperator->setInvalidDecl();
  9324. return;
  9325. }
  9326. StmtResult Body;
  9327. {
  9328. CompoundScopeRAII CompoundScope(*this);
  9329. Body = ActOnCompoundStmt(Loc, Loc, Statements,
  9330. /*isStmtExpr=*/false);
  9331. assert(!Body.isInvalid() && "Compound statement creation cannot fail");
  9332. }
  9333. MoveAssignOperator->setBody(Body.getAs<Stmt>());
  9334. if (ASTMutationListener *L = getASTMutationListener()) {
  9335. L->CompletedImplicitDefinition(MoveAssignOperator);
  9336. }
  9337. }
  9338. Sema::ImplicitExceptionSpecification
  9339. Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
  9340. CXXRecordDecl *ClassDecl = MD->getParent();
  9341. ImplicitExceptionSpecification ExceptSpec(*this);
  9342. if (ClassDecl->isInvalidDecl())
  9343. return ExceptSpec;
  9344. const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
  9345. assert(T->getNumParams() >= 1 && "not a copy ctor");
  9346. unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
  9347. // C++ [except.spec]p14:
  9348. // An implicitly declared special member function (Clause 12) shall have an
  9349. // exception-specification. [...]
  9350. for (const auto &Base : ClassDecl->bases()) {
  9351. // Virtual bases are handled below.
  9352. if (Base.isVirtual())
  9353. continue;
  9354. CXXRecordDecl *BaseClassDecl
  9355. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9356. if (CXXConstructorDecl *CopyConstructor =
  9357. LookupCopyingConstructor(BaseClassDecl, Quals))
  9358. ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
  9359. }
  9360. for (const auto &Base : ClassDecl->vbases()) {
  9361. CXXRecordDecl *BaseClassDecl
  9362. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  9363. if (CXXConstructorDecl *CopyConstructor =
  9364. LookupCopyingConstructor(BaseClassDecl, Quals))
  9365. ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
  9366. }
  9367. for (const auto *Field : ClassDecl->fields()) {
  9368. QualType FieldType = Context.getBaseElementType(Field->getType());
  9369. if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
  9370. if (CXXConstructorDecl *CopyConstructor =
  9371. LookupCopyingConstructor(FieldClassDecl,
  9372. Quals | FieldType.getCVRQualifiers()))
  9373. ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
  9374. }
  9375. }
  9376. return ExceptSpec;
  9377. }
  9378. CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
  9379. CXXRecordDecl *ClassDecl) {
  9380. // C++ [class.copy]p4:
  9381. // If the class definition does not explicitly declare a copy
  9382. // constructor, one is declared implicitly.
  9383. assert(ClassDecl->needsImplicitCopyConstructor());
  9384. DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
  9385. if (DSM.isAlreadyBeingDeclared())
  9386. return nullptr;
  9387. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  9388. QualType ArgType = ClassType;
  9389. bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
  9390. if (Const)
  9391. ArgType = ArgType.withConst();
  9392. ArgType = Context.getLValueReferenceType(ArgType);
  9393. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9394. CXXCopyConstructor,
  9395. Const);
  9396. DeclarationName Name
  9397. = Context.DeclarationNames.getCXXConstructorName(
  9398. Context.getCanonicalType(ClassType));
  9399. SourceLocation ClassLoc = ClassDecl->getLocation();
  9400. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9401. // An implicitly-declared copy constructor is an inline public
  9402. // member of its class.
  9403. CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
  9404. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  9405. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9406. Constexpr);
  9407. CopyConstructor->setAccess(AS_public);
  9408. CopyConstructor->setDefaulted();
  9409. if (getLangOpts().CUDA) {
  9410. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
  9411. CopyConstructor,
  9412. /* ConstRHS */ Const,
  9413. /* Diagnose */ false);
  9414. }
  9415. // Build an exception specification pointing back at this member.
  9416. FunctionProtoType::ExtProtoInfo EPI =
  9417. getImplicitMethodEPI(*this, CopyConstructor);
  9418. CopyConstructor->setType(
  9419. Context.getFunctionType(Context.VoidTy, ArgType, EPI, None)); // HLSL Change - add param mods
  9420. // Add the parameter to the constructor.
  9421. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
  9422. ClassLoc, ClassLoc,
  9423. /*IdentifierInfo=*/nullptr,
  9424. ArgType, /*TInfo=*/nullptr,
  9425. SC_None, nullptr);
  9426. CopyConstructor->setParams(FromParam);
  9427. CopyConstructor->setTrivial(
  9428. ClassDecl->needsOverloadResolutionForCopyConstructor()
  9429. ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
  9430. : ClassDecl->hasTrivialCopyConstructor());
  9431. if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
  9432. SetDeclDeleted(CopyConstructor, ClassLoc);
  9433. // Note that we have declared this constructor.
  9434. ++ASTContext::NumImplicitCopyConstructorsDeclared;
  9435. if (Scope *S = getScopeForContext(ClassDecl))
  9436. PushOnScopeChains(CopyConstructor, S, false);
  9437. ClassDecl->addDecl(CopyConstructor);
  9438. return CopyConstructor;
  9439. }
  9440. void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
  9441. CXXConstructorDecl *CopyConstructor) {
  9442. assert((CopyConstructor->isDefaulted() &&
  9443. CopyConstructor->isCopyConstructor() &&
  9444. !CopyConstructor->doesThisDeclarationHaveABody() &&
  9445. !CopyConstructor->isDeleted()) &&
  9446. "DefineImplicitCopyConstructor - call it for implicit copy ctor");
  9447. CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
  9448. assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
  9449. // C++11 [class.copy]p7:
  9450. // The [definition of an implicitly declared copy constructor] is
  9451. // deprecated if the class has a user-declared copy assignment operator
  9452. // or a user-declared destructor.
  9453. if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
  9454. diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
  9455. SynthesizedFunctionScope Scope(*this, CopyConstructor);
  9456. DiagnosticErrorTrap Trap(Diags);
  9457. if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
  9458. Trap.hasErrorOccurred()) {
  9459. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9460. << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
  9461. CopyConstructor->setInvalidDecl();
  9462. } else {
  9463. SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
  9464. ? CopyConstructor->getLocEnd()
  9465. : CopyConstructor->getLocation();
  9466. Sema::CompoundScopeRAII CompoundScope(*this);
  9467. CopyConstructor->setBody(
  9468. ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
  9469. }
  9470. // The exception specification is needed because we are defining the
  9471. // function.
  9472. ResolveExceptionSpec(CurrentLocation,
  9473. CopyConstructor->getType()->castAs<FunctionProtoType>());
  9474. CopyConstructor->markUsed(Context);
  9475. MarkVTableUsed(CurrentLocation, ClassDecl);
  9476. if (ASTMutationListener *L = getASTMutationListener()) {
  9477. L->CompletedImplicitDefinition(CopyConstructor);
  9478. }
  9479. }
  9480. Sema::ImplicitExceptionSpecification
  9481. Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
  9482. CXXRecordDecl *ClassDecl = MD->getParent();
  9483. // C++ [except.spec]p14:
  9484. // An implicitly declared special member function (Clause 12) shall have an
  9485. // exception-specification. [...]
  9486. ImplicitExceptionSpecification ExceptSpec(*this);
  9487. if (ClassDecl->isInvalidDecl())
  9488. return ExceptSpec;
  9489. // Direct base-class constructors.
  9490. for (const auto &B : ClassDecl->bases()) {
  9491. if (B.isVirtual()) // Handled below.
  9492. continue;
  9493. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  9494. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  9495. CXXConstructorDecl *Constructor =
  9496. LookupMovingConstructor(BaseClassDecl, 0);
  9497. // If this is a deleted function, add it anyway. This might be conformant
  9498. // with the standard. This might not. I'm not sure. It might not matter.
  9499. if (Constructor)
  9500. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  9501. }
  9502. }
  9503. // Virtual base-class constructors.
  9504. for (const auto &B : ClassDecl->vbases()) {
  9505. if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
  9506. CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  9507. CXXConstructorDecl *Constructor =
  9508. LookupMovingConstructor(BaseClassDecl, 0);
  9509. // If this is a deleted function, add it anyway. This might be conformant
  9510. // with the standard. This might not. I'm not sure. It might not matter.
  9511. if (Constructor)
  9512. ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
  9513. }
  9514. }
  9515. // Field constructors.
  9516. for (const auto *F : ClassDecl->fields()) {
  9517. QualType FieldType = Context.getBaseElementType(F->getType());
  9518. if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
  9519. CXXConstructorDecl *Constructor =
  9520. LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
  9521. // If this is a deleted function, add it anyway. This might be conformant
  9522. // with the standard. This might not. I'm not sure. It might not matter.
  9523. // In particular, the problem is that this function never gets called. It
  9524. // might just be ill-formed because this function attempts to refer to
  9525. // a deleted function here.
  9526. if (Constructor)
  9527. ExceptSpec.CalledDecl(F->getLocation(), Constructor);
  9528. }
  9529. }
  9530. return ExceptSpec;
  9531. }
  9532. CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
  9533. CXXRecordDecl *ClassDecl) {
  9534. assert(ClassDecl->needsImplicitMoveConstructor());
  9535. DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
  9536. if (DSM.isAlreadyBeingDeclared())
  9537. return nullptr;
  9538. QualType ClassType = Context.getTypeDeclType(ClassDecl);
  9539. QualType ArgType = Context.getRValueReferenceType(ClassType);
  9540. bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
  9541. CXXMoveConstructor,
  9542. false);
  9543. DeclarationName Name
  9544. = Context.DeclarationNames.getCXXConstructorName(
  9545. Context.getCanonicalType(ClassType));
  9546. SourceLocation ClassLoc = ClassDecl->getLocation();
  9547. DeclarationNameInfo NameInfo(Name, ClassLoc);
  9548. // C++11 [class.copy]p11:
  9549. // An implicitly-declared copy/move constructor is an inline public
  9550. // member of its class.
  9551. CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
  9552. Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
  9553. /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
  9554. Constexpr);
  9555. MoveConstructor->setAccess(AS_public);
  9556. MoveConstructor->setDefaulted();
  9557. if (getLangOpts().CUDA) {
  9558. inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
  9559. MoveConstructor,
  9560. /* ConstRHS */ false,
  9561. /* Diagnose */ false);
  9562. }
  9563. // Build an exception specification pointing back at this member.
  9564. FunctionProtoType::ExtProtoInfo EPI =
  9565. getImplicitMethodEPI(*this, MoveConstructor);
  9566. MoveConstructor->setType(
  9567. Context.getFunctionType(Context.VoidTy, ArgType, EPI, None)); // HLSL Change - all in-args
  9568. // Add the parameter to the constructor.
  9569. ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
  9570. ClassLoc, ClassLoc,
  9571. /*IdentifierInfo=*/nullptr,
  9572. ArgType, /*TInfo=*/nullptr,
  9573. SC_None, nullptr);
  9574. MoveConstructor->setParams(FromParam);
  9575. MoveConstructor->setTrivial(
  9576. ClassDecl->needsOverloadResolutionForMoveConstructor()
  9577. ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
  9578. : ClassDecl->hasTrivialMoveConstructor());
  9579. if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
  9580. ClassDecl->setImplicitMoveConstructorIsDeleted();
  9581. SetDeclDeleted(MoveConstructor, ClassLoc);
  9582. }
  9583. // Note that we have declared this constructor.
  9584. ++ASTContext::NumImplicitMoveConstructorsDeclared;
  9585. if (Scope *S = getScopeForContext(ClassDecl))
  9586. PushOnScopeChains(MoveConstructor, S, false);
  9587. ClassDecl->addDecl(MoveConstructor);
  9588. return MoveConstructor;
  9589. }
  9590. void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
  9591. CXXConstructorDecl *MoveConstructor) {
  9592. assert((MoveConstructor->isDefaulted() &&
  9593. MoveConstructor->isMoveConstructor() &&
  9594. !MoveConstructor->doesThisDeclarationHaveABody() &&
  9595. !MoveConstructor->isDeleted()) &&
  9596. "DefineImplicitMoveConstructor - call it for implicit move ctor");
  9597. CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
  9598. assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
  9599. SynthesizedFunctionScope Scope(*this, MoveConstructor);
  9600. DiagnosticErrorTrap Trap(Diags);
  9601. if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
  9602. Trap.hasErrorOccurred()) {
  9603. Diag(CurrentLocation, diag::note_member_synthesized_at)
  9604. << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
  9605. MoveConstructor->setInvalidDecl();
  9606. } else {
  9607. SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
  9608. ? MoveConstructor->getLocEnd()
  9609. : MoveConstructor->getLocation();
  9610. Sema::CompoundScopeRAII CompoundScope(*this);
  9611. MoveConstructor->setBody(ActOnCompoundStmt(
  9612. Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
  9613. }
  9614. // The exception specification is needed because we are defining the
  9615. // function.
  9616. ResolveExceptionSpec(CurrentLocation,
  9617. MoveConstructor->getType()->castAs<FunctionProtoType>());
  9618. MoveConstructor->markUsed(Context);
  9619. MarkVTableUsed(CurrentLocation, ClassDecl);
  9620. if (ASTMutationListener *L = getASTMutationListener()) {
  9621. L->CompletedImplicitDefinition(MoveConstructor);
  9622. }
  9623. }
  9624. bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
  9625. return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
  9626. }
  9627. void Sema::DefineImplicitLambdaToFunctionPointerConversion(
  9628. SourceLocation CurrentLocation,
  9629. CXXConversionDecl *Conv) {
  9630. CXXRecordDecl *Lambda = Conv->getParent();
  9631. CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  9632. // If we are defining a specialization of a conversion to function-ptr
  9633. // cache the deduced template arguments for this specialization
  9634. // so that we can use them to retrieve the corresponding call-operator
  9635. // and static-invoker.
  9636. const TemplateArgumentList *DeducedTemplateArgs = nullptr;
  9637. // Retrieve the corresponding call-operator specialization.
  9638. if (Lambda->isGenericLambda()) {
  9639. assert(Conv->isFunctionTemplateSpecialization());
  9640. FunctionTemplateDecl *CallOpTemplate =
  9641. CallOp->getDescribedFunctionTemplate();
  9642. DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
  9643. void *InsertPos = nullptr;
  9644. FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
  9645. DeducedTemplateArgs->asArray(),
  9646. InsertPos);
  9647. assert(CallOpSpec &&
  9648. "Conversion operator must have a corresponding call operator");
  9649. CallOp = cast<CXXMethodDecl>(CallOpSpec);
  9650. }
  9651. // Mark the call operator referenced (and add to pending instantiations
  9652. // if necessary).
  9653. // For both the conversion and static-invoker template specializations
  9654. // we construct their body's in this function, so no need to add them
  9655. // to the PendingInstantiations.
  9656. MarkFunctionReferenced(CurrentLocation, CallOp);
  9657. SynthesizedFunctionScope Scope(*this, Conv);
  9658. DiagnosticErrorTrap Trap(Diags);
  9659. // Retrieve the static invoker...
  9660. CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
  9661. // ... and get the corresponding specialization for a generic lambda.
  9662. if (Lambda->isGenericLambda()) {
  9663. assert(DeducedTemplateArgs &&
  9664. "Must have deduced template arguments from Conversion Operator");
  9665. FunctionTemplateDecl *InvokeTemplate =
  9666. Invoker->getDescribedFunctionTemplate();
  9667. void *InsertPos = nullptr;
  9668. FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
  9669. DeducedTemplateArgs->asArray(),
  9670. InsertPos);
  9671. assert(InvokeSpec &&
  9672. "Must have a corresponding static invoker specialization");
  9673. Invoker = cast<CXXMethodDecl>(InvokeSpec);
  9674. }
  9675. // Construct the body of the conversion function { return __invoke; }.
  9676. Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
  9677. VK_LValue, Conv->getLocation()).get();
  9678. assert(FunctionRef && "Can't refer to __invoke function?");
  9679. Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
  9680. Conv->setBody(new (Context) CompoundStmt(Context, Return,
  9681. Conv->getLocation(),
  9682. Conv->getLocation()));
  9683. Conv->markUsed(Context);
  9684. Conv->setReferenced();
  9685. // Fill in the __invoke function with a dummy implementation. IR generation
  9686. // will fill in the actual details.
  9687. Invoker->markUsed(Context);
  9688. Invoker->setReferenced();
  9689. Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
  9690. if (ASTMutationListener *L = getASTMutationListener()) {
  9691. L->CompletedImplicitDefinition(Conv);
  9692. L->CompletedImplicitDefinition(Invoker);
  9693. }
  9694. }
  9695. void Sema::DefineImplicitLambdaToBlockPointerConversion(
  9696. SourceLocation CurrentLocation,
  9697. CXXConversionDecl *Conv)
  9698. {
  9699. assert(!Conv->getParent()->isGenericLambda());
  9700. Conv->markUsed(Context);
  9701. SynthesizedFunctionScope Scope(*this, Conv);
  9702. DiagnosticErrorTrap Trap(Diags);
  9703. // Copy-initialize the lambda object as needed to capture it.
  9704. Expr *This = ActOnCXXThis(CurrentLocation).get();
  9705. Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
  9706. ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
  9707. Conv->getLocation(),
  9708. Conv, DerefThis);
  9709. // If we're not under ARC, make sure we still get the _Block_copy/autorelease
  9710. // behavior. Note that only the general conversion function does this
  9711. // (since it's unusable otherwise); in the case where we inline the
  9712. // block literal, it has block literal lifetime semantics.
  9713. if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
  9714. BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
  9715. CK_CopyAndAutoreleaseBlockObject,
  9716. BuildBlock.get(), nullptr, VK_RValue);
  9717. if (BuildBlock.isInvalid()) {
  9718. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  9719. Conv->setInvalidDecl();
  9720. return;
  9721. }
  9722. // Create the return statement that returns the block from the conversion
  9723. // function.
  9724. StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
  9725. if (Return.isInvalid()) {
  9726. Diag(CurrentLocation, diag::note_lambda_to_block_conv);
  9727. Conv->setInvalidDecl();
  9728. return;
  9729. }
  9730. // Set the body of the conversion function.
  9731. Stmt *ReturnS = Return.get();
  9732. Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
  9733. Conv->getLocation(),
  9734. Conv->getLocation()));
  9735. // We're done; notify the mutation listener, if any.
  9736. if (ASTMutationListener *L = getASTMutationListener()) {
  9737. L->CompletedImplicitDefinition(Conv);
  9738. }
  9739. }
  9740. /// \brief Determine whether the given list arguments contains exactly one
  9741. /// "real" (non-default) argument.
  9742. static bool hasOneRealArgument(MultiExprArg Args) {
  9743. switch (Args.size()) {
  9744. case 0:
  9745. return false;
  9746. default:
  9747. if (!Args[1]->isDefaultArgument())
  9748. return false;
  9749. // fall through
  9750. case 1:
  9751. return !Args[0]->isDefaultArgument();
  9752. }
  9753. return false;
  9754. }
  9755. ExprResult
  9756. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  9757. CXXConstructorDecl *Constructor,
  9758. MultiExprArg ExprArgs,
  9759. bool HadMultipleCandidates,
  9760. bool IsListInitialization,
  9761. bool IsStdInitListInitialization,
  9762. bool RequiresZeroInit,
  9763. unsigned ConstructKind,
  9764. SourceRange ParenRange) {
  9765. bool Elidable = false;
  9766. // C++0x [class.copy]p34:
  9767. // When certain criteria are met, an implementation is allowed to
  9768. // omit the copy/move construction of a class object, even if the
  9769. // copy/move constructor and/or destructor for the object have
  9770. // side effects. [...]
  9771. // - when a temporary class object that has not been bound to a
  9772. // reference (12.2) would be copied/moved to a class object
  9773. // with the same cv-unqualified type, the copy/move operation
  9774. // can be omitted by constructing the temporary object
  9775. // directly into the target of the omitted copy/move
  9776. if (ConstructKind == CXXConstructExpr::CK_Complete &&
  9777. Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
  9778. Expr *SubExpr = ExprArgs[0];
  9779. Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
  9780. }
  9781. return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
  9782. Elidable, ExprArgs, HadMultipleCandidates,
  9783. IsListInitialization,
  9784. IsStdInitListInitialization, RequiresZeroInit,
  9785. ConstructKind, ParenRange);
  9786. }
  9787. /// BuildCXXConstructExpr - Creates a complete call to a constructor,
  9788. /// including handling of its default argument expressions.
  9789. ExprResult
  9790. Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
  9791. CXXConstructorDecl *Constructor, bool Elidable,
  9792. MultiExprArg ExprArgs,
  9793. bool HadMultipleCandidates,
  9794. bool IsListInitialization,
  9795. bool IsStdInitListInitialization,
  9796. bool RequiresZeroInit,
  9797. unsigned ConstructKind,
  9798. SourceRange ParenRange) {
  9799. MarkFunctionReferenced(ConstructLoc, Constructor);
  9800. return CXXConstructExpr::Create(
  9801. Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
  9802. HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
  9803. RequiresZeroInit,
  9804. static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
  9805. ParenRange);
  9806. }
  9807. ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
  9808. assert(Field->hasInClassInitializer());
  9809. // If we already have the in-class initializer nothing needs to be done.
  9810. if (Field->getInClassInitializer())
  9811. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  9812. // Maybe we haven't instantiated the in-class initializer. Go check the
  9813. // pattern FieldDecl to see if it has one.
  9814. CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
  9815. if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
  9816. CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
  9817. DeclContext::lookup_result Lookup =
  9818. ClassPattern->lookup(Field->getDeclName());
  9819. assert(Lookup.size() == 1);
  9820. FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
  9821. if (InstantiateInClassInitializer(Loc, Field, Pattern,
  9822. getTemplateInstantiationArgs(Field)))
  9823. return ExprError();
  9824. return CXXDefaultInitExpr::Create(Context, Loc, Field);
  9825. }
  9826. // DR1351:
  9827. // If the brace-or-equal-initializer of a non-static data member
  9828. // invokes a defaulted default constructor of its class or of an
  9829. // enclosing class in a potentially evaluated subexpression, the
  9830. // program is ill-formed.
  9831. //
  9832. // This resolution is unworkable: the exception specification of the
  9833. // default constructor can be needed in an unevaluated context, in
  9834. // particular, in the operand of a noexcept-expression, and we can be
  9835. // unable to compute an exception specification for an enclosed class.
  9836. //
  9837. // Any attempt to resolve the exception specification of a defaulted default
  9838. // constructor before the initializer is lexically complete will ultimately
  9839. // come here at which point we can diagnose it.
  9840. RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
  9841. if (OutermostClass == ParentRD) {
  9842. Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
  9843. << ParentRD << Field;
  9844. } else {
  9845. Diag(Field->getLocEnd(),
  9846. diag::err_in_class_initializer_not_yet_parsed_outer_class)
  9847. << ParentRD << OutermostClass << Field;
  9848. }
  9849. return ExprError();
  9850. }
  9851. void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
  9852. if (VD->isInvalidDecl()) return;
  9853. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
  9854. if (ClassDecl->isInvalidDecl()) return;
  9855. if (ClassDecl->hasIrrelevantDestructor()) return;
  9856. if (ClassDecl->isDependentContext()) return;
  9857. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  9858. MarkFunctionReferenced(VD->getLocation(), Destructor);
  9859. CheckDestructorAccess(VD->getLocation(), Destructor,
  9860. PDiag(diag::err_access_dtor_var)
  9861. << VD->getDeclName()
  9862. << VD->getType());
  9863. DiagnoseUseOfDecl(Destructor, VD->getLocation());
  9864. if (Destructor->isTrivial()) return;
  9865. if (!VD->hasGlobalStorage()) return;
  9866. // Emit warning for non-trivial dtor in global scope (a real global,
  9867. // class-static, function-static).
  9868. Diag(VD->getLocation(), diag::warn_exit_time_destructor);
  9869. // TODO: this should be re-enabled for static locals by !CXAAtExit
  9870. if (!VD->isStaticLocal())
  9871. Diag(VD->getLocation(), diag::warn_global_destructor);
  9872. }
  9873. /// \brief Given a constructor and the set of arguments provided for the
  9874. /// constructor, convert the arguments and add any required default arguments
  9875. /// to form a proper call to this constructor.
  9876. ///
  9877. /// \returns true if an error occurred, false otherwise.
  9878. bool
  9879. Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
  9880. MultiExprArg ArgsPtr,
  9881. SourceLocation Loc,
  9882. SmallVectorImpl<Expr*> &ConvertedArgs,
  9883. bool AllowExplicit,
  9884. bool IsListInitialization) {
  9885. // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
  9886. unsigned NumArgs = ArgsPtr.size();
  9887. Expr **Args = ArgsPtr.data();
  9888. const FunctionProtoType *Proto
  9889. = Constructor->getType()->getAs<FunctionProtoType>();
  9890. assert(Proto && "Constructor without a prototype?");
  9891. unsigned NumParams = Proto->getNumParams();
  9892. // If too few arguments are available, we'll fill in the rest with defaults.
  9893. if (NumArgs < NumParams)
  9894. ConvertedArgs.reserve(NumParams);
  9895. else
  9896. ConvertedArgs.reserve(NumArgs);
  9897. VariadicCallType CallType =
  9898. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  9899. SmallVector<Expr *, 8> AllArgs;
  9900. bool Invalid = GatherArgumentsForCall(Loc, Constructor,
  9901. Proto, 0,
  9902. llvm::makeArrayRef(Args, NumArgs),
  9903. AllArgs,
  9904. CallType, AllowExplicit,
  9905. IsListInitialization);
  9906. ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
  9907. DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
  9908. CheckConstructorCall(Constructor,
  9909. llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
  9910. Proto, Loc);
  9911. return Invalid;
  9912. }
  9913. static inline bool
  9914. CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
  9915. const FunctionDecl *FnDecl) {
  9916. const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
  9917. if (isa<NamespaceDecl>(DC)) {
  9918. return SemaRef.Diag(FnDecl->getLocation(),
  9919. diag::err_operator_new_delete_declared_in_namespace)
  9920. << FnDecl->getDeclName();
  9921. }
  9922. if (isa<TranslationUnitDecl>(DC) &&
  9923. FnDecl->getStorageClass() == SC_Static) {
  9924. return SemaRef.Diag(FnDecl->getLocation(),
  9925. diag::err_operator_new_delete_declared_static)
  9926. << FnDecl->getDeclName();
  9927. }
  9928. return false;
  9929. }
  9930. static inline bool
  9931. CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
  9932. CanQualType ExpectedResultType,
  9933. CanQualType ExpectedFirstParamType,
  9934. unsigned DependentParamTypeDiag,
  9935. unsigned InvalidParamTypeDiag) {
  9936. QualType ResultType =
  9937. FnDecl->getType()->getAs<FunctionType>()->getReturnType();
  9938. // Check that the result type is not dependent.
  9939. if (ResultType->isDependentType())
  9940. return SemaRef.Diag(FnDecl->getLocation(),
  9941. diag::err_operator_new_delete_dependent_result_type)
  9942. << FnDecl->getDeclName() << ExpectedResultType;
  9943. // Check that the result type is what we expect.
  9944. if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
  9945. return SemaRef.Diag(FnDecl->getLocation(),
  9946. diag::err_operator_new_delete_invalid_result_type)
  9947. << FnDecl->getDeclName() << ExpectedResultType;
  9948. // A function template must have at least 2 parameters.
  9949. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
  9950. return SemaRef.Diag(FnDecl->getLocation(),
  9951. diag::err_operator_new_delete_template_too_few_parameters)
  9952. << FnDecl->getDeclName();
  9953. // The function decl must have at least 1 parameter.
  9954. if (FnDecl->getNumParams() == 0)
  9955. return SemaRef.Diag(FnDecl->getLocation(),
  9956. diag::err_operator_new_delete_too_few_parameters)
  9957. << FnDecl->getDeclName();
  9958. // Check the first parameter type is not dependent.
  9959. QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
  9960. if (FirstParamType->isDependentType())
  9961. return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
  9962. << FnDecl->getDeclName() << ExpectedFirstParamType;
  9963. // Check that the first parameter type is what we expect.
  9964. if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
  9965. ExpectedFirstParamType)
  9966. return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
  9967. << FnDecl->getDeclName() << ExpectedFirstParamType;
  9968. return false;
  9969. }
  9970. static bool
  9971. CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
  9972. // C++ [basic.stc.dynamic.allocation]p1:
  9973. // A program is ill-formed if an allocation function is declared in a
  9974. // namespace scope other than global scope or declared static in global
  9975. // scope.
  9976. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  9977. return true;
  9978. CanQualType SizeTy =
  9979. SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
  9980. // C++ [basic.stc.dynamic.allocation]p1:
  9981. // The return type shall be void*. The first parameter shall have type
  9982. // std::size_t.
  9983. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
  9984. SizeTy,
  9985. diag::err_operator_new_dependent_param_type,
  9986. diag::err_operator_new_param_type))
  9987. return true;
  9988. // C++ [basic.stc.dynamic.allocation]p1:
  9989. // The first parameter shall not have an associated default argument.
  9990. if (FnDecl->getParamDecl(0)->hasDefaultArg())
  9991. return SemaRef.Diag(FnDecl->getLocation(),
  9992. diag::err_operator_new_default_arg)
  9993. << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
  9994. return false;
  9995. }
  9996. static bool
  9997. CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
  9998. // C++ [basic.stc.dynamic.deallocation]p1:
  9999. // A program is ill-formed if deallocation functions are declared in a
  10000. // namespace scope other than global scope or declared static in global
  10001. // scope.
  10002. if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
  10003. return true;
  10004. // C++ [basic.stc.dynamic.deallocation]p2:
  10005. // Each deallocation function shall return void and its first parameter
  10006. // shall be void*.
  10007. if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
  10008. SemaRef.Context.VoidPtrTy,
  10009. diag::err_operator_delete_dependent_param_type,
  10010. diag::err_operator_delete_param_type))
  10011. return true;
  10012. return false;
  10013. }
  10014. /// CheckOverloadedOperatorDeclaration - Check whether the declaration
  10015. /// of this overloaded operator is well-formed. If so, returns false;
  10016. /// otherwise, emits appropriate diagnostics and returns true.
  10017. bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
  10018. assert(FnDecl && FnDecl->isOverloadedOperator() &&
  10019. "Expected an overloaded operator declaration");
  10020. OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
  10021. // C++ [over.oper]p5:
  10022. // The allocation and deallocation functions, operator new,
  10023. // operator new[], operator delete and operator delete[], are
  10024. // described completely in 3.7.3. The attributes and restrictions
  10025. // found in the rest of this subclause do not apply to them unless
  10026. // explicitly stated in 3.7.3.
  10027. if (Op == OO_Delete || Op == OO_Array_Delete)
  10028. return CheckOperatorDeleteDeclaration(*this, FnDecl);
  10029. if (Op == OO_New || Op == OO_Array_New)
  10030. return CheckOperatorNewDeclaration(*this, FnDecl);
  10031. // C++ [over.oper]p6:
  10032. // An operator function shall either be a non-static member
  10033. // function or be a non-member function and have at least one
  10034. // parameter whose type is a class, a reference to a class, an
  10035. // enumeration, or a reference to an enumeration.
  10036. if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
  10037. if (MethodDecl->isStatic())
  10038. return Diag(FnDecl->getLocation(),
  10039. diag::err_operator_overload_static) << FnDecl->getDeclName();
  10040. } else {
  10041. bool ClassOrEnumParam = false;
  10042. for (auto Param : FnDecl->params()) {
  10043. QualType ParamType = Param->getType().getNonReferenceType();
  10044. if (ParamType->isDependentType() || ParamType->isRecordType() ||
  10045. ParamType->isEnumeralType()) {
  10046. ClassOrEnumParam = true;
  10047. break;
  10048. }
  10049. }
  10050. if (!ClassOrEnumParam)
  10051. return Diag(FnDecl->getLocation(),
  10052. diag::err_operator_overload_needs_class_or_enum)
  10053. << FnDecl->getDeclName();
  10054. }
  10055. // C++ [over.oper]p8:
  10056. // An operator function cannot have default arguments (8.3.6),
  10057. // except where explicitly stated below.
  10058. //
  10059. // Only the function-call operator allows default arguments
  10060. // (C++ [over.call]p1).
  10061. if (Op != OO_Call) {
  10062. for (auto Param : FnDecl->params()) {
  10063. if (Param->hasDefaultArg())
  10064. return Diag(Param->getLocation(),
  10065. diag::err_operator_overload_default_arg)
  10066. << FnDecl->getDeclName() << Param->getDefaultArgRange();
  10067. }
  10068. }
  10069. static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
  10070. { false, false, false }
  10071. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  10072. , { Unary, Binary, MemberOnly }
  10073. #include "clang/Basic/OperatorKinds.def"
  10074. };
  10075. bool CanBeUnaryOperator = OperatorUses[Op][0];
  10076. bool CanBeBinaryOperator = OperatorUses[Op][1];
  10077. bool MustBeMemberOperator = OperatorUses[Op][2];
  10078. // C++ [over.oper]p8:
  10079. // [...] Operator functions cannot have more or fewer parameters
  10080. // than the number required for the corresponding operator, as
  10081. // described in the rest of this subclause.
  10082. unsigned NumParams = FnDecl->getNumParams()
  10083. + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
  10084. if (Op != OO_Call &&
  10085. ((NumParams == 1 && !CanBeUnaryOperator) ||
  10086. (NumParams == 2 && !CanBeBinaryOperator) ||
  10087. (NumParams < 1) || (NumParams > 2))) {
  10088. // We have the wrong number of parameters.
  10089. unsigned ErrorKind;
  10090. if (CanBeUnaryOperator && CanBeBinaryOperator) {
  10091. ErrorKind = 2; // 2 -> unary or binary.
  10092. } else if (CanBeUnaryOperator) {
  10093. ErrorKind = 0; // 0 -> unary
  10094. } else {
  10095. assert(CanBeBinaryOperator &&
  10096. "All non-call overloaded operators are unary or binary!");
  10097. ErrorKind = 1; // 1 -> binary
  10098. }
  10099. return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
  10100. << FnDecl->getDeclName() << NumParams << ErrorKind;
  10101. }
  10102. // Overloaded operators other than operator() cannot be variadic.
  10103. if (Op != OO_Call &&
  10104. FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
  10105. return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
  10106. << FnDecl->getDeclName();
  10107. }
  10108. // Some operators must be non-static member functions.
  10109. if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
  10110. return Diag(FnDecl->getLocation(),
  10111. diag::err_operator_overload_must_be_member)
  10112. << FnDecl->getDeclName();
  10113. }
  10114. // C++ [over.inc]p1:
  10115. // The user-defined function called operator++ implements the
  10116. // prefix and postfix ++ operator. If this function is a member
  10117. // function with no parameters, or a non-member function with one
  10118. // parameter of class or enumeration type, it defines the prefix
  10119. // increment operator ++ for objects of that type. If the function
  10120. // is a member function with one parameter (which shall be of type
  10121. // int) or a non-member function with two parameters (the second
  10122. // of which shall be of type int), it defines the postfix
  10123. // increment operator ++ for objects of that type.
  10124. if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
  10125. ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
  10126. QualType ParamType = LastParam->getType();
  10127. if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
  10128. !ParamType->isDependentType())
  10129. return Diag(LastParam->getLocation(),
  10130. diag::err_operator_overload_post_incdec_must_be_int)
  10131. << LastParam->getType() << (Op == OO_MinusMinus);
  10132. }
  10133. return false;
  10134. }
  10135. /// CheckLiteralOperatorDeclaration - Check whether the declaration
  10136. /// of this literal operator function is well-formed. If so, returns
  10137. /// false; otherwise, emits appropriate diagnostics and returns true.
  10138. bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
  10139. if (isa<CXXMethodDecl>(FnDecl)) {
  10140. Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
  10141. << FnDecl->getDeclName();
  10142. return true;
  10143. }
  10144. if (FnDecl->isExternC()) {
  10145. Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
  10146. return true;
  10147. }
  10148. bool Valid = false;
  10149. // This might be the definition of a literal operator template.
  10150. FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
  10151. // This might be a specialization of a literal operator template.
  10152. if (!TpDecl)
  10153. TpDecl = FnDecl->getPrimaryTemplate();
  10154. // template <char...> type operator "" name() and
  10155. // template <class T, T...> type operator "" name() are the only valid
  10156. // template signatures, and the only valid signatures with no parameters.
  10157. if (TpDecl) {
  10158. if (FnDecl->param_size() == 0) {
  10159. // Must have one or two template parameters
  10160. TemplateParameterList *Params = TpDecl->getTemplateParameters();
  10161. if (Params->size() == 1) {
  10162. NonTypeTemplateParmDecl *PmDecl =
  10163. dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
  10164. // The template parameter must be a char parameter pack.
  10165. if (PmDecl && PmDecl->isTemplateParameterPack() &&
  10166. Context.hasSameType(PmDecl->getType(), Context.CharTy))
  10167. Valid = true;
  10168. } else if (Params->size() == 2) {
  10169. TemplateTypeParmDecl *PmType =
  10170. dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
  10171. NonTypeTemplateParmDecl *PmArgs =
  10172. dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
  10173. // The second template parameter must be a parameter pack with the
  10174. // first template parameter as its type.
  10175. if (PmType && PmArgs &&
  10176. !PmType->isTemplateParameterPack() &&
  10177. PmArgs->isTemplateParameterPack()) {
  10178. const TemplateTypeParmType *TArgs =
  10179. PmArgs->getType()->getAs<TemplateTypeParmType>();
  10180. if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
  10181. TArgs->getIndex() == PmType->getIndex()) {
  10182. Valid = true;
  10183. if (ActiveTemplateInstantiations.empty())
  10184. Diag(FnDecl->getLocation(),
  10185. diag::ext_string_literal_operator_template);
  10186. }
  10187. }
  10188. }
  10189. }
  10190. } else if (FnDecl->param_size()) {
  10191. // Check the first parameter
  10192. FunctionDecl::param_iterator Param = FnDecl->param_begin();
  10193. QualType T = (*Param)->getType().getUnqualifiedType();
  10194. // unsigned long long int, long double, and any character type are allowed
  10195. // as the only parameters.
  10196. if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
  10197. Context.hasSameType(T, Context.LongDoubleTy) ||
  10198. Context.hasSameType(T, Context.CharTy) ||
  10199. Context.hasSameType(T, Context.WideCharTy) ||
  10200. Context.hasSameType(T, Context.Char16Ty) ||
  10201. Context.hasSameType(T, Context.Char32Ty)) {
  10202. if (++Param == FnDecl->param_end())
  10203. Valid = true;
  10204. goto FinishedParams;
  10205. }
  10206. // Otherwise it must be a pointer to const; let's strip those qualifiers.
  10207. const PointerType *PT = T->getAs<PointerType>();
  10208. if (!PT)
  10209. goto FinishedParams;
  10210. T = PT->getPointeeType();
  10211. if (!T.isConstQualified() || T.isVolatileQualified())
  10212. goto FinishedParams;
  10213. T = T.getUnqualifiedType();
  10214. // Move on to the second parameter;
  10215. ++Param;
  10216. // If there is no second parameter, the first must be a const char *
  10217. if (Param == FnDecl->param_end()) {
  10218. if (Context.hasSameType(T, Context.CharTy))
  10219. Valid = true;
  10220. goto FinishedParams;
  10221. }
  10222. // const char *, const wchar_t*, const char16_t*, and const char32_t*
  10223. // are allowed as the first parameter to a two-parameter function
  10224. if (!(Context.hasSameType(T, Context.CharTy) ||
  10225. Context.hasSameType(T, Context.WideCharTy) ||
  10226. Context.hasSameType(T, Context.Char16Ty) ||
  10227. Context.hasSameType(T, Context.Char32Ty)))
  10228. goto FinishedParams;
  10229. // The second and final parameter must be an std::size_t
  10230. T = (*Param)->getType().getUnqualifiedType();
  10231. if (Context.hasSameType(T, Context.getSizeType()) &&
  10232. ++Param == FnDecl->param_end())
  10233. Valid = true;
  10234. }
  10235. // FIXME: This diagnostic is absolutely terrible.
  10236. FinishedParams:
  10237. if (!Valid) {
  10238. Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
  10239. << FnDecl->getDeclName();
  10240. return true;
  10241. }
  10242. // A parameter-declaration-clause containing a default argument is not
  10243. // equivalent to any of the permitted forms.
  10244. for (auto Param : FnDecl->params()) {
  10245. if (Param->hasDefaultArg()) {
  10246. Diag(Param->getDefaultArgRange().getBegin(),
  10247. diag::err_literal_operator_default_argument)
  10248. << Param->getDefaultArgRange();
  10249. break;
  10250. }
  10251. }
  10252. StringRef LiteralName
  10253. = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
  10254. if (LiteralName[0] != '_') {
  10255. // C++11 [usrlit.suffix]p1:
  10256. // Literal suffix identifiers that do not start with an underscore
  10257. // are reserved for future standardization.
  10258. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
  10259. << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
  10260. }
  10261. return false;
  10262. }
  10263. /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
  10264. /// linkage specification, including the language and (if present)
  10265. /// the '{'. ExternLoc is the location of the 'extern', Lang is the
  10266. /// language string literal. LBraceLoc, if valid, provides the location of
  10267. /// the '{' brace. Otherwise, this linkage specification does not
  10268. /// have any braces.
  10269. Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
  10270. Expr *LangStr,
  10271. SourceLocation LBraceLoc) {
  10272. StringLiteral *Lit = cast<StringLiteral>(LangStr);
  10273. if (!Lit->isAscii()) {
  10274. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
  10275. << LangStr->getSourceRange();
  10276. return nullptr;
  10277. }
  10278. StringRef Lang = Lit->getString();
  10279. LinkageSpecDecl::LanguageIDs Language;
  10280. if (Lang == "C")
  10281. Language = LinkageSpecDecl::lang_c;
  10282. else if (Lang == "C++")
  10283. Language = LinkageSpecDecl::lang_cxx;
  10284. else {
  10285. Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
  10286. << LangStr->getSourceRange();
  10287. return nullptr;
  10288. }
  10289. // FIXME: Add all the various semantics of linkage specifications
  10290. LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
  10291. LangStr->getExprLoc(), Language,
  10292. LBraceLoc.isValid());
  10293. CurContext->addDecl(D);
  10294. PushDeclContext(S, D);
  10295. return D;
  10296. }
  10297. /// ActOnFinishLinkageSpecification - Complete the definition of
  10298. /// the C++ linkage specification LinkageSpec. If RBraceLoc is
  10299. /// valid, it's the position of the closing '}' brace in a linkage
  10300. /// specification that uses braces.
  10301. Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
  10302. Decl *LinkageSpec,
  10303. SourceLocation RBraceLoc) {
  10304. if (RBraceLoc.isValid()) {
  10305. LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
  10306. LSDecl->setRBraceLoc(RBraceLoc);
  10307. }
  10308. PopDeclContext();
  10309. return LinkageSpec;
  10310. }
  10311. Decl *Sema::ActOnEmptyDeclaration(Scope *S,
  10312. AttributeList *AttrList,
  10313. SourceLocation SemiLoc) {
  10314. Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
  10315. // Attribute declarations appertain to empty declaration so we handle
  10316. // them here.
  10317. if (AttrList)
  10318. ProcessDeclAttributeList(S, ED, AttrList);
  10319. CurContext->addDecl(ED);
  10320. return ED;
  10321. }
  10322. /// \brief Perform semantic analysis for the variable declaration that
  10323. /// occurs within a C++ catch clause, returning the newly-created
  10324. /// variable.
  10325. VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
  10326. TypeSourceInfo *TInfo,
  10327. SourceLocation StartLoc,
  10328. SourceLocation Loc,
  10329. IdentifierInfo *Name) {
  10330. bool Invalid = false;
  10331. QualType ExDeclType = TInfo->getType();
  10332. // Arrays and functions decay.
  10333. if (ExDeclType->isArrayType())
  10334. ExDeclType = Context.getArrayDecayedType(ExDeclType);
  10335. else if (ExDeclType->isFunctionType())
  10336. ExDeclType = Context.getPointerType(ExDeclType);
  10337. // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
  10338. // The exception-declaration shall not denote a pointer or reference to an
  10339. // incomplete type, other than [cv] void*.
  10340. // N2844 forbids rvalue references.
  10341. if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
  10342. Diag(Loc, diag::err_catch_rvalue_ref);
  10343. Invalid = true;
  10344. }
  10345. QualType BaseType = ExDeclType;
  10346. int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
  10347. unsigned DK = diag::err_catch_incomplete;
  10348. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  10349. BaseType = Ptr->getPointeeType();
  10350. Mode = 1;
  10351. DK = diag::err_catch_incomplete_ptr;
  10352. } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
  10353. // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
  10354. BaseType = Ref->getPointeeType();
  10355. Mode = 2;
  10356. DK = diag::err_catch_incomplete_ref;
  10357. }
  10358. if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
  10359. !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
  10360. Invalid = true;
  10361. if (!Invalid && !ExDeclType->isDependentType() &&
  10362. RequireNonAbstractType(Loc, ExDeclType,
  10363. diag::err_abstract_type_in_decl,
  10364. AbstractVariableType))
  10365. Invalid = true;
  10366. // Only the non-fragile NeXT runtime currently supports C++ catches
  10367. // of ObjC types, and no runtime supports catching ObjC types by value.
  10368. if (!Invalid && getLangOpts().ObjC1) {
  10369. QualType T = ExDeclType;
  10370. if (const ReferenceType *RT = T->getAs<ReferenceType>())
  10371. T = RT->getPointeeType();
  10372. if (T->isObjCObjectType()) {
  10373. Diag(Loc, diag::err_objc_object_catch);
  10374. Invalid = true;
  10375. } else if (T->isObjCObjectPointerType()) {
  10376. // FIXME: should this be a test for macosx-fragile specifically?
  10377. if (getLangOpts().ObjCRuntime.isFragile())
  10378. Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
  10379. }
  10380. }
  10381. VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
  10382. ExDeclType, TInfo, SC_None);
  10383. ExDecl->setExceptionVariable(true);
  10384. // In ARC, infer 'retaining' for variables of retainable type.
  10385. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
  10386. Invalid = true;
  10387. if (!Invalid && !ExDeclType->isDependentType()) {
  10388. if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
  10389. // Insulate this from anything else we might currently be parsing.
  10390. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  10391. // C++ [except.handle]p16:
  10392. // The object declared in an exception-declaration or, if the
  10393. // exception-declaration does not specify a name, a temporary (12.2) is
  10394. // copy-initialized (8.5) from the exception object. [...]
  10395. // The object is destroyed when the handler exits, after the destruction
  10396. // of any automatic objects initialized within the handler.
  10397. //
  10398. // We just pretend to initialize the object with itself, then make sure
  10399. // it can be destroyed later.
  10400. QualType initType = Context.getExceptionObjectType(ExDeclType);
  10401. InitializedEntity entity =
  10402. InitializedEntity::InitializeVariable(ExDecl);
  10403. InitializationKind initKind =
  10404. InitializationKind::CreateCopy(Loc, SourceLocation());
  10405. Expr *opaqueValue =
  10406. new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
  10407. InitializationSequence sequence(*this, entity, initKind, opaqueValue);
  10408. ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
  10409. if (result.isInvalid())
  10410. Invalid = true;
  10411. else {
  10412. // If the constructor used was non-trivial, set this as the
  10413. // "initializer".
  10414. CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
  10415. if (!construct->getConstructor()->isTrivial()) {
  10416. Expr *init = MaybeCreateExprWithCleanups(construct);
  10417. ExDecl->setInit(init);
  10418. }
  10419. // And make sure it's destructable.
  10420. FinalizeVarWithDestructor(ExDecl, recordType);
  10421. }
  10422. }
  10423. }
  10424. if (Invalid)
  10425. ExDecl->setInvalidDecl();
  10426. return ExDecl;
  10427. }
  10428. /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
  10429. /// handler.
  10430. Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
  10431. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10432. bool Invalid = D.isInvalidType();
  10433. // Check for unexpanded parameter packs.
  10434. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  10435. UPPC_ExceptionType)) {
  10436. TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
  10437. D.getIdentifierLoc());
  10438. Invalid = true;
  10439. }
  10440. IdentifierInfo *II = D.getIdentifier();
  10441. if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
  10442. LookupOrdinaryName,
  10443. ForRedeclaration)) {
  10444. // The scope should be freshly made just for us. There is just no way
  10445. // it contains any previous declaration, except for function parameters in
  10446. // a function-try-block's catch statement.
  10447. assert(!S->isDeclScope(PrevDecl));
  10448. if (isDeclInScope(PrevDecl, CurContext, S)) {
  10449. Diag(D.getIdentifierLoc(), diag::err_redefinition)
  10450. << D.getIdentifier();
  10451. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  10452. Invalid = true;
  10453. } else if (PrevDecl->isTemplateParameter())
  10454. // Maybe we will complain about the shadowed template parameter.
  10455. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10456. }
  10457. if (D.getCXXScopeSpec().isSet() && !Invalid) {
  10458. Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
  10459. << D.getCXXScopeSpec().getRange();
  10460. Invalid = true;
  10461. }
  10462. VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
  10463. D.getLocStart(),
  10464. D.getIdentifierLoc(),
  10465. D.getIdentifier());
  10466. if (Invalid)
  10467. ExDecl->setInvalidDecl();
  10468. // Add the exception declaration into this scope.
  10469. if (II)
  10470. PushOnScopeChains(ExDecl, S);
  10471. else
  10472. CurContext->addDecl(ExDecl);
  10473. ProcessDeclAttributes(S, ExDecl, D);
  10474. return ExDecl;
  10475. }
  10476. Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  10477. Expr *AssertExpr,
  10478. Expr *AssertMessageExpr,
  10479. SourceLocation RParenLoc) {
  10480. StringLiteral *AssertMessage =
  10481. AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
  10482. if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
  10483. return nullptr;
  10484. return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
  10485. AssertMessage, RParenLoc, false);
  10486. }
  10487. Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
  10488. Expr *AssertExpr,
  10489. StringLiteral *AssertMessage,
  10490. SourceLocation RParenLoc,
  10491. bool Failed) {
  10492. assert(AssertExpr != nullptr && "Expected non-null condition");
  10493. if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
  10494. !Failed) {
  10495. // In a static_assert-declaration, the constant-expression shall be a
  10496. // constant expression that can be contextually converted to bool.
  10497. ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
  10498. if (Converted.isInvalid())
  10499. Failed = true;
  10500. llvm::APSInt Cond;
  10501. if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
  10502. diag::err_static_assert_expression_is_not_constant,
  10503. /*AllowFold=*/false).isInvalid())
  10504. Failed = true;
  10505. if (!Failed && !Cond) {
  10506. SmallString<256> MsgBuffer;
  10507. llvm::raw_svector_ostream Msg(MsgBuffer);
  10508. if (AssertMessage)
  10509. AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
  10510. Diag(StaticAssertLoc, diag::err_static_assert_failed)
  10511. << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
  10512. Failed = true;
  10513. }
  10514. }
  10515. Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
  10516. AssertExpr, AssertMessage, RParenLoc,
  10517. Failed);
  10518. CurContext->addDecl(Decl);
  10519. return Decl;
  10520. }
  10521. /// \brief Perform semantic analysis of the given friend type declaration.
  10522. ///
  10523. /// \returns A friend declaration that.
  10524. FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
  10525. SourceLocation FriendLoc,
  10526. TypeSourceInfo *TSInfo) {
  10527. assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  10528. QualType T = TSInfo->getType();
  10529. SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
  10530. // C++03 [class.friend]p2:
  10531. // An elaborated-type-specifier shall be used in a friend declaration
  10532. // for a class.*
  10533. //
  10534. // * The class-key of the elaborated-type-specifier is required.
  10535. if (!ActiveTemplateInstantiations.empty()) {
  10536. // Do not complain about the form of friend template types during
  10537. // template instantiation; we will already have complained when the
  10538. // template was declared.
  10539. } else {
  10540. if (!T->isElaboratedTypeSpecifier()) {
  10541. // If we evaluated the type to a record type, suggest putting
  10542. // a tag in front.
  10543. if (const RecordType *RT = T->getAs<RecordType>()) {
  10544. RecordDecl *RD = RT->getDecl();
  10545. SmallString<16> InsertionText(" ");
  10546. InsertionText += RD->getKindName();
  10547. Diag(TypeRange.getBegin(),
  10548. getLangOpts().CPlusPlus11 ?
  10549. diag::warn_cxx98_compat_unelaborated_friend_type :
  10550. diag::ext_unelaborated_friend_type)
  10551. << (unsigned) RD->getTagKind()
  10552. << T
  10553. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
  10554. InsertionText);
  10555. } else {
  10556. Diag(FriendLoc,
  10557. getLangOpts().CPlusPlus11 ?
  10558. diag::warn_cxx98_compat_nonclass_type_friend :
  10559. diag::ext_nonclass_type_friend)
  10560. << T
  10561. << TypeRange;
  10562. }
  10563. } else if (T->getAs<EnumType>()) {
  10564. Diag(FriendLoc,
  10565. getLangOpts().CPlusPlus11 ?
  10566. diag::warn_cxx98_compat_enum_friend :
  10567. diag::ext_enum_friend)
  10568. << T
  10569. << TypeRange;
  10570. }
  10571. // C++11 [class.friend]p3:
  10572. // A friend declaration that does not declare a function shall have one
  10573. // of the following forms:
  10574. // friend elaborated-type-specifier ;
  10575. // friend simple-type-specifier ;
  10576. // friend typename-specifier ;
  10577. if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
  10578. Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
  10579. }
  10580. // If the type specifier in a friend declaration designates a (possibly
  10581. // cv-qualified) class type, that class is declared as a friend; otherwise,
  10582. // the friend declaration is ignored.
  10583. return FriendDecl::Create(Context, CurContext,
  10584. TSInfo->getTypeLoc().getLocStart(), TSInfo,
  10585. FriendLoc);
  10586. }
  10587. /// Handle a friend tag declaration where the scope specifier was
  10588. /// templated.
  10589. Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
  10590. unsigned TagSpec, SourceLocation TagLoc,
  10591. CXXScopeSpec &SS,
  10592. IdentifierInfo *Name,
  10593. SourceLocation NameLoc,
  10594. AttributeList *Attr,
  10595. MultiTemplateParamsArg TempParamLists) {
  10596. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  10597. bool isExplicitSpecialization = false;
  10598. bool Invalid = false;
  10599. if (TemplateParameterList *TemplateParams =
  10600. MatchTemplateParametersToScopeSpecifier(
  10601. TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
  10602. isExplicitSpecialization, Invalid)) {
  10603. if (TemplateParams->size() > 0) {
  10604. // This is a declaration of a class template.
  10605. if (Invalid)
  10606. return nullptr;
  10607. return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
  10608. NameLoc, Attr, TemplateParams, AS_public,
  10609. /*ModulePrivateLoc=*/SourceLocation(),
  10610. FriendLoc, TempParamLists.size() - 1,
  10611. TempParamLists.data()).get();
  10612. } else {
  10613. // The "template<>" header is extraneous.
  10614. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  10615. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  10616. isExplicitSpecialization = true;
  10617. }
  10618. }
  10619. if (Invalid) return nullptr;
  10620. bool isAllExplicitSpecializations = true;
  10621. for (unsigned I = TempParamLists.size(); I-- > 0; ) {
  10622. if (TempParamLists[I]->size()) {
  10623. isAllExplicitSpecializations = false;
  10624. break;
  10625. }
  10626. }
  10627. // FIXME: don't ignore attributes.
  10628. // If it's explicit specializations all the way down, just forget
  10629. // about the template header and build an appropriate non-templated
  10630. // friend. TODO: for source fidelity, remember the headers.
  10631. if (isAllExplicitSpecializations) {
  10632. if (SS.isEmpty()) {
  10633. bool Owned = false;
  10634. bool IsDependent = false;
  10635. return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
  10636. Attr, AS_public,
  10637. /*ModulePrivateLoc=*/SourceLocation(),
  10638. MultiTemplateParamsArg(), Owned, IsDependent,
  10639. /*ScopedEnumKWLoc=*/SourceLocation(),
  10640. /*ScopedEnumUsesClassTag=*/false,
  10641. /*UnderlyingType=*/TypeResult(),
  10642. /*IsTypeSpecifier=*/false);
  10643. }
  10644. NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
  10645. ElaboratedTypeKeyword Keyword
  10646. = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  10647. QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
  10648. *Name, NameLoc);
  10649. if (T.isNull())
  10650. return nullptr;
  10651. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  10652. if (isa<DependentNameType>(T)) {
  10653. DependentNameTypeLoc TL =
  10654. TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  10655. TL.setElaboratedKeywordLoc(TagLoc);
  10656. TL.setQualifierLoc(QualifierLoc);
  10657. TL.setNameLoc(NameLoc);
  10658. } else {
  10659. ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
  10660. TL.setElaboratedKeywordLoc(TagLoc);
  10661. TL.setQualifierLoc(QualifierLoc);
  10662. TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
  10663. }
  10664. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  10665. TSI, FriendLoc, TempParamLists);
  10666. Friend->setAccess(AS_public);
  10667. CurContext->addDecl(Friend);
  10668. return Friend;
  10669. }
  10670. assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
  10671. // Handle the case of a templated-scope friend class. e.g.
  10672. // template <class T> class A<T>::B;
  10673. // FIXME: we don't support these right now.
  10674. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
  10675. << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
  10676. ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
  10677. QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
  10678. TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
  10679. DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
  10680. TL.setElaboratedKeywordLoc(TagLoc);
  10681. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  10682. TL.setNameLoc(NameLoc);
  10683. FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
  10684. TSI, FriendLoc, TempParamLists);
  10685. Friend->setAccess(AS_public);
  10686. Friend->setUnsupportedFriend(true);
  10687. CurContext->addDecl(Friend);
  10688. return Friend;
  10689. }
  10690. /// Handle a friend type declaration. This works in tandem with
  10691. /// ActOnTag.
  10692. ///
  10693. /// Notes on friend class templates:
  10694. ///
  10695. /// We generally treat friend class declarations as if they were
  10696. /// declaring a class. So, for example, the elaborated type specifier
  10697. /// in a friend declaration is required to obey the restrictions of a
  10698. /// class-head (i.e. no typedefs in the scope chain), template
  10699. /// parameters are required to match up with simple template-ids, &c.
  10700. /// However, unlike when declaring a template specialization, it's
  10701. /// okay to refer to a template specialization without an empty
  10702. /// template parameter declaration, e.g.
  10703. /// friend class A<T>::B<unsigned>;
  10704. /// We permit this as a special case; if there are any template
  10705. /// parameters present at all, require proper matching, i.e.
  10706. /// template <> template \<class T> friend class A<int>::B;
  10707. Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
  10708. MultiTemplateParamsArg TempParams) {
  10709. SourceLocation Loc = DS.getLocStart();
  10710. assert(DS.isFriendSpecified());
  10711. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  10712. // Try to convert the decl specifier to a type. This works for
  10713. // friend templates because ActOnTag never produces a ClassTemplateDecl
  10714. // for a TUK_Friend.
  10715. Declarator TheDeclarator(DS, Declarator::MemberContext);
  10716. TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
  10717. QualType T = TSI->getType();
  10718. if (TheDeclarator.isInvalidType())
  10719. return nullptr;
  10720. if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
  10721. return nullptr;
  10722. // This is definitely an error in C++98. It's probably meant to
  10723. // be forbidden in C++0x, too, but the specification is just
  10724. // poorly written.
  10725. //
  10726. // The problem is with declarations like the following:
  10727. // template <T> friend A<T>::foo;
  10728. // where deciding whether a class C is a friend or not now hinges
  10729. // on whether there exists an instantiation of A that causes
  10730. // 'foo' to equal C. There are restrictions on class-heads
  10731. // (which we declare (by fiat) elaborated friend declarations to
  10732. // be) that makes this tractable.
  10733. //
  10734. // FIXME: handle "template <> friend class A<T>;", which
  10735. // is possibly well-formed? Who even knows?
  10736. if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
  10737. Diag(Loc, diag::err_tagless_friend_type_template)
  10738. << DS.getSourceRange();
  10739. return nullptr;
  10740. }
  10741. // C++98 [class.friend]p1: A friend of a class is a function
  10742. // or class that is not a member of the class . . .
  10743. // This is fixed in DR77, which just barely didn't make the C++03
  10744. // deadline. It's also a very silly restriction that seriously
  10745. // affects inner classes and which nobody else seems to implement;
  10746. // thus we never diagnose it, not even in -pedantic.
  10747. //
  10748. // But note that we could warn about it: it's always useless to
  10749. // friend one of your own members (it's not, however, worthless to
  10750. // friend a member of an arbitrary specialization of your template).
  10751. Decl *D;
  10752. if (unsigned NumTempParamLists = TempParams.size())
  10753. D = FriendTemplateDecl::Create(Context, CurContext, Loc,
  10754. NumTempParamLists,
  10755. TempParams.data(),
  10756. TSI,
  10757. DS.getFriendSpecLoc());
  10758. else
  10759. D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  10760. if (!D)
  10761. return nullptr;
  10762. D->setAccess(AS_public);
  10763. CurContext->addDecl(D);
  10764. return D;
  10765. }
  10766. NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
  10767. MultiTemplateParamsArg TemplateParams) {
  10768. const DeclSpec &DS = D.getDeclSpec();
  10769. assert(DS.isFriendSpecified());
  10770. assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
  10771. SourceLocation Loc = D.getIdentifierLoc();
  10772. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10773. // C++ [class.friend]p1
  10774. // A friend of a class is a function or class....
  10775. // Note that this sees through typedefs, which is intended.
  10776. // It *doesn't* see through dependent types, which is correct
  10777. // according to [temp.arg.type]p3:
  10778. // If a declaration acquires a function type through a
  10779. // type dependent on a template-parameter and this causes
  10780. // a declaration that does not use the syntactic form of a
  10781. // function declarator to have a function type, the program
  10782. // is ill-formed.
  10783. if (!TInfo->getType()->isFunctionType()) {
  10784. Diag(Loc, diag::err_unexpected_friend);
  10785. // It might be worthwhile to try to recover by creating an
  10786. // appropriate declaration.
  10787. return nullptr;
  10788. }
  10789. // C++ [namespace.memdef]p3
  10790. // - If a friend declaration in a non-local class first declares a
  10791. // class or function, the friend class or function is a member
  10792. // of the innermost enclosing namespace.
  10793. // - The name of the friend is not found by simple name lookup
  10794. // until a matching declaration is provided in that namespace
  10795. // scope (either before or after the class declaration granting
  10796. // friendship).
  10797. // - If a friend function is called, its name may be found by the
  10798. // name lookup that considers functions from namespaces and
  10799. // classes associated with the types of the function arguments.
  10800. // - When looking for a prior declaration of a class or a function
  10801. // declared as a friend, scopes outside the innermost enclosing
  10802. // namespace scope are not considered.
  10803. CXXScopeSpec &SS = D.getCXXScopeSpec();
  10804. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  10805. DeclarationName Name = NameInfo.getName();
  10806. assert(Name);
  10807. // Check for unexpanded parameter packs.
  10808. if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
  10809. DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
  10810. DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
  10811. return nullptr;
  10812. // The context we found the declaration in, or in which we should
  10813. // create the declaration.
  10814. DeclContext *DC;
  10815. Scope *DCScope = S;
  10816. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  10817. ForRedeclaration);
  10818. // There are five cases here.
  10819. // - There's no scope specifier and we're in a local class. Only look
  10820. // for functions declared in the immediately-enclosing block scope.
  10821. // We recover from invalid scope qualifiers as if they just weren't there.
  10822. FunctionDecl *FunctionContainingLocalClass = nullptr;
  10823. if ((SS.isInvalid() || !SS.isSet()) &&
  10824. (FunctionContainingLocalClass =
  10825. cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
  10826. // C++11 [class.friend]p11:
  10827. // If a friend declaration appears in a local class and the name
  10828. // specified is an unqualified name, a prior declaration is
  10829. // looked up without considering scopes that are outside the
  10830. // innermost enclosing non-class scope. For a friend function
  10831. // declaration, if there is no prior declaration, the program is
  10832. // ill-formed.
  10833. // Find the innermost enclosing non-class scope. This is the block
  10834. // scope containing the local class definition (or for a nested class,
  10835. // the outer local class).
  10836. DCScope = S->getFnParent();
  10837. // Look up the function name in the scope.
  10838. Previous.clear(LookupLocalFriendName);
  10839. LookupName(Previous, S, /*AllowBuiltinCreation*/false);
  10840. if (!Previous.empty()) {
  10841. // All possible previous declarations must have the same context:
  10842. // either they were declared at block scope or they are members of
  10843. // one of the enclosing local classes.
  10844. DC = Previous.getRepresentativeDecl()->getDeclContext();
  10845. } else {
  10846. // This is ill-formed, but provide the context that we would have
  10847. // declared the function in, if we were permitted to, for error recovery.
  10848. DC = FunctionContainingLocalClass;
  10849. }
  10850. adjustContextForLocalExternDecl(DC);
  10851. // C++ [class.friend]p6:
  10852. // A function can be defined in a friend declaration of a class if and
  10853. // only if the class is a non-local class (9.8), the function name is
  10854. // unqualified, and the function has namespace scope.
  10855. if (D.isFunctionDefinition()) {
  10856. Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
  10857. }
  10858. // - There's no scope specifier, in which case we just go to the
  10859. // appropriate scope and look for a function or function template
  10860. // there as appropriate.
  10861. } else if (SS.isInvalid() || !SS.isSet()) {
  10862. // C++11 [namespace.memdef]p3:
  10863. // If the name in a friend declaration is neither qualified nor
  10864. // a template-id and the declaration is a function or an
  10865. // elaborated-type-specifier, the lookup to determine whether
  10866. // the entity has been previously declared shall not consider
  10867. // any scopes outside the innermost enclosing namespace.
  10868. bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
  10869. // Find the appropriate context according to the above.
  10870. DC = CurContext;
  10871. // Skip class contexts. If someone can cite chapter and verse
  10872. // for this behavior, that would be nice --- it's what GCC and
  10873. // EDG do, and it seems like a reasonable intent, but the spec
  10874. // really only says that checks for unqualified existing
  10875. // declarations should stop at the nearest enclosing namespace,
  10876. // not that they should only consider the nearest enclosing
  10877. // namespace.
  10878. while (DC->isRecord())
  10879. DC = DC->getParent();
  10880. DeclContext *LookupDC = DC;
  10881. while (LookupDC->isTransparentContext())
  10882. LookupDC = LookupDC->getParent();
  10883. while (true) {
  10884. LookupQualifiedName(Previous, LookupDC);
  10885. if (!Previous.empty()) {
  10886. DC = LookupDC;
  10887. break;
  10888. }
  10889. if (isTemplateId) {
  10890. if (isa<TranslationUnitDecl>(LookupDC)) break;
  10891. } else {
  10892. if (LookupDC->isFileContext()) break;
  10893. }
  10894. LookupDC = LookupDC->getParent();
  10895. }
  10896. DCScope = getScopeForDeclContext(S, DC);
  10897. // - There's a non-dependent scope specifier, in which case we
  10898. // compute it and do a previous lookup there for a function
  10899. // or function template.
  10900. } else if (!SS.getScopeRep()->isDependent()) {
  10901. DC = computeDeclContext(SS);
  10902. if (!DC) return nullptr;
  10903. if (RequireCompleteDeclContext(SS, DC)) return nullptr;
  10904. LookupQualifiedName(Previous, DC);
  10905. // Ignore things found implicitly in the wrong scope.
  10906. // TODO: better diagnostics for this case. Suggesting the right
  10907. // qualified scope would be nice...
  10908. LookupResult::Filter F = Previous.makeFilter();
  10909. while (F.hasNext()) {
  10910. NamedDecl *D = F.next();
  10911. if (!DC->InEnclosingNamespaceSetOf(
  10912. D->getDeclContext()->getRedeclContext()))
  10913. F.erase();
  10914. }
  10915. F.done();
  10916. if (Previous.empty()) {
  10917. D.setInvalidType();
  10918. Diag(Loc, diag::err_qualified_friend_not_found)
  10919. << Name << TInfo->getType();
  10920. return nullptr;
  10921. }
  10922. // C++ [class.friend]p1: A friend of a class is a function or
  10923. // class that is not a member of the class . . .
  10924. if (DC->Equals(CurContext))
  10925. Diag(DS.getFriendSpecLoc(),
  10926. getLangOpts().CPlusPlus11 ?
  10927. diag::warn_cxx98_compat_friend_is_member :
  10928. diag::err_friend_is_member);
  10929. if (D.isFunctionDefinition()) {
  10930. // C++ [class.friend]p6:
  10931. // A function can be defined in a friend declaration of a class if and
  10932. // only if the class is a non-local class (9.8), the function name is
  10933. // unqualified, and the function has namespace scope.
  10934. SemaDiagnosticBuilder DB
  10935. = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
  10936. DB << SS.getScopeRep();
  10937. if (DC->isFileContext())
  10938. DB << FixItHint::CreateRemoval(SS.getRange());
  10939. SS.clear();
  10940. }
  10941. // - There's a scope specifier that does not match any template
  10942. // parameter lists, in which case we use some arbitrary context,
  10943. // create a method or method template, and wait for instantiation.
  10944. // - There's a scope specifier that does match some template
  10945. // parameter lists, which we don't handle right now.
  10946. } else {
  10947. if (D.isFunctionDefinition()) {
  10948. // C++ [class.friend]p6:
  10949. // A function can be defined in a friend declaration of a class if and
  10950. // only if the class is a non-local class (9.8), the function name is
  10951. // unqualified, and the function has namespace scope.
  10952. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
  10953. << SS.getScopeRep();
  10954. }
  10955. DC = CurContext;
  10956. assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
  10957. }
  10958. if (!DC->isRecord()) {
  10959. // This implies that it has to be an operator or function.
  10960. if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
  10961. D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
  10962. D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
  10963. Diag(Loc, diag::err_introducing_special_friend) <<
  10964. (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
  10965. D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
  10966. return nullptr;
  10967. }
  10968. }
  10969. // FIXME: This is an egregious hack to cope with cases where the scope stack
  10970. // does not contain the declaration context, i.e., in an out-of-line
  10971. // definition of a class.
  10972. Scope FakeDCScope(S, Scope::DeclScope, Diags);
  10973. if (!DCScope) {
  10974. FakeDCScope.setEntity(DC);
  10975. DCScope = &FakeDCScope;
  10976. }
  10977. bool AddToScope = true;
  10978. NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
  10979. TemplateParams, AddToScope);
  10980. if (!ND) return nullptr;
  10981. assert(ND->getLexicalDeclContext() == CurContext);
  10982. // If we performed typo correction, we might have added a scope specifier
  10983. // and changed the decl context.
  10984. DC = ND->getDeclContext();
  10985. // Add the function declaration to the appropriate lookup tables,
  10986. // adjusting the redeclarations list as necessary. We don't
  10987. // want to do this yet if the friending class is dependent.
  10988. //
  10989. // Also update the scope-based lookup if the target context's
  10990. // lookup context is in lexical scope.
  10991. if (!CurContext->isDependentContext()) {
  10992. DC = DC->getRedeclContext();
  10993. DC->makeDeclVisibleInContext(ND);
  10994. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  10995. PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
  10996. }
  10997. FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
  10998. D.getIdentifierLoc(), ND,
  10999. DS.getFriendSpecLoc());
  11000. FrD->setAccess(AS_public);
  11001. CurContext->addDecl(FrD);
  11002. if (ND->isInvalidDecl()) {
  11003. FrD->setInvalidDecl();
  11004. } else {
  11005. if (DC->isRecord()) CheckFriendAccess(ND);
  11006. FunctionDecl *FD;
  11007. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  11008. FD = FTD->getTemplatedDecl();
  11009. else
  11010. FD = cast<FunctionDecl>(ND);
  11011. // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
  11012. // default argument expression, that declaration shall be a definition
  11013. // and shall be the only declaration of the function or function
  11014. // template in the translation unit.
  11015. if (functionDeclHasDefaultArgument(FD)) {
  11016. if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
  11017. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
  11018. Diag(OldFD->getLocation(), diag::note_previous_declaration);
  11019. } else if (!D.isFunctionDefinition())
  11020. Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
  11021. }
  11022. // Mark templated-scope function declarations as unsupported.
  11023. if (FD->getNumTemplateParameterLists() && SS.isValid()) {
  11024. Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
  11025. << SS.getScopeRep() << SS.getRange()
  11026. << cast<CXXRecordDecl>(CurContext);
  11027. FrD->setUnsupportedFriend(true);
  11028. }
  11029. }
  11030. return ND;
  11031. }
  11032. void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
  11033. AdjustDeclIfTemplate(Dcl);
  11034. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
  11035. if (!Fn) {
  11036. Diag(DelLoc, diag::err_deleted_non_function);
  11037. return;
  11038. }
  11039. if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
  11040. // Don't consider the implicit declaration we generate for explicit
  11041. // specializations. FIXME: Do not generate these implicit declarations.
  11042. if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
  11043. Prev->getPreviousDecl()) &&
  11044. !Prev->isDefined()) {
  11045. Diag(DelLoc, diag::err_deleted_decl_not_first);
  11046. Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
  11047. Prev->isImplicit() ? diag::note_previous_implicit_declaration
  11048. : diag::note_previous_declaration);
  11049. }
  11050. // If the declaration wasn't the first, we delete the function anyway for
  11051. // recovery.
  11052. Fn = Fn->getCanonicalDecl();
  11053. }
  11054. // dllimport/dllexport cannot be deleted.
  11055. if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
  11056. Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
  11057. Fn->setInvalidDecl();
  11058. }
  11059. if (Fn->isDeleted())
  11060. return;
  11061. // See if we're deleting a function which is already known to override a
  11062. // non-deleted virtual function.
  11063. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
  11064. bool IssuedDiagnostic = false;
  11065. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  11066. E = MD->end_overridden_methods();
  11067. I != E; ++I) {
  11068. if (!(*MD->begin_overridden_methods())->isDeleted()) {
  11069. if (!IssuedDiagnostic) {
  11070. Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
  11071. IssuedDiagnostic = true;
  11072. }
  11073. Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  11074. }
  11075. }
  11076. }
  11077. // C++11 [basic.start.main]p3:
  11078. // A program that defines main as deleted [...] is ill-formed.
  11079. if (Fn->isMain())
  11080. Diag(DelLoc, diag::err_deleted_main);
  11081. Fn->setDeletedAsWritten();
  11082. }
  11083. void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
  11084. CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
  11085. if (MD) {
  11086. if (MD->getParent()->isDependentType()) {
  11087. MD->setDefaulted();
  11088. MD->setExplicitlyDefaulted();
  11089. return;
  11090. }
  11091. CXXSpecialMember Member = getSpecialMember(MD);
  11092. if (Member == CXXInvalid) {
  11093. if (!MD->isInvalidDecl())
  11094. Diag(DefaultLoc, diag::err_default_special_members);
  11095. return;
  11096. }
  11097. MD->setDefaulted();
  11098. MD->setExplicitlyDefaulted();
  11099. // If this definition appears within the record, do the checking when
  11100. // the record is complete.
  11101. const FunctionDecl *Primary = MD;
  11102. if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
  11103. // Find the uninstantiated declaration that actually had the '= default'
  11104. // on it.
  11105. Pattern->isDefined(Primary);
  11106. // If the method was defaulted on its first declaration, we will have
  11107. // already performed the checking in CheckCompletedCXXClass. Such a
  11108. // declaration doesn't trigger an implicit definition.
  11109. if (Primary == Primary->getCanonicalDecl())
  11110. return;
  11111. CheckExplicitlyDefaultedSpecialMember(MD);
  11112. if (MD->isInvalidDecl())
  11113. return;
  11114. switch (Member) {
  11115. case CXXDefaultConstructor:
  11116. DefineImplicitDefaultConstructor(DefaultLoc,
  11117. cast<CXXConstructorDecl>(MD));
  11118. break;
  11119. case CXXCopyConstructor:
  11120. DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  11121. break;
  11122. case CXXCopyAssignment:
  11123. DefineImplicitCopyAssignment(DefaultLoc, MD);
  11124. break;
  11125. case CXXDestructor:
  11126. DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
  11127. break;
  11128. case CXXMoveConstructor:
  11129. DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
  11130. break;
  11131. case CXXMoveAssignment:
  11132. DefineImplicitMoveAssignment(DefaultLoc, MD);
  11133. break;
  11134. case CXXInvalid:
  11135. llvm_unreachable("Invalid special member.");
  11136. }
  11137. } else {
  11138. Diag(DefaultLoc, diag::err_default_special_members);
  11139. }
  11140. }
  11141. static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
  11142. for (Stmt *SubStmt : S->children()) {
  11143. if (!SubStmt)
  11144. continue;
  11145. if (isa<ReturnStmt>(SubStmt))
  11146. Self.Diag(SubStmt->getLocStart(),
  11147. diag::err_return_in_constructor_handler);
  11148. if (!isa<Expr>(SubStmt))
  11149. SearchForReturnInStmt(Self, SubStmt);
  11150. }
  11151. }
  11152. void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
  11153. for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
  11154. CXXCatchStmt *Handler = TryBlock->getHandler(I);
  11155. SearchForReturnInStmt(*this, Handler);
  11156. }
  11157. }
  11158. bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  11159. const CXXMethodDecl *Old) {
  11160. const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
  11161. const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
  11162. CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
  11163. // If the calling conventions match, everything is fine
  11164. if (NewCC == OldCC)
  11165. return false;
  11166. // If the calling conventions mismatch because the new function is static,
  11167. // suppress the calling convention mismatch error; the error about static
  11168. // function override (err_static_overrides_virtual from
  11169. // Sema::CheckFunctionDeclaration) is more clear.
  11170. if (New->getStorageClass() == SC_Static)
  11171. return false;
  11172. Diag(New->getLocation(),
  11173. diag::err_conflicting_overriding_cc_attributes)
  11174. << New->getDeclName() << New->getType() << Old->getType();
  11175. Diag(Old->getLocation(), diag::note_overridden_virtual_function);
  11176. return true;
  11177. }
  11178. bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
  11179. const CXXMethodDecl *Old) {
  11180. QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
  11181. QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
  11182. if (Context.hasSameType(NewTy, OldTy) ||
  11183. NewTy->isDependentType() || OldTy->isDependentType())
  11184. return false;
  11185. // Check if the return types are covariant
  11186. QualType NewClassTy, OldClassTy;
  11187. /// Both types must be pointers or references to classes.
  11188. if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
  11189. if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
  11190. NewClassTy = NewPT->getPointeeType();
  11191. OldClassTy = OldPT->getPointeeType();
  11192. }
  11193. } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
  11194. if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
  11195. if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
  11196. NewClassTy = NewRT->getPointeeType();
  11197. OldClassTy = OldRT->getPointeeType();
  11198. }
  11199. }
  11200. }
  11201. // The return types aren't either both pointers or references to a class type.
  11202. if (NewClassTy.isNull()) {
  11203. Diag(New->getLocation(),
  11204. diag::err_different_return_type_for_overriding_virtual_function)
  11205. << New->getDeclName() << NewTy << OldTy
  11206. << New->getReturnTypeSourceRange();
  11207. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11208. << Old->getReturnTypeSourceRange();
  11209. return true;
  11210. }
  11211. // C++ [class.virtual]p6:
  11212. // If the return type of D::f differs from the return type of B::f, the
  11213. // class type in the return type of D::f shall be complete at the point of
  11214. // declaration of D::f or shall be the class type D.
  11215. if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
  11216. if (!RT->isBeingDefined() &&
  11217. RequireCompleteType(New->getLocation(), NewClassTy,
  11218. diag::err_covariant_return_incomplete,
  11219. New->getDeclName()))
  11220. return true;
  11221. }
  11222. if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
  11223. // Check if the new class derives from the old class.
  11224. if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
  11225. Diag(New->getLocation(), diag::err_covariant_return_not_derived)
  11226. << New->getDeclName() << NewTy << OldTy
  11227. << New->getReturnTypeSourceRange();
  11228. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11229. << Old->getReturnTypeSourceRange();
  11230. return true;
  11231. }
  11232. // Check if we the conversion from derived to base is valid.
  11233. if (CheckDerivedToBaseConversion(
  11234. NewClassTy, OldClassTy,
  11235. diag::err_covariant_return_inaccessible_base,
  11236. diag::err_covariant_return_ambiguous_derived_to_base_conv,
  11237. New->getLocation(), New->getReturnTypeSourceRange(),
  11238. New->getDeclName(), nullptr)) {
  11239. // FIXME: this note won't trigger for delayed access control
  11240. // diagnostics, and it's impossible to get an undelayed error
  11241. // here from access control during the original parse because
  11242. // the ParsingDeclSpec/ParsingDeclarator are still in scope.
  11243. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11244. << Old->getReturnTypeSourceRange();
  11245. return true;
  11246. }
  11247. }
  11248. // The qualifiers of the return types must be the same.
  11249. if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
  11250. Diag(New->getLocation(),
  11251. diag::err_covariant_return_type_different_qualifications)
  11252. << New->getDeclName() << NewTy << OldTy
  11253. << New->getReturnTypeSourceRange();
  11254. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11255. << Old->getReturnTypeSourceRange();
  11256. return true;
  11257. };
  11258. // The new class type must have the same or less qualifiers as the old type.
  11259. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
  11260. Diag(New->getLocation(),
  11261. diag::err_covariant_return_type_class_type_more_qualified)
  11262. << New->getDeclName() << NewTy << OldTy
  11263. << New->getReturnTypeSourceRange();
  11264. Diag(Old->getLocation(), diag::note_overridden_virtual_function)
  11265. << Old->getReturnTypeSourceRange();
  11266. return true;
  11267. };
  11268. return false;
  11269. }
  11270. /// \brief Mark the given method pure.
  11271. ///
  11272. /// \param Method the method to be marked pure.
  11273. ///
  11274. /// \param InitRange the source range that covers the "0" initializer.
  11275. bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
  11276. SourceLocation EndLoc = InitRange.getEnd();
  11277. if (EndLoc.isValid())
  11278. Method->setRangeEnd(EndLoc);
  11279. if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
  11280. Method->setPure();
  11281. return false;
  11282. }
  11283. if (!Method->isInvalidDecl())
  11284. Diag(Method->getLocation(), diag::err_non_virtual_pure)
  11285. << Method->getDeclName() << InitRange;
  11286. return true;
  11287. }
  11288. void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
  11289. if (D->getFriendObjectKind())
  11290. Diag(D->getLocation(), diag::err_pure_friend);
  11291. else if (auto *M = dyn_cast<CXXMethodDecl>(D))
  11292. CheckPureMethod(M, ZeroLoc);
  11293. else
  11294. Diag(D->getLocation(), diag::err_illegal_initializer);
  11295. }
  11296. /// \brief Determine whether the given declaration is a static data member.
  11297. static bool isStaticDataMember(const Decl *D) {
  11298. if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
  11299. return Var->isStaticDataMember();
  11300. return false;
  11301. }
  11302. /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
  11303. /// an initializer for the out-of-line declaration 'Dcl'. The scope
  11304. /// is a fresh scope pushed for just this purpose.
  11305. ///
  11306. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
  11307. /// static data member of class X, names should be looked up in the scope of
  11308. /// class X.
  11309. void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
  11310. // If there is no declaration, there was an error parsing it.
  11311. if (!D || D->isInvalidDecl())
  11312. return;
  11313. // We will always have a nested name specifier here, but this declaration
  11314. // might not be out of line if the specifier names the current namespace:
  11315. // extern int n;
  11316. // int ::n = 0;
  11317. if (D->isOutOfLine())
  11318. EnterDeclaratorContext(S, D->getDeclContext());
  11319. // If we are parsing the initializer for a static data member, push a
  11320. // new expression evaluation context that is associated with this static
  11321. // data member.
  11322. if (isStaticDataMember(D))
  11323. PushExpressionEvaluationContext(PotentiallyEvaluated, D);
  11324. }
  11325. /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
  11326. /// initializer for the out-of-line declaration 'D'.
  11327. void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
  11328. // If there is no declaration, there was an error parsing it.
  11329. if (!D || D->isInvalidDecl())
  11330. return;
  11331. if (isStaticDataMember(D))
  11332. PopExpressionEvaluationContext();
  11333. if (D->isOutOfLine())
  11334. ExitDeclaratorContext(S);
  11335. }
  11336. /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
  11337. /// C++ if/switch/while/for statement.
  11338. /// e.g: "if (int x = f()) {...}"
  11339. DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
  11340. // C++ 6.4p2:
  11341. // The declarator shall not specify a function or an array.
  11342. // The type-specifier-seq shall not contain typedef and shall not declare a
  11343. // new class or enumeration.
  11344. assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  11345. "Parser allowed 'typedef' as storage class of condition decl.");
  11346. Decl *Dcl = ActOnDeclarator(S, D);
  11347. if (!Dcl)
  11348. return true;
  11349. if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
  11350. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
  11351. << D.getSourceRange();
  11352. return true;
  11353. }
  11354. return Dcl;
  11355. }
  11356. void Sema::LoadExternalVTableUses() {
  11357. if (!ExternalSource)
  11358. return;
  11359. SmallVector<ExternalVTableUse, 4> VTables;
  11360. ExternalSource->ReadUsedVTables(VTables);
  11361. SmallVector<VTableUse, 4> NewUses;
  11362. for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
  11363. llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
  11364. = VTablesUsed.find(VTables[I].Record);
  11365. // Even if a definition wasn't required before, it may be required now.
  11366. if (Pos != VTablesUsed.end()) {
  11367. if (!Pos->second && VTables[I].DefinitionRequired)
  11368. Pos->second = true;
  11369. continue;
  11370. }
  11371. VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
  11372. NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
  11373. }
  11374. VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
  11375. }
  11376. void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
  11377. bool DefinitionRequired) {
  11378. // Ignore any vtable uses in unevaluated operands or for classes that do
  11379. // not have a vtable.
  11380. if (!Class->isDynamicClass() || Class->isDependentContext() ||
  11381. CurContext->isDependentContext() || isUnevaluatedContext())
  11382. return;
  11383. // Try to insert this class into the map.
  11384. LoadExternalVTableUses();
  11385. Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  11386. std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
  11387. Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
  11388. if (!Pos.second) {
  11389. // If we already had an entry, check to see if we are promoting this vtable
  11390. // to require a definition. If so, we need to reappend to the VTableUses
  11391. // list, since we may have already processed the first entry.
  11392. if (DefinitionRequired && !Pos.first->second) {
  11393. Pos.first->second = true;
  11394. } else {
  11395. // Otherwise, we can early exit.
  11396. return;
  11397. }
  11398. } else {
  11399. // The Microsoft ABI requires that we perform the destructor body
  11400. // checks (i.e. operator delete() lookup) when the vtable is marked used, as
  11401. // the deleting destructor is emitted with the vtable, not with the
  11402. // destructor definition as in the Itanium ABI.
  11403. // If it has a definition, we do the check at that point instead.
  11404. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  11405. Class->hasUserDeclaredDestructor() &&
  11406. !Class->getDestructor()->isDefined() &&
  11407. !Class->getDestructor()->isDeleted()) {
  11408. CXXDestructorDecl *DD = Class->getDestructor();
  11409. ContextRAII SavedContext(*this, DD);
  11410. CheckDestructor(DD);
  11411. }
  11412. }
  11413. // Local classes need to have their virtual members marked
  11414. // immediately. For all other classes, we mark their virtual members
  11415. // at the end of the translation unit.
  11416. if (Class->isLocalClass())
  11417. MarkVirtualMembersReferenced(Loc, Class);
  11418. else
  11419. VTableUses.push_back(std::make_pair(Class, Loc));
  11420. }
  11421. bool Sema::DefineUsedVTables() {
  11422. LoadExternalVTableUses();
  11423. if (VTableUses.empty())
  11424. return false;
  11425. // Note: The VTableUses vector could grow as a result of marking
  11426. // the members of a class as "used", so we check the size each
  11427. // time through the loop and prefer indices (which are stable) to
  11428. // iterators (which are not).
  11429. bool DefinedAnything = false;
  11430. for (unsigned I = 0; I != VTableUses.size(); ++I) {
  11431. CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
  11432. if (!Class)
  11433. continue;
  11434. SourceLocation Loc = VTableUses[I].second;
  11435. bool DefineVTable = true;
  11436. // If this class has a key function, but that key function is
  11437. // defined in another translation unit, we don't need to emit the
  11438. // vtable even though we're using it.
  11439. const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
  11440. if (KeyFunction && !KeyFunction->hasBody()) {
  11441. // The key function is in another translation unit.
  11442. DefineVTable = false;
  11443. TemplateSpecializationKind TSK =
  11444. KeyFunction->getTemplateSpecializationKind();
  11445. assert(TSK != TSK_ExplicitInstantiationDefinition &&
  11446. TSK != TSK_ImplicitInstantiation &&
  11447. "Instantiations don't have key functions");
  11448. (void)TSK;
  11449. } else if (!KeyFunction) {
  11450. // If we have a class with no key function that is the subject
  11451. // of an explicit instantiation declaration, suppress the
  11452. // vtable; it will live with the explicit instantiation
  11453. // definition.
  11454. bool IsExplicitInstantiationDeclaration
  11455. = Class->getTemplateSpecializationKind()
  11456. == TSK_ExplicitInstantiationDeclaration;
  11457. for (auto R : Class->redecls()) {
  11458. TemplateSpecializationKind TSK
  11459. = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
  11460. if (TSK == TSK_ExplicitInstantiationDeclaration)
  11461. IsExplicitInstantiationDeclaration = true;
  11462. else if (TSK == TSK_ExplicitInstantiationDefinition) {
  11463. IsExplicitInstantiationDeclaration = false;
  11464. break;
  11465. }
  11466. }
  11467. if (IsExplicitInstantiationDeclaration)
  11468. DefineVTable = false;
  11469. }
  11470. // The exception specifications for all virtual members may be needed even
  11471. // if we are not providing an authoritative form of the vtable in this TU.
  11472. // We may choose to emit it available_externally anyway.
  11473. if (!DefineVTable) {
  11474. MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
  11475. continue;
  11476. }
  11477. // Mark all of the virtual members of this class as referenced, so
  11478. // that we can build a vtable. Then, tell the AST consumer that a
  11479. // vtable for this class is required.
  11480. DefinedAnything = true;
  11481. MarkVirtualMembersReferenced(Loc, Class);
  11482. CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
  11483. if (VTablesUsed[Canonical])
  11484. Consumer.HandleVTable(Class);
  11485. // Optionally warn if we're emitting a weak vtable.
  11486. if (Class->isExternallyVisible() &&
  11487. Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
  11488. const FunctionDecl *KeyFunctionDef = nullptr;
  11489. if (!KeyFunction ||
  11490. (KeyFunction->hasBody(KeyFunctionDef) &&
  11491. KeyFunctionDef->isInlined()))
  11492. Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
  11493. TSK_ExplicitInstantiationDefinition
  11494. ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
  11495. << Class;
  11496. }
  11497. }
  11498. VTableUses.clear();
  11499. return DefinedAnything;
  11500. }
  11501. void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
  11502. const CXXRecordDecl *RD) {
  11503. for (const auto *I : RD->methods())
  11504. if (I->isVirtual() && !I->isPure())
  11505. ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
  11506. }
  11507. void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
  11508. const CXXRecordDecl *RD) {
  11509. // Mark all functions which will appear in RD's vtable as used.
  11510. CXXFinalOverriderMap FinalOverriders;
  11511. RD->getFinalOverriders(FinalOverriders);
  11512. for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
  11513. E = FinalOverriders.end();
  11514. I != E; ++I) {
  11515. for (OverridingMethods::const_iterator OI = I->second.begin(),
  11516. OE = I->second.end();
  11517. OI != OE; ++OI) {
  11518. assert(OI->second.size() > 0 && "no final overrider");
  11519. CXXMethodDecl *Overrider = OI->second.front().Method;
  11520. // C++ [basic.def.odr]p2:
  11521. // [...] A virtual member function is used if it is not pure. [...]
  11522. if (!Overrider->isPure())
  11523. MarkFunctionReferenced(Loc, Overrider);
  11524. }
  11525. }
  11526. // Only classes that have virtual bases need a VTT.
  11527. if (RD->getNumVBases() == 0)
  11528. return;
  11529. for (const auto &I : RD->bases()) {
  11530. const CXXRecordDecl *Base =
  11531. cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  11532. if (Base->getNumVBases() == 0)
  11533. continue;
  11534. MarkVirtualMembersReferenced(Loc, Base);
  11535. }
  11536. }
  11537. /// SetIvarInitializers - This routine builds initialization ASTs for the
  11538. /// Objective-C implementation whose ivars need be initialized.
  11539. void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
  11540. if (!getLangOpts().CPlusPlus)
  11541. return;
  11542. if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
  11543. SmallVector<ObjCIvarDecl*, 8> ivars;
  11544. CollectIvarsToConstructOrDestruct(OID, ivars);
  11545. if (ivars.empty())
  11546. return;
  11547. SmallVector<CXXCtorInitializer*, 32> AllToInit;
  11548. for (unsigned i = 0; i < ivars.size(); i++) {
  11549. FieldDecl *Field = ivars[i];
  11550. if (Field->isInvalidDecl())
  11551. continue;
  11552. CXXCtorInitializer *Member;
  11553. InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
  11554. InitializationKind InitKind =
  11555. InitializationKind::CreateDefault(ObjCImplementation->getLocation());
  11556. InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
  11557. ExprResult MemberInit =
  11558. InitSeq.Perform(*this, InitEntity, InitKind, None);
  11559. MemberInit = MaybeCreateExprWithCleanups(MemberInit);
  11560. // Note, MemberInit could actually come back empty if no initialization
  11561. // is required (e.g., because it would call a trivial default constructor)
  11562. if (!MemberInit.get() || MemberInit.isInvalid())
  11563. continue;
  11564. Member =
  11565. new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
  11566. SourceLocation(),
  11567. MemberInit.getAs<Expr>(),
  11568. SourceLocation());
  11569. AllToInit.push_back(Member);
  11570. // Be sure that the destructor is accessible and is marked as referenced.
  11571. if (const RecordType *RecordTy =
  11572. Context.getBaseElementType(Field->getType())
  11573. ->getAs<RecordType>()) {
  11574. CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
  11575. if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
  11576. MarkFunctionReferenced(Field->getLocation(), Destructor);
  11577. CheckDestructorAccess(Field->getLocation(), Destructor,
  11578. PDiag(diag::err_access_dtor_ivar)
  11579. << Context.getBaseElementType(Field->getType()));
  11580. }
  11581. }
  11582. }
  11583. ObjCImplementation->setIvarInitializers(Context,
  11584. AllToInit.data(), AllToInit.size());
  11585. }
  11586. }
  11587. static
  11588. void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
  11589. llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
  11590. llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
  11591. llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
  11592. Sema &S) {
  11593. if (Ctor->isInvalidDecl())
  11594. return;
  11595. CXXConstructorDecl *Target = Ctor->getTargetConstructor();
  11596. // Target may not be determinable yet, for instance if this is a dependent
  11597. // call in an uninstantiated template.
  11598. if (Target) {
  11599. const FunctionDecl *FNTarget = nullptr;
  11600. (void)Target->hasBody(FNTarget);
  11601. Target = const_cast<CXXConstructorDecl*>(
  11602. cast_or_null<CXXConstructorDecl>(FNTarget));
  11603. }
  11604. CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
  11605. // Avoid dereferencing a null pointer here.
  11606. *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
  11607. if (!Current.insert(Canonical).second)
  11608. return;
  11609. // We know that beyond here, we aren't chaining into a cycle.
  11610. if (!Target || !Target->isDelegatingConstructor() ||
  11611. Target->isInvalidDecl() || Valid.count(TCanonical)) {
  11612. Valid.insert(Current.begin(), Current.end());
  11613. Current.clear();
  11614. // We've hit a cycle.
  11615. } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
  11616. Current.count(TCanonical)) {
  11617. // If we haven't diagnosed this cycle yet, do so now.
  11618. if (!Invalid.count(TCanonical)) {
  11619. S.Diag((*Ctor->init_begin())->getSourceLocation(),
  11620. diag::warn_delegating_ctor_cycle)
  11621. << Ctor;
  11622. // Don't add a note for a function delegating directly to itself.
  11623. if (TCanonical != Canonical)
  11624. S.Diag(Target->getLocation(), diag::note_it_delegates_to);
  11625. CXXConstructorDecl *C = Target;
  11626. while (C->getCanonicalDecl() != Canonical) {
  11627. const FunctionDecl *FNTarget = nullptr;
  11628. (void)C->getTargetConstructor()->hasBody(FNTarget);
  11629. assert(FNTarget && "Ctor cycle through bodiless function");
  11630. C = const_cast<CXXConstructorDecl*>(
  11631. cast<CXXConstructorDecl>(FNTarget));
  11632. S.Diag(C->getLocation(), diag::note_which_delegates_to);
  11633. }
  11634. }
  11635. Invalid.insert(Current.begin(), Current.end());
  11636. Current.clear();
  11637. } else {
  11638. DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
  11639. }
  11640. }
  11641. void Sema::CheckDelegatingCtorCycles() {
  11642. llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
  11643. for (DelegatingCtorDeclsType::iterator
  11644. I = DelegatingCtorDecls.begin(ExternalSource),
  11645. E = DelegatingCtorDecls.end();
  11646. I != E; ++I)
  11647. DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
  11648. for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
  11649. CE = Invalid.end();
  11650. CI != CE; ++CI)
  11651. (*CI)->setInvalidDecl();
  11652. }
  11653. namespace {
  11654. /// \brief AST visitor that finds references to the 'this' expression.
  11655. class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
  11656. Sema &S;
  11657. public:
  11658. explicit FindCXXThisExpr(Sema &S) : S(S) { }
  11659. bool VisitCXXThisExpr(CXXThisExpr *E) {
  11660. S.Diag(E->getLocation(), diag::err_this_static_member_func)
  11661. << E->isImplicit();
  11662. return false;
  11663. }
  11664. };
  11665. }
  11666. bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
  11667. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  11668. if (!TSInfo)
  11669. return false;
  11670. TypeLoc TL = TSInfo->getTypeLoc();
  11671. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  11672. if (!ProtoTL)
  11673. return false;
  11674. // C++11 [expr.prim.general]p3:
  11675. // [The expression this] shall not appear before the optional
  11676. // cv-qualifier-seq and it shall not appear within the declaration of a
  11677. // static member function (although its type and value category are defined
  11678. // within a static member function as they are within a non-static member
  11679. // function). [ Note: this is because declaration matching does not occur
  11680. // until the complete declarator is known. - end note ]
  11681. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  11682. FindCXXThisExpr Finder(*this);
  11683. // If the return type came after the cv-qualifier-seq, check it now.
  11684. if (Proto->hasTrailingReturn() &&
  11685. !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
  11686. return true;
  11687. // Check the exception specification.
  11688. if (checkThisInStaticMemberFunctionExceptionSpec(Method))
  11689. return true;
  11690. return checkThisInStaticMemberFunctionAttributes(Method);
  11691. }
  11692. bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
  11693. TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
  11694. if (!TSInfo)
  11695. return false;
  11696. TypeLoc TL = TSInfo->getTypeLoc();
  11697. FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
  11698. if (!ProtoTL)
  11699. return false;
  11700. const FunctionProtoType *Proto = ProtoTL.getTypePtr();
  11701. FindCXXThisExpr Finder(*this);
  11702. switch (Proto->getExceptionSpecType()) {
  11703. case EST_Unparsed:
  11704. case EST_Uninstantiated:
  11705. case EST_Unevaluated:
  11706. case EST_BasicNoexcept:
  11707. case EST_DynamicNone:
  11708. case EST_MSAny:
  11709. case EST_None:
  11710. break;
  11711. case EST_ComputedNoexcept:
  11712. if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
  11713. return true;
  11714. case EST_Dynamic:
  11715. for (const auto &E : Proto->exceptions()) {
  11716. if (!Finder.TraverseType(E))
  11717. return true;
  11718. }
  11719. break;
  11720. }
  11721. return false;
  11722. }
  11723. bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
  11724. FindCXXThisExpr Finder(*this);
  11725. // Check attributes.
  11726. for (const auto *A : Method->attrs()) {
  11727. // FIXME: This should be emitted by tblgen.
  11728. Expr *Arg = nullptr;
  11729. ArrayRef<Expr *> Args;
  11730. if (const auto *G = dyn_cast<GuardedByAttr>(A))
  11731. Arg = G->getArg();
  11732. else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
  11733. Arg = G->getArg();
  11734. else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
  11735. Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
  11736. else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
  11737. Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
  11738. else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
  11739. Arg = ETLF->getSuccessValue();
  11740. Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
  11741. } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
  11742. Arg = STLF->getSuccessValue();
  11743. Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
  11744. } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
  11745. Arg = LR->getArg();
  11746. else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
  11747. Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
  11748. else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
  11749. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  11750. else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
  11751. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  11752. else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
  11753. Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
  11754. else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
  11755. Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
  11756. if (Arg && !Finder.TraverseStmt(Arg))
  11757. return true;
  11758. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  11759. if (!Finder.TraverseStmt(Args[I]))
  11760. return true;
  11761. }
  11762. }
  11763. return false;
  11764. }
  11765. void Sema::checkExceptionSpecification(
  11766. bool IsTopLevel, ExceptionSpecificationType EST,
  11767. ArrayRef<ParsedType> DynamicExceptions,
  11768. ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
  11769. SmallVectorImpl<QualType> &Exceptions,
  11770. FunctionProtoType::ExceptionSpecInfo &ESI) {
  11771. // HLSL Change Starts
  11772. if (LangOpts.HLSL) {
  11773. assert(DynamicExceptions.size() == 0);
  11774. assert(DynamicExceptionRanges.size() == 0);
  11775. assert(NoexceptExpr == nullptr);
  11776. assert(Exceptions.size() == 0);
  11777. return;
  11778. }
  11779. // HLSL Change Ends
  11780. Exceptions.clear();
  11781. ESI.Type = EST;
  11782. if (EST == EST_Dynamic) {
  11783. Exceptions.reserve(DynamicExceptions.size());
  11784. for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
  11785. // FIXME: Preserve type source info.
  11786. QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
  11787. if (IsTopLevel) {
  11788. SmallVector<UnexpandedParameterPack, 2> Unexpanded;
  11789. collectUnexpandedParameterPacks(ET, Unexpanded);
  11790. if (!Unexpanded.empty()) {
  11791. DiagnoseUnexpandedParameterPacks(
  11792. DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
  11793. Unexpanded);
  11794. continue;
  11795. }
  11796. }
  11797. // Check that the type is valid for an exception spec, and
  11798. // drop it if not.
  11799. if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
  11800. Exceptions.push_back(ET);
  11801. }
  11802. ESI.Exceptions = Exceptions;
  11803. return;
  11804. }
  11805. if (EST == EST_ComputedNoexcept) {
  11806. // If an error occurred, there's no expression here.
  11807. if (NoexceptExpr) {
  11808. assert((NoexceptExpr->isTypeDependent() ||
  11809. NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
  11810. Context.BoolTy) &&
  11811. "Parser should have made sure that the expression is boolean");
  11812. if (IsTopLevel && NoexceptExpr &&
  11813. DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
  11814. ESI.Type = EST_BasicNoexcept;
  11815. return;
  11816. }
  11817. if (!NoexceptExpr->isValueDependent())
  11818. NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
  11819. diag::err_noexcept_needs_constant_expression,
  11820. /*AllowFold*/ false).get();
  11821. ESI.NoexceptExpr = NoexceptExpr;
  11822. }
  11823. return;
  11824. }
  11825. }
  11826. void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
  11827. ExceptionSpecificationType EST,
  11828. SourceRange SpecificationRange,
  11829. ArrayRef<ParsedType> DynamicExceptions,
  11830. ArrayRef<SourceRange> DynamicExceptionRanges,
  11831. Expr *NoexceptExpr) {
  11832. if (!MethodD)
  11833. return;
  11834. // Dig out the method we're referring to.
  11835. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
  11836. MethodD = FunTmpl->getTemplatedDecl();
  11837. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
  11838. if (!Method)
  11839. return;
  11840. // Check the exception specification.
  11841. llvm::SmallVector<QualType, 4> Exceptions;
  11842. FunctionProtoType::ExceptionSpecInfo ESI;
  11843. checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
  11844. DynamicExceptionRanges, NoexceptExpr, Exceptions,
  11845. ESI);
  11846. // Update the exception specification on the function type.
  11847. Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
  11848. if (Method->isStatic())
  11849. checkThisInStaticMemberFunctionExceptionSpec(Method);
  11850. if (Method->isVirtual()) {
  11851. // Check overrides, which we previously had to delay.
  11852. for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
  11853. OEnd = Method->end_overridden_methods();
  11854. O != OEnd; ++O)
  11855. CheckOverridingFunctionExceptionSpec(Method, *O);
  11856. }
  11857. }
  11858. /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
  11859. ///
  11860. MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
  11861. SourceLocation DeclStart,
  11862. Declarator &D, Expr *BitWidth,
  11863. InClassInitStyle InitStyle,
  11864. AccessSpecifier AS,
  11865. AttributeList *MSPropertyAttr) {
  11866. IdentifierInfo *II = D.getIdentifier();
  11867. if (!II) {
  11868. Diag(DeclStart, diag::err_anonymous_property);
  11869. return nullptr;
  11870. }
  11871. SourceLocation Loc = D.getIdentifierLoc();
  11872. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11873. QualType T = TInfo->getType();
  11874. if (getLangOpts().CPlusPlus) {
  11875. CheckExtraCXXDefaultArguments(D);
  11876. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  11877. UPPC_DataMemberType)) {
  11878. D.setInvalidType();
  11879. T = Context.IntTy;
  11880. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  11881. }
  11882. }
  11883. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  11884. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  11885. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  11886. diag::err_invalid_thread)
  11887. << DeclSpec::getSpecifierName(TSCS);
  11888. // Check to see if this name was declared as a member previously
  11889. NamedDecl *PrevDecl = nullptr;
  11890. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  11891. LookupName(Previous, S);
  11892. switch (Previous.getResultKind()) {
  11893. case LookupResult::Found:
  11894. case LookupResult::FoundUnresolvedValue:
  11895. PrevDecl = Previous.getAsSingle<NamedDecl>();
  11896. break;
  11897. case LookupResult::FoundOverloaded:
  11898. PrevDecl = Previous.getRepresentativeDecl();
  11899. break;
  11900. case LookupResult::NotFound:
  11901. case LookupResult::NotFoundInCurrentInstantiation:
  11902. case LookupResult::Ambiguous:
  11903. break;
  11904. }
  11905. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  11906. // Maybe we will complain about the shadowed template parameter.
  11907. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11908. // Just pretend that we didn't see the previous declaration.
  11909. PrevDecl = nullptr;
  11910. }
  11911. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  11912. PrevDecl = nullptr;
  11913. SourceLocation TSSL = D.getLocStart();
  11914. const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
  11915. MSPropertyDecl *NewPD = MSPropertyDecl::Create(
  11916. Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
  11917. ProcessDeclAttributes(TUScope, NewPD, D);
  11918. NewPD->setAccess(AS);
  11919. if (NewPD->isInvalidDecl())
  11920. Record->setInvalidDecl();
  11921. if (D.getDeclSpec().isModulePrivateSpecified())
  11922. NewPD->setModulePrivate();
  11923. if (NewPD->isInvalidDecl() && PrevDecl) {
  11924. // Don't introduce NewFD into scope; there's already something
  11925. // with the same name in the same scope.
  11926. } else if (II) {
  11927. PushOnScopeChains(NewPD, S);
  11928. } else
  11929. Record->addDecl(NewPD);
  11930. return NewPD;
  11931. }