SemaDecl.cpp 509 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282
  1. //===--- SemaDecl.cpp - Semantic Analysis for 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 declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "TypeLocBuilder.h"
  15. #include "clang/AST/ASTConsumer.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTLambda.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/CommentDiagnostic.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/ExprCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  33. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  34. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  35. #include "clang/Parse/ParseDiagnostic.h"
  36. #include "clang/Sema/CXXFieldCollector.h"
  37. #include "clang/Sema/DeclSpec.h"
  38. #include "clang/Sema/DelayedDiagnostic.h"
  39. #include "clang/Sema/Initialization.h"
  40. #include "clang/Sema/Lookup.h"
  41. #include "clang/Sema/ParsedTemplate.h"
  42. #include "clang/Sema/Scope.h"
  43. #include "clang/Sema/ScopeInfo.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include <algorithm>
  48. #include <cstring>
  49. #include <functional>
  50. using namespace clang;
  51. using namespace sema;
  52. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  53. if (OwnedType) {
  54. Decl *Group[2] = { OwnedType, Ptr };
  55. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  56. }
  57. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  58. }
  59. namespace {
  60. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  61. public:
  62. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
  63. bool AllowTemplates=false)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowClassTemplates(AllowTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  73. bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
  74. return (IsType || AllowedTemplate) &&
  75. (AllowInvalidDecl || !ND->isInvalidDecl());
  76. }
  77. return !WantClassName && candidate.isKeyword();
  78. }
  79. private:
  80. bool AllowInvalidDecl;
  81. bool WantClassName;
  82. bool AllowClassTemplates;
  83. };
  84. }
  85. /// \brief Determine whether the token kind starts a simple-type-specifier.
  86. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  87. switch (Kind) {
  88. // FIXME: Take into account the current language when deciding whether a
  89. // token kind is a valid type specifier
  90. case tok::kw_short:
  91. case tok::kw_long:
  92. case tok::kw___int64:
  93. case tok::kw___int128:
  94. case tok::kw_signed:
  95. case tok::kw_unsigned:
  96. case tok::kw_void:
  97. case tok::kw_char:
  98. case tok::kw_int:
  99. case tok::kw_half:
  100. case tok::kw_float:
  101. case tok::kw_double:
  102. case tok::kw_wchar_t:
  103. case tok::kw_bool:
  104. case tok::kw___underlying_type:
  105. return true;
  106. case tok::annot_typename:
  107. case tok::kw_char16_t:
  108. case tok::kw_char32_t:
  109. case tok::kw_typeof:
  110. case tok::annot_decltype:
  111. case tok::kw_decltype:
  112. return getLangOpts().CPlusPlus;
  113. default:
  114. break;
  115. }
  116. return false;
  117. }
  118. /// \brief If the identifier refers to a type name within this scope,
  119. /// return the declaration of that type.
  120. ///
  121. /// This routine performs ordinary name lookup of the identifier II
  122. /// within the given scope, with optional C++ scope specifier SS, to
  123. /// determine whether the name refers to a type. If so, returns an
  124. /// opaque pointer (actually a QualType) corresponding to that
  125. /// type. Otherwise, returns NULL.
  126. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  127. Scope *S, CXXScopeSpec *SS,
  128. bool isClassName, bool HasTrailingDot,
  129. ParsedType ObjectTypePtr,
  130. bool IsCtorOrDtorName,
  131. bool WantNontrivialTypeSourceInfo,
  132. IdentifierInfo **CorrectedII) {
  133. // Determine where we will perform name lookup.
  134. DeclContext *LookupCtx = 0;
  135. if (ObjectTypePtr) {
  136. QualType ObjectType = ObjectTypePtr.get();
  137. if (ObjectType->isRecordType())
  138. LookupCtx = computeDeclContext(ObjectType);
  139. } else if (SS && SS->isNotEmpty()) {
  140. LookupCtx = computeDeclContext(*SS, false);
  141. if (!LookupCtx) {
  142. if (isDependentScopeSpecifier(*SS)) {
  143. // C++ [temp.res]p3:
  144. // A qualified-id that refers to a type and in which the
  145. // nested-name-specifier depends on a template-parameter (14.6.2)
  146. // shall be prefixed by the keyword typename to indicate that the
  147. // qualified-id denotes a type, forming an
  148. // elaborated-type-specifier (7.1.5.3).
  149. //
  150. // We therefore do not perform any name lookup if the result would
  151. // refer to a member of an unknown specialization.
  152. if (!isClassName && !IsCtorOrDtorName)
  153. return ParsedType();
  154. // We know from the grammar that this name refers to a type,
  155. // so build a dependent node to describe the type.
  156. if (WantNontrivialTypeSourceInfo)
  157. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  158. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  159. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  160. II, NameLoc);
  161. return ParsedType::make(T);
  162. }
  163. return ParsedType();
  164. }
  165. if (!LookupCtx->isDependentContext() &&
  166. RequireCompleteDeclContext(*SS, LookupCtx))
  167. return ParsedType();
  168. }
  169. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  170. // lookup for class-names.
  171. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  172. LookupOrdinaryName;
  173. LookupResult Result(*this, &II, NameLoc, Kind);
  174. if (LookupCtx) {
  175. // Perform "qualified" name lookup into the declaration context we
  176. // computed, which is either the type of the base of a member access
  177. // expression or the declaration context associated with a prior
  178. // nested-name-specifier.
  179. LookupQualifiedName(Result, LookupCtx);
  180. if (ObjectTypePtr && Result.empty()) {
  181. // C++ [basic.lookup.classref]p3:
  182. // If the unqualified-id is ~type-name, the type-name is looked up
  183. // in the context of the entire postfix-expression. If the type T of
  184. // the object expression is of a class type C, the type-name is also
  185. // looked up in the scope of class C. At least one of the lookups shall
  186. // find a name that refers to (possibly cv-qualified) T.
  187. LookupName(Result, S);
  188. }
  189. } else {
  190. // Perform unqualified name lookup.
  191. LookupName(Result, S);
  192. }
  193. NamedDecl *IIDecl = 0;
  194. switch (Result.getResultKind()) {
  195. case LookupResult::NotFound:
  196. case LookupResult::NotFoundInCurrentInstantiation:
  197. if (CorrectedII) {
  198. TypeNameValidatorCCC Validator(true, isClassName);
  199. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
  200. Kind, S, SS, Validator,
  201. CTK_ErrorRecovery);
  202. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  203. TemplateTy Template;
  204. bool MemberOfUnknownSpecialization;
  205. UnqualifiedId TemplateName;
  206. TemplateName.setIdentifier(NewII, NameLoc);
  207. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  208. CXXScopeSpec NewSS, *NewSSPtr = SS;
  209. if (SS && NNS) {
  210. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  211. NewSSPtr = &NewSS;
  212. }
  213. if (Correction && (NNS || NewII != &II) &&
  214. // Ignore a correction to a template type as the to-be-corrected
  215. // identifier is not a template (typo correction for template names
  216. // is handled elsewhere).
  217. !(getLangOpts().CPlusPlus && NewSSPtr &&
  218. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  219. false, Template, MemberOfUnknownSpecialization))) {
  220. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  221. isClassName, HasTrailingDot, ObjectTypePtr,
  222. IsCtorOrDtorName,
  223. WantNontrivialTypeSourceInfo);
  224. if (Ty) {
  225. diagnoseTypo(Correction,
  226. PDiag(diag::err_unknown_type_or_class_name_suggest)
  227. << Result.getLookupName() << isClassName);
  228. if (SS && NNS)
  229. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  230. *CorrectedII = NewII;
  231. return Ty;
  232. }
  233. }
  234. }
  235. // If typo correction failed or was not performed, fall through
  236. case LookupResult::FoundOverloaded:
  237. case LookupResult::FoundUnresolvedValue:
  238. Result.suppressDiagnostics();
  239. return ParsedType();
  240. case LookupResult::Ambiguous:
  241. // Recover from type-hiding ambiguities by hiding the type. We'll
  242. // do the lookup again when looking for an object, and we can
  243. // diagnose the error then. If we don't do this, then the error
  244. // about hiding the type will be immediately followed by an error
  245. // that only makes sense if the identifier was treated like a type.
  246. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  247. Result.suppressDiagnostics();
  248. return ParsedType();
  249. }
  250. // Look to see if we have a type anywhere in the list of results.
  251. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  252. Res != ResEnd; ++Res) {
  253. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  254. if (!IIDecl ||
  255. (*Res)->getLocation().getRawEncoding() <
  256. IIDecl->getLocation().getRawEncoding())
  257. IIDecl = *Res;
  258. }
  259. }
  260. if (!IIDecl) {
  261. // None of the entities we found is a type, so there is no way
  262. // to even assume that the result is a type. In this case, don't
  263. // complain about the ambiguity. The parser will either try to
  264. // perform this lookup again (e.g., as an object name), which
  265. // will produce the ambiguity, or will complain that it expected
  266. // a type name.
  267. Result.suppressDiagnostics();
  268. return ParsedType();
  269. }
  270. // We found a type within the ambiguous lookup; diagnose the
  271. // ambiguity and then return that type. This might be the right
  272. // answer, or it might not be, but it suppresses any attempt to
  273. // perform the name lookup again.
  274. break;
  275. case LookupResult::Found:
  276. IIDecl = Result.getFoundDecl();
  277. break;
  278. }
  279. assert(IIDecl && "Didn't find decl");
  280. QualType T;
  281. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  282. DiagnoseUseOfDecl(IIDecl, NameLoc);
  283. T = Context.getTypeDeclType(TD);
  284. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  285. // constructor or destructor name (in such a case, the scope specifier
  286. // will be attached to the enclosing Expr or Decl node).
  287. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  288. if (WantNontrivialTypeSourceInfo) {
  289. // Construct a type with type-source information.
  290. TypeLocBuilder Builder;
  291. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  292. T = getElaboratedType(ETK_None, *SS, T);
  293. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  294. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  295. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  296. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  297. } else {
  298. T = getElaboratedType(ETK_None, *SS, T);
  299. }
  300. }
  301. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  302. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  303. if (!HasTrailingDot)
  304. T = Context.getObjCInterfaceType(IDecl);
  305. }
  306. if (T.isNull()) {
  307. // If it's not plausibly a type, suppress diagnostics.
  308. Result.suppressDiagnostics();
  309. return ParsedType();
  310. }
  311. return ParsedType::make(T);
  312. }
  313. /// isTagName() - This method is called *for error recovery purposes only*
  314. /// to determine if the specified name is a valid tag name ("struct foo"). If
  315. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  316. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  317. /// cases in C where the user forgot to specify the tag.
  318. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  319. // Do a tag name lookup in this scope.
  320. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  321. LookupName(R, S, false);
  322. R.suppressDiagnostics();
  323. if (R.getResultKind() == LookupResult::Found)
  324. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  325. switch (TD->getTagKind()) {
  326. case TTK_Struct: return DeclSpec::TST_struct;
  327. case TTK_Interface: return DeclSpec::TST_interface;
  328. case TTK_Union: return DeclSpec::TST_union;
  329. case TTK_Class: return DeclSpec::TST_class;
  330. case TTK_Enum: return DeclSpec::TST_enum;
  331. }
  332. }
  333. return DeclSpec::TST_unspecified;
  334. }
  335. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  336. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  337. /// then downgrade the missing typename error to a warning.
  338. /// This is needed for MSVC compatibility; Example:
  339. /// @code
  340. /// template<class T> class A {
  341. /// public:
  342. /// typedef int TYPE;
  343. /// };
  344. /// template<class T> class B : public A<T> {
  345. /// public:
  346. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  347. /// };
  348. /// @endcode
  349. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  350. if (CurContext->isRecord()) {
  351. const Type *Ty = SS->getScopeRep()->getAsType();
  352. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  353. for (const auto &Base : RD->bases())
  354. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  355. return true;
  356. return S->isFunctionPrototypeScope();
  357. }
  358. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  359. }
  360. bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  361. SourceLocation IILoc,
  362. Scope *S,
  363. CXXScopeSpec *SS,
  364. ParsedType &SuggestedType,
  365. bool AllowClassTemplates) {
  366. // We don't have anything to suggest (yet).
  367. SuggestedType = ParsedType();
  368. // There may have been a typo in the name of the type. Look up typo
  369. // results, in case we have something that we can suggest.
  370. TypeNameValidatorCCC Validator(false, false, AllowClassTemplates);
  371. if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
  372. LookupOrdinaryName, S, SS,
  373. Validator, CTK_ErrorRecovery)) {
  374. if (Corrected.isKeyword()) {
  375. // We corrected to a keyword.
  376. diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
  377. II = Corrected.getCorrectionAsIdentifierInfo();
  378. } else {
  379. // We found a similarly-named type or interface; suggest that.
  380. if (!SS || !SS->isSet()) {
  381. diagnoseTypo(Corrected,
  382. PDiag(diag::err_unknown_typename_suggest) << II);
  383. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  384. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  385. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  386. II->getName().equals(CorrectedStr);
  387. diagnoseTypo(Corrected,
  388. PDiag(diag::err_unknown_nested_typename_suggest)
  389. << II << DC << DroppedSpecifier << SS->getRange());
  390. } else {
  391. llvm_unreachable("could not have corrected a typo here");
  392. }
  393. CXXScopeSpec tmpSS;
  394. if (Corrected.getCorrectionSpecifier())
  395. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  396. SourceRange(IILoc));
  397. SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
  398. IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
  399. false, ParsedType(),
  400. /*IsCtorOrDtorName=*/false,
  401. /*NonTrivialTypeSourceInfo=*/true);
  402. }
  403. return true;
  404. }
  405. if (getLangOpts().CPlusPlus) {
  406. // See if II is a class template that the user forgot to pass arguments to.
  407. UnqualifiedId Name;
  408. Name.setIdentifier(II, IILoc);
  409. CXXScopeSpec EmptySS;
  410. TemplateTy TemplateResult;
  411. bool MemberOfUnknownSpecialization;
  412. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  413. Name, ParsedType(), true, TemplateResult,
  414. MemberOfUnknownSpecialization) == TNK_Type_template) {
  415. TemplateName TplName = TemplateResult.get();
  416. Diag(IILoc, diag::err_template_missing_args) << TplName;
  417. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  418. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  419. << TplDecl->getTemplateParameters()->getSourceRange();
  420. }
  421. return true;
  422. }
  423. }
  424. // FIXME: Should we move the logic that tries to recover from a missing tag
  425. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  426. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  427. Diag(IILoc, diag::err_unknown_typename) << II;
  428. else if (DeclContext *DC = computeDeclContext(*SS, false))
  429. Diag(IILoc, diag::err_typename_nested_not_found)
  430. << II << DC << SS->getRange();
  431. else if (isDependentScopeSpecifier(*SS)) {
  432. unsigned DiagID = diag::err_typename_missing;
  433. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  434. DiagID = diag::warn_typename_missing;
  435. Diag(SS->getRange().getBegin(), DiagID)
  436. << SS->getScopeRep() << II->getName()
  437. << SourceRange(SS->getRange().getBegin(), IILoc)
  438. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  439. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  440. *SS, *II, IILoc).get();
  441. } else {
  442. assert(SS && SS->isInvalid() &&
  443. "Invalid scope specifier has already been diagnosed");
  444. }
  445. return true;
  446. }
  447. /// \brief Determine whether the given result set contains either a type name
  448. /// or
  449. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  450. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  451. NextToken.is(tok::less);
  452. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  453. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  454. return true;
  455. if (CheckTemplate && isa<TemplateDecl>(*I))
  456. return true;
  457. }
  458. return false;
  459. }
  460. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  461. Scope *S, CXXScopeSpec &SS,
  462. IdentifierInfo *&Name,
  463. SourceLocation NameLoc) {
  464. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  465. SemaRef.LookupParsedName(R, S, &SS);
  466. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  467. StringRef FixItTagName;
  468. switch (Tag->getTagKind()) {
  469. case TTK_Class:
  470. FixItTagName = "class ";
  471. break;
  472. case TTK_Enum:
  473. FixItTagName = "enum ";
  474. break;
  475. case TTK_Struct:
  476. FixItTagName = "struct ";
  477. break;
  478. case TTK_Interface:
  479. FixItTagName = "__interface ";
  480. break;
  481. case TTK_Union:
  482. FixItTagName = "union ";
  483. break;
  484. }
  485. StringRef TagName = FixItTagName.drop_back();
  486. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  487. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  488. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  489. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  490. I != IEnd; ++I)
  491. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  492. << Name << TagName;
  493. // Replace lookup results with just the tag decl.
  494. Result.clear(Sema::LookupTagName);
  495. SemaRef.LookupParsedName(Result, S, &SS);
  496. return true;
  497. }
  498. return false;
  499. }
  500. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  501. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  502. QualType T, SourceLocation NameLoc) {
  503. ASTContext &Context = S.Context;
  504. TypeLocBuilder Builder;
  505. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  506. T = S.getElaboratedType(ETK_None, SS, T);
  507. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  508. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  509. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  510. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  511. }
  512. Sema::NameClassification Sema::ClassifyName(Scope *S,
  513. CXXScopeSpec &SS,
  514. IdentifierInfo *&Name,
  515. SourceLocation NameLoc,
  516. const Token &NextToken,
  517. bool IsAddressOfOperand,
  518. CorrectionCandidateCallback *CCC) {
  519. DeclarationNameInfo NameInfo(Name, NameLoc);
  520. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  521. if (NextToken.is(tok::coloncolon)) {
  522. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  523. QualType(), false, SS, 0, false);
  524. }
  525. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  526. LookupParsedName(Result, S, &SS, !CurMethod);
  527. // Perform lookup for Objective-C instance variables (including automatically
  528. // synthesized instance variables), if we're in an Objective-C method.
  529. // FIXME: This lookup really, really needs to be folded in to the normal
  530. // unqualified lookup mechanism.
  531. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  532. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  533. if (E.get() || E.isInvalid())
  534. return E;
  535. }
  536. bool SecondTry = false;
  537. bool IsFilteredTemplateName = false;
  538. Corrected:
  539. switch (Result.getResultKind()) {
  540. case LookupResult::NotFound:
  541. // If an unqualified-id is followed by a '(', then we have a function
  542. // call.
  543. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  544. // In C++, this is an ADL-only call.
  545. // FIXME: Reference?
  546. if (getLangOpts().CPlusPlus)
  547. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  548. // C90 6.3.2.2:
  549. // If the expression that precedes the parenthesized argument list in a
  550. // function call consists solely of an identifier, and if no
  551. // declaration is visible for this identifier, the identifier is
  552. // implicitly declared exactly as if, in the innermost block containing
  553. // the function call, the declaration
  554. //
  555. // extern int identifier ();
  556. //
  557. // appeared.
  558. //
  559. // We also allow this in C99 as an extension.
  560. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  561. Result.addDecl(D);
  562. Result.resolveKind();
  563. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  564. }
  565. }
  566. // In C, we first see whether there is a tag type by the same name, in
  567. // which case it's likely that the user just forget to write "enum",
  568. // "struct", or "union".
  569. if (!getLangOpts().CPlusPlus && !SecondTry &&
  570. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  571. break;
  572. }
  573. // Perform typo correction to determine if there is another name that is
  574. // close to this name.
  575. if (!SecondTry && CCC) {
  576. SecondTry = true;
  577. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  578. Result.getLookupKind(), S,
  579. &SS, *CCC,
  580. CTK_ErrorRecovery)) {
  581. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  582. unsigned QualifiedDiag = diag::err_no_member_suggest;
  583. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  584. NamedDecl *UnderlyingFirstDecl
  585. = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
  586. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  587. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  588. UnqualifiedDiag = diag::err_no_template_suggest;
  589. QualifiedDiag = diag::err_no_member_template_suggest;
  590. } else if (UnderlyingFirstDecl &&
  591. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  592. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  593. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  594. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  595. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  596. }
  597. if (SS.isEmpty()) {
  598. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  599. } else {// FIXME: is this even reachable? Test it.
  600. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  601. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  602. Name->getName().equals(CorrectedStr);
  603. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  604. << Name << computeDeclContext(SS, false)
  605. << DroppedSpecifier << SS.getRange());
  606. }
  607. // Update the name, so that the caller has the new name.
  608. Name = Corrected.getCorrectionAsIdentifierInfo();
  609. // Typo correction corrected to a keyword.
  610. if (Corrected.isKeyword())
  611. return Name;
  612. // Also update the LookupResult...
  613. // FIXME: This should probably go away at some point
  614. Result.clear();
  615. Result.setLookupName(Corrected.getCorrection());
  616. if (FirstDecl)
  617. Result.addDecl(FirstDecl);
  618. // If we found an Objective-C instance variable, let
  619. // LookupInObjCMethod build the appropriate expression to
  620. // reference the ivar.
  621. // FIXME: This is a gross hack.
  622. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  623. Result.clear();
  624. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  625. return E;
  626. }
  627. goto Corrected;
  628. }
  629. }
  630. // We failed to correct; just fall through and let the parser deal with it.
  631. Result.suppressDiagnostics();
  632. return NameClassification::Unknown();
  633. case LookupResult::NotFoundInCurrentInstantiation: {
  634. // We performed name lookup into the current instantiation, and there were
  635. // dependent bases, so we treat this result the same way as any other
  636. // dependent nested-name-specifier.
  637. // C++ [temp.res]p2:
  638. // A name used in a template declaration or definition and that is
  639. // dependent on a template-parameter is assumed not to name a type
  640. // unless the applicable name lookup finds a type name or the name is
  641. // qualified by the keyword typename.
  642. //
  643. // FIXME: If the next token is '<', we might want to ask the parser to
  644. // perform some heroics to see if we actually have a
  645. // template-argument-list, which would indicate a missing 'template'
  646. // keyword here.
  647. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  648. NameInfo, IsAddressOfOperand,
  649. /*TemplateArgs=*/0);
  650. }
  651. case LookupResult::Found:
  652. case LookupResult::FoundOverloaded:
  653. case LookupResult::FoundUnresolvedValue:
  654. break;
  655. case LookupResult::Ambiguous:
  656. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  657. hasAnyAcceptableTemplateNames(Result)) {
  658. // C++ [temp.local]p3:
  659. // A lookup that finds an injected-class-name (10.2) can result in an
  660. // ambiguity in certain cases (for example, if it is found in more than
  661. // one base class). If all of the injected-class-names that are found
  662. // refer to specializations of the same class template, and if the name
  663. // is followed by a template-argument-list, the reference refers to the
  664. // class template itself and not a specialization thereof, and is not
  665. // ambiguous.
  666. //
  667. // This filtering can make an ambiguous result into an unambiguous one,
  668. // so try again after filtering out template names.
  669. FilterAcceptableTemplateNames(Result);
  670. if (!Result.isAmbiguous()) {
  671. IsFilteredTemplateName = true;
  672. break;
  673. }
  674. }
  675. // Diagnose the ambiguity and return an error.
  676. return NameClassification::Error();
  677. }
  678. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  679. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  680. // C++ [temp.names]p3:
  681. // After name lookup (3.4) finds that a name is a template-name or that
  682. // an operator-function-id or a literal- operator-id refers to a set of
  683. // overloaded functions any member of which is a function template if
  684. // this is followed by a <, the < is always taken as the delimiter of a
  685. // template-argument-list and never as the less-than operator.
  686. if (!IsFilteredTemplateName)
  687. FilterAcceptableTemplateNames(Result);
  688. if (!Result.empty()) {
  689. bool IsFunctionTemplate;
  690. bool IsVarTemplate;
  691. TemplateName Template;
  692. if (Result.end() - Result.begin() > 1) {
  693. IsFunctionTemplate = true;
  694. Template = Context.getOverloadedTemplateName(Result.begin(),
  695. Result.end());
  696. } else {
  697. TemplateDecl *TD
  698. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  699. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  700. IsVarTemplate = isa<VarTemplateDecl>(TD);
  701. if (SS.isSet() && !SS.isInvalid())
  702. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  703. /*TemplateKeyword=*/false,
  704. TD);
  705. else
  706. Template = TemplateName(TD);
  707. }
  708. if (IsFunctionTemplate) {
  709. // Function templates always go through overload resolution, at which
  710. // point we'll perform the various checks (e.g., accessibility) we need
  711. // to based on which function we selected.
  712. Result.suppressDiagnostics();
  713. return NameClassification::FunctionTemplate(Template);
  714. }
  715. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  716. : NameClassification::TypeTemplate(Template);
  717. }
  718. }
  719. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  720. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  721. DiagnoseUseOfDecl(Type, NameLoc);
  722. QualType T = Context.getTypeDeclType(Type);
  723. if (SS.isNotEmpty())
  724. return buildNestedType(*this, SS, T, NameLoc);
  725. return ParsedType::make(T);
  726. }
  727. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  728. if (!Class) {
  729. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  730. if (ObjCCompatibleAliasDecl *Alias =
  731. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  732. Class = Alias->getClassInterface();
  733. }
  734. if (Class) {
  735. DiagnoseUseOfDecl(Class, NameLoc);
  736. if (NextToken.is(tok::period)) {
  737. // Interface. <something> is parsed as a property reference expression.
  738. // Just return "unknown" as a fall-through for now.
  739. Result.suppressDiagnostics();
  740. return NameClassification::Unknown();
  741. }
  742. QualType T = Context.getObjCInterfaceType(Class);
  743. return ParsedType::make(T);
  744. }
  745. // We can have a type template here if we're classifying a template argument.
  746. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  747. return NameClassification::TypeTemplate(
  748. TemplateName(cast<TemplateDecl>(FirstDecl)));
  749. // Check for a tag type hidden by a non-type decl in a few cases where it
  750. // seems likely a type is wanted instead of the non-type that was found.
  751. bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
  752. if ((NextToken.is(tok::identifier) ||
  753. (NextIsOp &&
  754. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  755. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  756. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  757. DiagnoseUseOfDecl(Type, NameLoc);
  758. QualType T = Context.getTypeDeclType(Type);
  759. if (SS.isNotEmpty())
  760. return buildNestedType(*this, SS, T, NameLoc);
  761. return ParsedType::make(T);
  762. }
  763. if (FirstDecl->isCXXClassMember())
  764. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
  765. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  766. return BuildDeclarationNameExpr(SS, Result, ADL);
  767. }
  768. // Determines the context to return to after temporarily entering a
  769. // context. This depends in an unnecessarily complicated way on the
  770. // exact ordering of callbacks from the parser.
  771. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  772. // Functions defined inline within classes aren't parsed until we've
  773. // finished parsing the top-level class, so the top-level class is
  774. // the context we'll need to return to.
  775. // A Lambda call operator whose parent is a class must not be treated
  776. // as an inline member function. A Lambda can be used legally
  777. // either as an in-class member initializer or a default argument. These
  778. // are parsed once the class has been marked complete and so the containing
  779. // context would be the nested class (when the lambda is defined in one);
  780. // If the class is not complete, then the lambda is being used in an
  781. // ill-formed fashion (such as to specify the width of a bit-field, or
  782. // in an array-bound) - in which case we still want to return the
  783. // lexically containing DC (which could be a nested class).
  784. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  785. DC = DC->getLexicalParent();
  786. // A function not defined within a class will always return to its
  787. // lexical context.
  788. if (!isa<CXXRecordDecl>(DC))
  789. return DC;
  790. // A C++ inline method/friend is parsed *after* the topmost class
  791. // it was declared in is fully parsed ("complete"); the topmost
  792. // class is the context we need to return to.
  793. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  794. DC = RD;
  795. // Return the declaration context of the topmost class the inline method is
  796. // declared in.
  797. return DC;
  798. }
  799. return DC->getLexicalParent();
  800. }
  801. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  802. assert(getContainingDC(DC) == CurContext &&
  803. "The next DeclContext should be lexically contained in the current one.");
  804. CurContext = DC;
  805. S->setEntity(DC);
  806. }
  807. void Sema::PopDeclContext() {
  808. assert(CurContext && "DeclContext imbalance!");
  809. CurContext = getContainingDC(CurContext);
  810. assert(CurContext && "Popped translation unit!");
  811. }
  812. /// EnterDeclaratorContext - Used when we must lookup names in the context
  813. /// of a declarator's nested name specifier.
  814. ///
  815. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  816. // C++0x [basic.lookup.unqual]p13:
  817. // A name used in the definition of a static data member of class
  818. // X (after the qualified-id of the static member) is looked up as
  819. // if the name was used in a member function of X.
  820. // C++0x [basic.lookup.unqual]p14:
  821. // If a variable member of a namespace is defined outside of the
  822. // scope of its namespace then any name used in the definition of
  823. // the variable member (after the declarator-id) is looked up as
  824. // if the definition of the variable member occurred in its
  825. // namespace.
  826. // Both of these imply that we should push a scope whose context
  827. // is the semantic context of the declaration. We can't use
  828. // PushDeclContext here because that context is not necessarily
  829. // lexically contained in the current context. Fortunately,
  830. // the containing scope should have the appropriate information.
  831. assert(!S->getEntity() && "scope already has entity");
  832. #ifndef NDEBUG
  833. Scope *Ancestor = S->getParent();
  834. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  835. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  836. #endif
  837. CurContext = DC;
  838. S->setEntity(DC);
  839. }
  840. void Sema::ExitDeclaratorContext(Scope *S) {
  841. assert(S->getEntity() == CurContext && "Context imbalance!");
  842. // Switch back to the lexical context. The safety of this is
  843. // enforced by an assert in EnterDeclaratorContext.
  844. Scope *Ancestor = S->getParent();
  845. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  846. CurContext = Ancestor->getEntity();
  847. // We don't need to do anything with the scope, which is going to
  848. // disappear.
  849. }
  850. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  851. // We assume that the caller has already called
  852. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  853. FunctionDecl *FD = D->getAsFunction();
  854. if (!FD)
  855. return;
  856. // Same implementation as PushDeclContext, but enters the context
  857. // from the lexical parent, rather than the top-level class.
  858. assert(CurContext == FD->getLexicalParent() &&
  859. "The next DeclContext should be lexically contained in the current one.");
  860. CurContext = FD;
  861. S->setEntity(CurContext);
  862. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  863. ParmVarDecl *Param = FD->getParamDecl(P);
  864. // If the parameter has an identifier, then add it to the scope
  865. if (Param->getIdentifier()) {
  866. S->AddDecl(Param);
  867. IdResolver.AddDecl(Param);
  868. }
  869. }
  870. }
  871. void Sema::ActOnExitFunctionContext() {
  872. // Same implementation as PopDeclContext, but returns to the lexical parent,
  873. // rather than the top-level class.
  874. assert(CurContext && "DeclContext imbalance!");
  875. CurContext = CurContext->getLexicalParent();
  876. assert(CurContext && "Popped translation unit!");
  877. }
  878. /// \brief Determine whether we allow overloading of the function
  879. /// PrevDecl with another declaration.
  880. ///
  881. /// This routine determines whether overloading is possible, not
  882. /// whether some new function is actually an overload. It will return
  883. /// true in C++ (where we can always provide overloads) or, as an
  884. /// extension, in C when the previous function is already an
  885. /// overloaded function declaration or has the "overloadable"
  886. /// attribute.
  887. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  888. ASTContext &Context) {
  889. if (Context.getLangOpts().CPlusPlus)
  890. return true;
  891. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  892. return true;
  893. return (Previous.getResultKind() == LookupResult::Found
  894. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  895. }
  896. /// Add this decl to the scope shadowed decl chains.
  897. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  898. // Move up the scope chain until we find the nearest enclosing
  899. // non-transparent context. The declaration will be introduced into this
  900. // scope.
  901. while (S->getEntity() && S->getEntity()->isTransparentContext())
  902. S = S->getParent();
  903. // Add scoped declarations into their context, so that they can be
  904. // found later. Declarations without a context won't be inserted
  905. // into any context.
  906. if (AddToContext)
  907. CurContext->addDecl(D);
  908. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  909. // are function-local declarations.
  910. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  911. !D->getDeclContext()->getRedeclContext()->Equals(
  912. D->getLexicalDeclContext()->getRedeclContext()) &&
  913. !D->getLexicalDeclContext()->isFunctionOrMethod())
  914. return;
  915. // Template instantiations should also not be pushed into scope.
  916. if (isa<FunctionDecl>(D) &&
  917. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  918. return;
  919. // If this replaces anything in the current scope,
  920. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  921. IEnd = IdResolver.end();
  922. for (; I != IEnd; ++I) {
  923. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  924. S->RemoveDecl(*I);
  925. IdResolver.RemoveDecl(*I);
  926. // Should only need to replace one decl.
  927. break;
  928. }
  929. }
  930. S->AddDecl(D);
  931. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  932. // Implicitly-generated labels may end up getting generated in an order that
  933. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  934. // the label at the appropriate place in the identifier chain.
  935. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  936. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  937. if (IDC == CurContext) {
  938. if (!S->isDeclScope(*I))
  939. continue;
  940. } else if (IDC->Encloses(CurContext))
  941. break;
  942. }
  943. IdResolver.InsertDeclAfter(I, D);
  944. } else {
  945. IdResolver.AddDecl(D);
  946. }
  947. }
  948. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  949. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  950. TUScope->AddDecl(D);
  951. }
  952. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  953. bool AllowInlineNamespace) {
  954. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  955. }
  956. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  957. DeclContext *TargetDC = DC->getPrimaryContext();
  958. do {
  959. if (DeclContext *ScopeDC = S->getEntity())
  960. if (ScopeDC->getPrimaryContext() == TargetDC)
  961. return S;
  962. } while ((S = S->getParent()));
  963. return 0;
  964. }
  965. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  966. DeclContext*,
  967. ASTContext&);
  968. /// Filters out lookup results that don't fall within the given scope
  969. /// as determined by isDeclInScope.
  970. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  971. bool ConsiderLinkage,
  972. bool AllowInlineNamespace) {
  973. LookupResult::Filter F = R.makeFilter();
  974. while (F.hasNext()) {
  975. NamedDecl *D = F.next();
  976. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  977. continue;
  978. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  979. continue;
  980. F.erase();
  981. }
  982. F.done();
  983. }
  984. static bool isUsingDecl(NamedDecl *D) {
  985. return isa<UsingShadowDecl>(D) ||
  986. isa<UnresolvedUsingTypenameDecl>(D) ||
  987. isa<UnresolvedUsingValueDecl>(D);
  988. }
  989. /// Removes using shadow declarations from the lookup results.
  990. static void RemoveUsingDecls(LookupResult &R) {
  991. LookupResult::Filter F = R.makeFilter();
  992. while (F.hasNext())
  993. if (isUsingDecl(F.next()))
  994. F.erase();
  995. F.done();
  996. }
  997. /// \brief Check for this common pattern:
  998. /// @code
  999. /// class S {
  1000. /// S(const S&); // DO NOT IMPLEMENT
  1001. /// void operator=(const S&); // DO NOT IMPLEMENT
  1002. /// };
  1003. /// @endcode
  1004. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1005. // FIXME: Should check for private access too but access is set after we get
  1006. // the decl here.
  1007. if (D->doesThisDeclarationHaveABody())
  1008. return false;
  1009. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1010. return CD->isCopyConstructor();
  1011. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1012. return Method->isCopyAssignmentOperator();
  1013. return false;
  1014. }
  1015. // We need this to handle
  1016. //
  1017. // typedef struct {
  1018. // void *foo() { return 0; }
  1019. // } A;
  1020. //
  1021. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1022. // for example. If 'A', foo will have external linkage. If we have '*A',
  1023. // foo will have no linkage. Since we can't know until we get to the end
  1024. // of the typedef, this function finds out if D might have non-external linkage.
  1025. // Callers should verify at the end of the TU if it D has external linkage or
  1026. // not.
  1027. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1028. const DeclContext *DC = D->getDeclContext();
  1029. while (!DC->isTranslationUnit()) {
  1030. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1031. if (!RD->hasNameForLinkage())
  1032. return true;
  1033. }
  1034. DC = DC->getParent();
  1035. }
  1036. return !D->isExternallyVisible();
  1037. }
  1038. // FIXME: This needs to be refactored; some other isInMainFile users want
  1039. // these semantics.
  1040. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1041. if (S.TUKind != TU_Complete)
  1042. return false;
  1043. return S.SourceMgr.isInMainFile(Loc);
  1044. }
  1045. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1046. assert(D);
  1047. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1048. return false;
  1049. // Ignore all entities declared within templates, and out-of-line definitions
  1050. // of members of class templates.
  1051. if (D->getDeclContext()->isDependentContext() ||
  1052. D->getLexicalDeclContext()->isDependentContext())
  1053. return false;
  1054. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1055. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1056. return false;
  1057. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1058. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1059. return false;
  1060. } else {
  1061. // 'static inline' functions are defined in headers; don't warn.
  1062. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1063. return false;
  1064. }
  1065. if (FD->doesThisDeclarationHaveABody() &&
  1066. Context.DeclMustBeEmitted(FD))
  1067. return false;
  1068. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1069. // Constants and utility variables are defined in headers with internal
  1070. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1071. // like "inline".)
  1072. if (!isMainFileLoc(*this, VD->getLocation()))
  1073. return false;
  1074. if (Context.DeclMustBeEmitted(VD))
  1075. return false;
  1076. if (VD->isStaticDataMember() &&
  1077. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1078. return false;
  1079. } else {
  1080. return false;
  1081. }
  1082. // Only warn for unused decls internal to the translation unit.
  1083. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1084. // for inline functions defined in the main source file, for instance.
  1085. return mightHaveNonExternalLinkage(D);
  1086. }
  1087. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1088. if (!D)
  1089. return;
  1090. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1091. const FunctionDecl *First = FD->getFirstDecl();
  1092. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1093. return; // First should already be in the vector.
  1094. }
  1095. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1096. const VarDecl *First = VD->getFirstDecl();
  1097. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1098. return; // First should already be in the vector.
  1099. }
  1100. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1101. UnusedFileScopedDecls.push_back(D);
  1102. }
  1103. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1104. if (D->isInvalidDecl())
  1105. return false;
  1106. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1107. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1108. return false;
  1109. if (isa<LabelDecl>(D))
  1110. return true;
  1111. // White-list anything that isn't a local variable.
  1112. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
  1113. !D->getDeclContext()->isFunctionOrMethod())
  1114. return false;
  1115. // Types of valid local variables should be complete, so this should succeed.
  1116. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1117. // White-list anything with an __attribute__((unused)) type.
  1118. QualType Ty = VD->getType();
  1119. // Only look at the outermost level of typedef.
  1120. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1121. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1122. return false;
  1123. }
  1124. // If we failed to complete the type for some reason, or if the type is
  1125. // dependent, don't diagnose the variable.
  1126. if (Ty->isIncompleteType() || Ty->isDependentType())
  1127. return false;
  1128. if (const TagType *TT = Ty->getAs<TagType>()) {
  1129. const TagDecl *Tag = TT->getDecl();
  1130. if (Tag->hasAttr<UnusedAttr>())
  1131. return false;
  1132. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1133. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1134. return false;
  1135. if (const Expr *Init = VD->getInit()) {
  1136. if (const ExprWithCleanups *Cleanups =
  1137. dyn_cast<ExprWithCleanups>(Init))
  1138. Init = Cleanups->getSubExpr();
  1139. const CXXConstructExpr *Construct =
  1140. dyn_cast<CXXConstructExpr>(Init);
  1141. if (Construct && !Construct->isElidable()) {
  1142. CXXConstructorDecl *CD = Construct->getConstructor();
  1143. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1144. return false;
  1145. }
  1146. }
  1147. }
  1148. }
  1149. // TODO: __attribute__((unused)) templates?
  1150. }
  1151. return true;
  1152. }
  1153. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1154. FixItHint &Hint) {
  1155. if (isa<LabelDecl>(D)) {
  1156. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1157. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1158. if (AfterColon.isInvalid())
  1159. return;
  1160. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1161. getCharRange(D->getLocStart(), AfterColon));
  1162. }
  1163. return;
  1164. }
  1165. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1166. /// unless they are marked attr(unused).
  1167. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1168. if (!ShouldDiagnoseUnusedDecl(D))
  1169. return;
  1170. FixItHint Hint;
  1171. GenerateFixForUnusedDecl(D, Context, Hint);
  1172. unsigned DiagID;
  1173. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1174. DiagID = diag::warn_unused_exception_param;
  1175. else if (isa<LabelDecl>(D))
  1176. DiagID = diag::warn_unused_label;
  1177. else
  1178. DiagID = diag::warn_unused_variable;
  1179. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1180. }
  1181. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1182. // Verify that we have no forward references left. If so, there was a goto
  1183. // or address of a label taken, but no definition of it. Label fwd
  1184. // definitions are indicated with a null substmt.
  1185. if (L->getStmt() == 0)
  1186. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1187. }
  1188. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1189. S->mergeNRVOIntoParent();
  1190. if (S->decl_empty()) return;
  1191. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1192. "Scope shouldn't contain decls!");
  1193. for (auto *TmpD : S->decls()) {
  1194. assert(TmpD && "This decl didn't get pushed??");
  1195. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1196. NamedDecl *D = cast<NamedDecl>(TmpD);
  1197. if (!D->getDeclName()) continue;
  1198. // Diagnose unused variables in this scope.
  1199. if (!S->hasUnrecoverableErrorOccurred())
  1200. DiagnoseUnusedDecl(D);
  1201. // If this was a forward reference to a label, verify it was defined.
  1202. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1203. CheckPoppedLabel(LD, *this);
  1204. // Remove this name from our lexical scope.
  1205. IdResolver.RemoveDecl(D);
  1206. }
  1207. }
  1208. /// \brief Look for an Objective-C class in the translation unit.
  1209. ///
  1210. /// \param Id The name of the Objective-C class we're looking for. If
  1211. /// typo-correction fixes this name, the Id will be updated
  1212. /// to the fixed name.
  1213. ///
  1214. /// \param IdLoc The location of the name in the translation unit.
  1215. ///
  1216. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1217. /// if there is no class with the given name.
  1218. ///
  1219. /// \returns The declaration of the named Objective-C class, or NULL if the
  1220. /// class could not be found.
  1221. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1222. SourceLocation IdLoc,
  1223. bool DoTypoCorrection) {
  1224. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1225. // creation from this context.
  1226. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1227. if (!IDecl && DoTypoCorrection) {
  1228. // Perform typo correction at the given location, but only if we
  1229. // find an Objective-C class name.
  1230. DeclFilterCCC<ObjCInterfaceDecl> Validator;
  1231. if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
  1232. LookupOrdinaryName, TUScope, NULL,
  1233. Validator, CTK_ErrorRecovery)) {
  1234. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1235. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1236. Id = IDecl->getIdentifier();
  1237. }
  1238. }
  1239. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1240. // This routine must always return a class definition, if any.
  1241. if (Def && Def->getDefinition())
  1242. Def = Def->getDefinition();
  1243. return Def;
  1244. }
  1245. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1246. /// from S, where a non-field would be declared. This routine copes
  1247. /// with the difference between C and C++ scoping rules in structs and
  1248. /// unions. For example, the following code is well-formed in C but
  1249. /// ill-formed in C++:
  1250. /// @code
  1251. /// struct S6 {
  1252. /// enum { BAR } e;
  1253. /// };
  1254. ///
  1255. /// void test_S6() {
  1256. /// struct S6 a;
  1257. /// a.e = BAR;
  1258. /// }
  1259. /// @endcode
  1260. /// For the declaration of BAR, this routine will return a different
  1261. /// scope. The scope S will be the scope of the unnamed enumeration
  1262. /// within S6. In C++, this routine will return the scope associated
  1263. /// with S6, because the enumeration's scope is a transparent
  1264. /// context but structures can contain non-field names. In C, this
  1265. /// routine will return the translation unit scope, since the
  1266. /// enumeration's scope is a transparent context and structures cannot
  1267. /// contain non-field names.
  1268. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1269. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1270. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1271. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1272. S = S->getParent();
  1273. return S;
  1274. }
  1275. /// \brief Looks up the declaration of "struct objc_super" and
  1276. /// saves it for later use in building builtin declaration of
  1277. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1278. /// pre-existing declaration exists no action takes place.
  1279. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1280. IdentifierInfo *II) {
  1281. if (!II->isStr("objc_msgSendSuper"))
  1282. return;
  1283. ASTContext &Context = ThisSema.Context;
  1284. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1285. SourceLocation(), Sema::LookupTagName);
  1286. ThisSema.LookupName(Result, S);
  1287. if (Result.getResultKind() == LookupResult::Found)
  1288. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1289. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1290. }
  1291. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1292. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1293. /// if we're creating this built-in in anticipation of redeclaring the
  1294. /// built-in.
  1295. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
  1296. Scope *S, bool ForRedeclaration,
  1297. SourceLocation Loc) {
  1298. LookupPredefedObjCSuperType(*this, S, II);
  1299. Builtin::ID BID = (Builtin::ID)bid;
  1300. ASTContext::GetBuiltinTypeError Error;
  1301. QualType R = Context.GetBuiltinType(BID, Error);
  1302. switch (Error) {
  1303. case ASTContext::GE_None:
  1304. // Okay
  1305. break;
  1306. case ASTContext::GE_Missing_stdio:
  1307. if (ForRedeclaration)
  1308. Diag(Loc, diag::warn_implicit_decl_requires_stdio)
  1309. << Context.BuiltinInfo.GetName(BID);
  1310. return 0;
  1311. case ASTContext::GE_Missing_setjmp:
  1312. if (ForRedeclaration)
  1313. Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
  1314. << Context.BuiltinInfo.GetName(BID);
  1315. return 0;
  1316. case ASTContext::GE_Missing_ucontext:
  1317. if (ForRedeclaration)
  1318. Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
  1319. << Context.BuiltinInfo.GetName(BID);
  1320. return 0;
  1321. }
  1322. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  1323. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1324. << Context.BuiltinInfo.GetName(BID)
  1325. << R;
  1326. if (Context.BuiltinInfo.getHeaderName(BID) &&
  1327. Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
  1328. != DiagnosticsEngine::Ignored)
  1329. Diag(Loc, diag::note_please_include_header)
  1330. << Context.BuiltinInfo.getHeaderName(BID)
  1331. << Context.BuiltinInfo.GetName(BID);
  1332. }
  1333. DeclContext *Parent = Context.getTranslationUnitDecl();
  1334. if (getLangOpts().CPlusPlus) {
  1335. LinkageSpecDecl *CLinkageDecl =
  1336. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1337. LinkageSpecDecl::lang_c, false);
  1338. CLinkageDecl->setImplicit();
  1339. Parent->addDecl(CLinkageDecl);
  1340. Parent = CLinkageDecl;
  1341. }
  1342. FunctionDecl *New = FunctionDecl::Create(Context,
  1343. Parent,
  1344. Loc, Loc, II, R, /*TInfo=*/0,
  1345. SC_Extern,
  1346. false,
  1347. /*hasPrototype=*/true);
  1348. New->setImplicit();
  1349. // Create Decl objects for each parameter, adding them to the
  1350. // FunctionDecl.
  1351. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1352. SmallVector<ParmVarDecl*, 16> Params;
  1353. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1354. ParmVarDecl *parm =
  1355. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1356. 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0);
  1357. parm->setScopeInfo(0, i);
  1358. Params.push_back(parm);
  1359. }
  1360. New->setParams(Params);
  1361. }
  1362. AddKnownFunctionAttributes(New);
  1363. RegisterLocallyScopedExternCDecl(New, S);
  1364. // TUScope is the translation-unit scope to insert this function into.
  1365. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1366. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1367. // entirely, but we're not there yet.
  1368. DeclContext *SavedContext = CurContext;
  1369. CurContext = Parent;
  1370. PushOnScopeChains(New, TUScope);
  1371. CurContext = SavedContext;
  1372. return New;
  1373. }
  1374. /// \brief Filter out any previous declarations that the given declaration
  1375. /// should not consider because they are not permitted to conflict, e.g.,
  1376. /// because they come from hidden sub-modules and do not refer to the same
  1377. /// entity.
  1378. static void filterNonConflictingPreviousDecls(ASTContext &context,
  1379. NamedDecl *decl,
  1380. LookupResult &previous){
  1381. // This is only interesting when modules are enabled.
  1382. if (!context.getLangOpts().Modules)
  1383. return;
  1384. // Empty sets are uninteresting.
  1385. if (previous.empty())
  1386. return;
  1387. LookupResult::Filter filter = previous.makeFilter();
  1388. while (filter.hasNext()) {
  1389. NamedDecl *old = filter.next();
  1390. // Non-hidden declarations are never ignored.
  1391. if (!old->isHidden())
  1392. continue;
  1393. if (!old->isExternallyVisible())
  1394. filter.erase();
  1395. }
  1396. filter.done();
  1397. }
  1398. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1399. QualType OldType;
  1400. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1401. OldType = OldTypedef->getUnderlyingType();
  1402. else
  1403. OldType = Context.getTypeDeclType(Old);
  1404. QualType NewType = New->getUnderlyingType();
  1405. if (NewType->isVariablyModifiedType()) {
  1406. // Must not redefine a typedef with a variably-modified type.
  1407. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1408. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1409. << Kind << NewType;
  1410. if (Old->getLocation().isValid())
  1411. Diag(Old->getLocation(), diag::note_previous_definition);
  1412. New->setInvalidDecl();
  1413. return true;
  1414. }
  1415. if (OldType != NewType &&
  1416. !OldType->isDependentType() &&
  1417. !NewType->isDependentType() &&
  1418. !Context.hasSameType(OldType, NewType)) {
  1419. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1420. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1421. << Kind << NewType << OldType;
  1422. if (Old->getLocation().isValid())
  1423. Diag(Old->getLocation(), diag::note_previous_definition);
  1424. New->setInvalidDecl();
  1425. return true;
  1426. }
  1427. return false;
  1428. }
  1429. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1430. /// same name and scope as a previous declaration 'Old'. Figure out
  1431. /// how to resolve this situation, merging decls or emitting
  1432. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1433. ///
  1434. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1435. // If the new decl is known invalid already, don't bother doing any
  1436. // merging checks.
  1437. if (New->isInvalidDecl()) return;
  1438. // Allow multiple definitions for ObjC built-in typedefs.
  1439. // FIXME: Verify the underlying types are equivalent!
  1440. if (getLangOpts().ObjC1) {
  1441. const IdentifierInfo *TypeID = New->getIdentifier();
  1442. switch (TypeID->getLength()) {
  1443. default: break;
  1444. case 2:
  1445. {
  1446. if (!TypeID->isStr("id"))
  1447. break;
  1448. QualType T = New->getUnderlyingType();
  1449. if (!T->isPointerType())
  1450. break;
  1451. if (!T->isVoidPointerType()) {
  1452. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1453. if (!PT->isStructureType())
  1454. break;
  1455. }
  1456. Context.setObjCIdRedefinitionType(T);
  1457. // Install the built-in type for 'id', ignoring the current definition.
  1458. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1459. return;
  1460. }
  1461. case 5:
  1462. if (!TypeID->isStr("Class"))
  1463. break;
  1464. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1465. // Install the built-in type for 'Class', ignoring the current definition.
  1466. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1467. return;
  1468. case 3:
  1469. if (!TypeID->isStr("SEL"))
  1470. break;
  1471. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1472. // Install the built-in type for 'SEL', ignoring the current definition.
  1473. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1474. return;
  1475. }
  1476. // Fall through - the typedef name was not a builtin type.
  1477. }
  1478. // Verify the old decl was also a type.
  1479. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1480. if (!Old) {
  1481. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1482. << New->getDeclName();
  1483. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1484. if (OldD->getLocation().isValid())
  1485. Diag(OldD->getLocation(), diag::note_previous_definition);
  1486. return New->setInvalidDecl();
  1487. }
  1488. // If the old declaration is invalid, just give up here.
  1489. if (Old->isInvalidDecl())
  1490. return New->setInvalidDecl();
  1491. // If the typedef types are not identical, reject them in all languages and
  1492. // with any extensions enabled.
  1493. if (isIncompatibleTypedef(Old, New))
  1494. return;
  1495. // The types match. Link up the redeclaration chain and merge attributes if
  1496. // the old declaration was a typedef.
  1497. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1498. New->setPreviousDecl(Typedef);
  1499. mergeDeclAttributes(New, Old);
  1500. }
  1501. if (getLangOpts().MicrosoftExt)
  1502. return;
  1503. if (getLangOpts().CPlusPlus) {
  1504. // C++ [dcl.typedef]p2:
  1505. // In a given non-class scope, a typedef specifier can be used to
  1506. // redefine the name of any type declared in that scope to refer
  1507. // to the type to which it already refers.
  1508. if (!isa<CXXRecordDecl>(CurContext))
  1509. return;
  1510. // C++0x [dcl.typedef]p4:
  1511. // In a given class scope, a typedef specifier can be used to redefine
  1512. // any class-name declared in that scope that is not also a typedef-name
  1513. // to refer to the type to which it already refers.
  1514. //
  1515. // This wording came in via DR424, which was a correction to the
  1516. // wording in DR56, which accidentally banned code like:
  1517. //
  1518. // struct S {
  1519. // typedef struct A { } A;
  1520. // };
  1521. //
  1522. // in the C++03 standard. We implement the C++0x semantics, which
  1523. // allow the above but disallow
  1524. //
  1525. // struct S {
  1526. // typedef int I;
  1527. // typedef int I;
  1528. // };
  1529. //
  1530. // since that was the intent of DR56.
  1531. if (!isa<TypedefNameDecl>(Old))
  1532. return;
  1533. Diag(New->getLocation(), diag::err_redefinition)
  1534. << New->getDeclName();
  1535. Diag(Old->getLocation(), diag::note_previous_definition);
  1536. return New->setInvalidDecl();
  1537. }
  1538. // Modules always permit redefinition of typedefs, as does C11.
  1539. if (getLangOpts().Modules || getLangOpts().C11)
  1540. return;
  1541. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1542. // is normally mapped to an error, but can be controlled with
  1543. // -Wtypedef-redefinition. If either the original or the redefinition is
  1544. // in a system header, don't emit this for compatibility with GCC.
  1545. if (getDiagnostics().getSuppressSystemWarnings() &&
  1546. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1547. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1548. return;
  1549. Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
  1550. << New->getDeclName();
  1551. Diag(Old->getLocation(), diag::note_previous_definition);
  1552. return;
  1553. }
  1554. /// DeclhasAttr - returns true if decl Declaration already has the target
  1555. /// attribute.
  1556. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1557. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1558. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1559. for (const auto *i : D->attrs())
  1560. if (i->getKind() == A->getKind()) {
  1561. if (Ann) {
  1562. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1563. return true;
  1564. continue;
  1565. }
  1566. // FIXME: Don't hardcode this check
  1567. if (OA && isa<OwnershipAttr>(i))
  1568. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1569. return true;
  1570. }
  1571. return false;
  1572. }
  1573. static bool isAttributeTargetADefinition(Decl *D) {
  1574. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1575. return VD->isThisDeclarationADefinition();
  1576. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1577. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1578. return true;
  1579. }
  1580. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1581. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1582. ///
  1583. /// \return \c true if any attributes were added to \p New.
  1584. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1585. // Look for alignas attributes on Old, and pick out whichever attribute
  1586. // specifies the strictest alignment requirement.
  1587. AlignedAttr *OldAlignasAttr = 0;
  1588. AlignedAttr *OldStrictestAlignAttr = 0;
  1589. unsigned OldAlign = 0;
  1590. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1591. // FIXME: We have no way of representing inherited dependent alignments
  1592. // in a case like:
  1593. // template<int A, int B> struct alignas(A) X;
  1594. // template<int A, int B> struct alignas(B) X {};
  1595. // For now, we just ignore any alignas attributes which are not on the
  1596. // definition in such a case.
  1597. if (I->isAlignmentDependent())
  1598. return false;
  1599. if (I->isAlignas())
  1600. OldAlignasAttr = I;
  1601. unsigned Align = I->getAlignment(S.Context);
  1602. if (Align > OldAlign) {
  1603. OldAlign = Align;
  1604. OldStrictestAlignAttr = I;
  1605. }
  1606. }
  1607. // Look for alignas attributes on New.
  1608. AlignedAttr *NewAlignasAttr = 0;
  1609. unsigned NewAlign = 0;
  1610. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  1611. if (I->isAlignmentDependent())
  1612. return false;
  1613. if (I->isAlignas())
  1614. NewAlignasAttr = I;
  1615. unsigned Align = I->getAlignment(S.Context);
  1616. if (Align > NewAlign)
  1617. NewAlign = Align;
  1618. }
  1619. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  1620. // Both declarations have 'alignas' attributes. We require them to match.
  1621. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  1622. // fall short. (If two declarations both have alignas, they must both match
  1623. // every definition, and so must match each other if there is a definition.)
  1624. // If either declaration only contains 'alignas(0)' specifiers, then it
  1625. // specifies the natural alignment for the type.
  1626. if (OldAlign == 0 || NewAlign == 0) {
  1627. QualType Ty;
  1628. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  1629. Ty = VD->getType();
  1630. else
  1631. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  1632. if (OldAlign == 0)
  1633. OldAlign = S.Context.getTypeAlign(Ty);
  1634. if (NewAlign == 0)
  1635. NewAlign = S.Context.getTypeAlign(Ty);
  1636. }
  1637. if (OldAlign != NewAlign) {
  1638. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  1639. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  1640. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  1641. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  1642. }
  1643. }
  1644. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  1645. // C++11 [dcl.align]p6:
  1646. // if any declaration of an entity has an alignment-specifier,
  1647. // every defining declaration of that entity shall specify an
  1648. // equivalent alignment.
  1649. // C11 6.7.5/7:
  1650. // If the definition of an object does not have an alignment
  1651. // specifier, any other declaration of that object shall also
  1652. // have no alignment specifier.
  1653. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  1654. << OldAlignasAttr;
  1655. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  1656. << OldAlignasAttr;
  1657. }
  1658. bool AnyAdded = false;
  1659. // Ensure we have an attribute representing the strictest alignment.
  1660. if (OldAlign > NewAlign) {
  1661. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  1662. Clone->setInherited(true);
  1663. New->addAttr(Clone);
  1664. AnyAdded = true;
  1665. }
  1666. // Ensure we have an alignas attribute if the old declaration had one.
  1667. if (OldAlignasAttr && !NewAlignasAttr &&
  1668. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  1669. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  1670. Clone->setInherited(true);
  1671. New->addAttr(Clone);
  1672. AnyAdded = true;
  1673. }
  1674. return AnyAdded;
  1675. }
  1676. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  1677. const InheritableAttr *Attr, bool Override) {
  1678. InheritableAttr *NewAttr = nullptr;
  1679. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  1680. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  1681. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1682. AA->getIntroduced(), AA->getDeprecated(),
  1683. AA->getObsoleted(), AA->getUnavailable(),
  1684. AA->getMessage(), Override,
  1685. AttrSpellingListIndex);
  1686. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  1687. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1688. AttrSpellingListIndex);
  1689. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  1690. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  1691. AttrSpellingListIndex);
  1692. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1693. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  1694. AttrSpellingListIndex);
  1695. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1696. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  1697. AttrSpellingListIndex);
  1698. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  1699. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1700. FA->getFormatIdx(), FA->getFirstArg(),
  1701. AttrSpellingListIndex);
  1702. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  1703. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  1704. AttrSpellingListIndex);
  1705. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  1706. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  1707. AttrSpellingListIndex,
  1708. IA->getSemanticSpelling());
  1709. else if (isa<AlignedAttr>(Attr))
  1710. // AlignedAttrs are handled separately, because we need to handle all
  1711. // such attributes on a declaration at the same time.
  1712. NewAttr = nullptr;
  1713. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  1714. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  1715. if (NewAttr) {
  1716. NewAttr->setInherited(true);
  1717. D->addAttr(NewAttr);
  1718. return true;
  1719. }
  1720. return false;
  1721. }
  1722. static const Decl *getDefinition(const Decl *D) {
  1723. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1724. return TD->getDefinition();
  1725. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1726. const VarDecl *Def = VD->getDefinition();
  1727. if (Def)
  1728. return Def;
  1729. return VD->getActingDefinition();
  1730. }
  1731. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1732. const FunctionDecl* Def;
  1733. if (FD->isDefined(Def))
  1734. return Def;
  1735. }
  1736. return NULL;
  1737. }
  1738. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  1739. for (const auto *Attribute : D->attrs())
  1740. if (Attribute->getKind() == Kind)
  1741. return true;
  1742. return false;
  1743. }
  1744. /// checkNewAttributesAfterDef - If we already have a definition, check that
  1745. /// there are no new attributes in this declaration.
  1746. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  1747. if (!New->hasAttrs())
  1748. return;
  1749. const Decl *Def = getDefinition(Old);
  1750. if (!Def || Def == New)
  1751. return;
  1752. AttrVec &NewAttributes = New->getAttrs();
  1753. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  1754. const Attr *NewAttribute = NewAttributes[I];
  1755. if (isa<AliasAttr>(NewAttribute)) {
  1756. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
  1757. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
  1758. else {
  1759. VarDecl *VD = cast<VarDecl>(New);
  1760. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  1761. VarDecl::TentativeDefinition
  1762. ? diag::err_alias_after_tentative
  1763. : diag::err_redefinition;
  1764. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  1765. S.Diag(Def->getLocation(), diag::note_previous_definition);
  1766. VD->setInvalidDecl();
  1767. }
  1768. ++I;
  1769. continue;
  1770. }
  1771. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  1772. // Tentative definitions are only interesting for the alias check above.
  1773. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  1774. ++I;
  1775. continue;
  1776. }
  1777. }
  1778. if (hasAttribute(Def, NewAttribute->getKind())) {
  1779. ++I;
  1780. continue; // regular attr merging will take care of validating this.
  1781. }
  1782. if (isa<C11NoReturnAttr>(NewAttribute)) {
  1783. // C's _Noreturn is allowed to be added to a function after it is defined.
  1784. ++I;
  1785. continue;
  1786. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  1787. if (AA->isAlignas()) {
  1788. // C++11 [dcl.align]p6:
  1789. // if any declaration of an entity has an alignment-specifier,
  1790. // every defining declaration of that entity shall specify an
  1791. // equivalent alignment.
  1792. // C11 6.7.5/7:
  1793. // If the definition of an object does not have an alignment
  1794. // specifier, any other declaration of that object shall also
  1795. // have no alignment specifier.
  1796. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  1797. << AA;
  1798. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  1799. << AA;
  1800. NewAttributes.erase(NewAttributes.begin() + I);
  1801. --E;
  1802. continue;
  1803. }
  1804. }
  1805. S.Diag(NewAttribute->getLocation(),
  1806. diag::warn_attribute_precede_definition);
  1807. S.Diag(Def->getLocation(), diag::note_previous_definition);
  1808. NewAttributes.erase(NewAttributes.begin() + I);
  1809. --E;
  1810. }
  1811. }
  1812. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  1813. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  1814. AvailabilityMergeKind AMK) {
  1815. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  1816. UsedAttr *NewAttr = OldAttr->clone(Context);
  1817. NewAttr->setInherited(true);
  1818. New->addAttr(NewAttr);
  1819. }
  1820. if (!Old->hasAttrs() && !New->hasAttrs())
  1821. return;
  1822. // attributes declared post-definition are currently ignored
  1823. checkNewAttributesAfterDef(*this, New, Old);
  1824. if (!Old->hasAttrs())
  1825. return;
  1826. bool foundAny = New->hasAttrs();
  1827. // Ensure that any moving of objects within the allocated map is done before
  1828. // we process them.
  1829. if (!foundAny) New->setAttrs(AttrVec());
  1830. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  1831. bool Override = false;
  1832. // Ignore deprecated/unavailable/availability attributes if requested.
  1833. if (isa<DeprecatedAttr>(I) ||
  1834. isa<UnavailableAttr>(I) ||
  1835. isa<AvailabilityAttr>(I)) {
  1836. switch (AMK) {
  1837. case AMK_None:
  1838. continue;
  1839. case AMK_Redeclaration:
  1840. break;
  1841. case AMK_Override:
  1842. Override = true;
  1843. break;
  1844. }
  1845. }
  1846. // Already handled.
  1847. if (isa<UsedAttr>(I))
  1848. continue;
  1849. if (mergeDeclAttribute(*this, New, I, Override))
  1850. foundAny = true;
  1851. }
  1852. if (mergeAlignedAttrs(*this, New, Old))
  1853. foundAny = true;
  1854. if (!foundAny) New->dropAttrs();
  1855. }
  1856. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  1857. /// to the new one.
  1858. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  1859. const ParmVarDecl *oldDecl,
  1860. Sema &S) {
  1861. // C++11 [dcl.attr.depend]p2:
  1862. // The first declaration of a function shall specify the
  1863. // carries_dependency attribute for its declarator-id if any declaration
  1864. // of the function specifies the carries_dependency attribute.
  1865. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  1866. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  1867. S.Diag(CDA->getLocation(),
  1868. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  1869. // Find the first declaration of the parameter.
  1870. // FIXME: Should we build redeclaration chains for function parameters?
  1871. const FunctionDecl *FirstFD =
  1872. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  1873. const ParmVarDecl *FirstVD =
  1874. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  1875. S.Diag(FirstVD->getLocation(),
  1876. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  1877. }
  1878. if (!oldDecl->hasAttrs())
  1879. return;
  1880. bool foundAny = newDecl->hasAttrs();
  1881. // Ensure that any moving of objects within the allocated map is
  1882. // done before we process them.
  1883. if (!foundAny) newDecl->setAttrs(AttrVec());
  1884. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  1885. if (!DeclHasAttr(newDecl, I)) {
  1886. InheritableAttr *newAttr =
  1887. cast<InheritableParamAttr>(I->clone(S.Context));
  1888. newAttr->setInherited(true);
  1889. newDecl->addAttr(newAttr);
  1890. foundAny = true;
  1891. }
  1892. }
  1893. if (!foundAny) newDecl->dropAttrs();
  1894. }
  1895. namespace {
  1896. /// Used in MergeFunctionDecl to keep track of function parameters in
  1897. /// C.
  1898. struct GNUCompatibleParamWarning {
  1899. ParmVarDecl *OldParm;
  1900. ParmVarDecl *NewParm;
  1901. QualType PromotedType;
  1902. };
  1903. }
  1904. /// getSpecialMember - get the special member enum for a method.
  1905. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  1906. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  1907. if (Ctor->isDefaultConstructor())
  1908. return Sema::CXXDefaultConstructor;
  1909. if (Ctor->isCopyConstructor())
  1910. return Sema::CXXCopyConstructor;
  1911. if (Ctor->isMoveConstructor())
  1912. return Sema::CXXMoveConstructor;
  1913. } else if (isa<CXXDestructorDecl>(MD)) {
  1914. return Sema::CXXDestructor;
  1915. } else if (MD->isCopyAssignmentOperator()) {
  1916. return Sema::CXXCopyAssignment;
  1917. } else if (MD->isMoveAssignmentOperator()) {
  1918. return Sema::CXXMoveAssignment;
  1919. }
  1920. return Sema::CXXInvalid;
  1921. }
  1922. /// canRedefineFunction - checks if a function can be redefined. Currently,
  1923. /// only extern inline functions can be redefined, and even then only in
  1924. /// GNU89 mode.
  1925. static bool canRedefineFunction(const FunctionDecl *FD,
  1926. const LangOptions& LangOpts) {
  1927. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  1928. !LangOpts.CPlusPlus &&
  1929. FD->isInlineSpecified() &&
  1930. FD->getStorageClass() == SC_Extern);
  1931. }
  1932. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  1933. const AttributedType *AT = T->getAs<AttributedType>();
  1934. while (AT && !AT->isCallingConv())
  1935. AT = AT->getModifiedType()->getAs<AttributedType>();
  1936. return AT;
  1937. }
  1938. template <typename T>
  1939. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  1940. const DeclContext *DC = Old->getDeclContext();
  1941. if (DC->isRecord())
  1942. return false;
  1943. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  1944. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  1945. return true;
  1946. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  1947. return true;
  1948. return false;
  1949. }
  1950. /// MergeFunctionDecl - We just parsed a function 'New' from
  1951. /// declarator D which has the same name and scope as a previous
  1952. /// declaration 'Old'. Figure out how to resolve this situation,
  1953. /// merging decls or emitting diagnostics as appropriate.
  1954. ///
  1955. /// In C++, New and Old must be declarations that are not
  1956. /// overloaded. Use IsOverload to determine whether New and Old are
  1957. /// overloaded, and to select the Old declaration that New should be
  1958. /// merged with.
  1959. ///
  1960. /// Returns true if there was an error, false otherwise.
  1961. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  1962. Scope *S, bool MergeTypeWithOld) {
  1963. // Verify the old decl was also a function.
  1964. FunctionDecl *Old = OldD->getAsFunction();
  1965. if (!Old) {
  1966. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  1967. if (New->getFriendObjectKind()) {
  1968. Diag(New->getLocation(), diag::err_using_decl_friend);
  1969. Diag(Shadow->getTargetDecl()->getLocation(),
  1970. diag::note_using_decl_target);
  1971. Diag(Shadow->getUsingDecl()->getLocation(),
  1972. diag::note_using_decl) << 0;
  1973. return true;
  1974. }
  1975. // C++11 [namespace.udecl]p14:
  1976. // If a function declaration in namespace scope or block scope has the
  1977. // same name and the same parameter-type-list as a function introduced
  1978. // by a using-declaration, and the declarations do not declare the same
  1979. // function, the program is ill-formed.
  1980. // Check whether the two declarations might declare the same function.
  1981. Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl());
  1982. if (Old &&
  1983. !Old->getDeclContext()->getRedeclContext()->Equals(
  1984. New->getDeclContext()->getRedeclContext()) &&
  1985. !(Old->isExternC() && New->isExternC()))
  1986. Old = 0;
  1987. if (!Old) {
  1988. Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  1989. Diag(Shadow->getTargetDecl()->getLocation(),
  1990. diag::note_using_decl_target);
  1991. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  1992. return true;
  1993. }
  1994. OldD = Old;
  1995. } else {
  1996. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1997. << New->getDeclName();
  1998. Diag(OldD->getLocation(), diag::note_previous_definition);
  1999. return true;
  2000. }
  2001. }
  2002. // If the old declaration is invalid, just give up here.
  2003. if (Old->isInvalidDecl())
  2004. return true;
  2005. // Determine whether the previous declaration was a definition,
  2006. // implicit declaration, or a declaration.
  2007. diag::kind PrevDiag;
  2008. SourceLocation OldLocation = Old->getLocation();
  2009. if (Old->isThisDeclarationADefinition())
  2010. PrevDiag = diag::note_previous_definition;
  2011. else if (Old->isImplicit()) {
  2012. PrevDiag = diag::note_previous_implicit_declaration;
  2013. if (OldLocation.isInvalid())
  2014. OldLocation = New->getLocation();
  2015. } else
  2016. PrevDiag = diag::note_previous_declaration;
  2017. // Don't complain about this if we're in GNU89 mode and the old function
  2018. // is an extern inline function.
  2019. // Don't complain about specializations. They are not supposed to have
  2020. // storage classes.
  2021. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2022. New->getStorageClass() == SC_Static &&
  2023. Old->hasExternalFormalLinkage() &&
  2024. !New->getTemplateSpecializationInfo() &&
  2025. !canRedefineFunction(Old, getLangOpts())) {
  2026. if (getLangOpts().MicrosoftExt) {
  2027. Diag(New->getLocation(), diag::warn_static_non_static) << New;
  2028. Diag(OldLocation, PrevDiag);
  2029. } else {
  2030. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2031. Diag(OldLocation, PrevDiag);
  2032. return true;
  2033. }
  2034. }
  2035. // If a function is first declared with a calling convention, but is later
  2036. // declared or defined without one, all following decls assume the calling
  2037. // convention of the first.
  2038. //
  2039. // It's OK if a function is first declared without a calling convention,
  2040. // but is later declared or defined with the default calling convention.
  2041. //
  2042. // To test if either decl has an explicit calling convention, we look for
  2043. // AttributedType sugar nodes on the type as written. If they are missing or
  2044. // were canonicalized away, we assume the calling convention was implicit.
  2045. //
  2046. // Note also that we DO NOT return at this point, because we still have
  2047. // other tests to run.
  2048. QualType OldQType = Context.getCanonicalType(Old->getType());
  2049. QualType NewQType = Context.getCanonicalType(New->getType());
  2050. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2051. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2052. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2053. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2054. bool RequiresAdjustment = false;
  2055. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2056. FunctionDecl *First = Old->getFirstDecl();
  2057. const FunctionType *FT =
  2058. First->getType().getCanonicalType()->castAs<FunctionType>();
  2059. FunctionType::ExtInfo FI = FT->getExtInfo();
  2060. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2061. if (!NewCCExplicit) {
  2062. // Inherit the CC from the previous declaration if it was specified
  2063. // there but not here.
  2064. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2065. RequiresAdjustment = true;
  2066. } else {
  2067. // Calling conventions aren't compatible, so complain.
  2068. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2069. Diag(New->getLocation(), diag::err_cconv_change)
  2070. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2071. << !FirstCCExplicit
  2072. << (!FirstCCExplicit ? "" :
  2073. FunctionType::getNameForCallConv(FI.getCC()));
  2074. // Put the note on the first decl, since it is the one that matters.
  2075. Diag(First->getLocation(), diag::note_previous_declaration);
  2076. return true;
  2077. }
  2078. }
  2079. // FIXME: diagnose the other way around?
  2080. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2081. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2082. RequiresAdjustment = true;
  2083. }
  2084. // Merge regparm attribute.
  2085. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2086. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2087. if (NewTypeInfo.getHasRegParm()) {
  2088. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2089. << NewType->getRegParmType()
  2090. << OldType->getRegParmType();
  2091. Diag(OldLocation, diag::note_previous_declaration);
  2092. return true;
  2093. }
  2094. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2095. RequiresAdjustment = true;
  2096. }
  2097. // Merge ns_returns_retained attribute.
  2098. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2099. if (NewTypeInfo.getProducesResult()) {
  2100. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  2101. Diag(OldLocation, diag::note_previous_declaration);
  2102. return true;
  2103. }
  2104. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2105. RequiresAdjustment = true;
  2106. }
  2107. if (RequiresAdjustment) {
  2108. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2109. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2110. New->setType(QualType(AdjustedType, 0));
  2111. NewQType = Context.getCanonicalType(New->getType());
  2112. NewType = cast<FunctionType>(NewQType);
  2113. }
  2114. // If this redeclaration makes the function inline, we may need to add it to
  2115. // UndefinedButUsed.
  2116. if (!Old->isInlined() && New->isInlined() &&
  2117. !New->hasAttr<GNUInlineAttr>() &&
  2118. (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
  2119. Old->isUsed(false) &&
  2120. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2121. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2122. SourceLocation()));
  2123. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2124. // about it.
  2125. if (New->hasAttr<GNUInlineAttr>() &&
  2126. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2127. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2128. }
  2129. if (getLangOpts().CPlusPlus) {
  2130. // (C++98 13.1p2):
  2131. // Certain function declarations cannot be overloaded:
  2132. // -- Function declarations that differ only in the return type
  2133. // cannot be overloaded.
  2134. // Go back to the type source info to compare the declared return types,
  2135. // per C++1y [dcl.type.auto]p13:
  2136. // Redeclarations or specializations of a function or function template
  2137. // with a declared return type that uses a placeholder type shall also
  2138. // use that placeholder, not a deduced type.
  2139. QualType OldDeclaredReturnType =
  2140. (Old->getTypeSourceInfo()
  2141. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2142. : OldType)->getReturnType();
  2143. QualType NewDeclaredReturnType =
  2144. (New->getTypeSourceInfo()
  2145. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2146. : NewType)->getReturnType();
  2147. QualType ResQT;
  2148. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2149. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2150. New->isLocalExternDecl())) {
  2151. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2152. OldDeclaredReturnType->isObjCObjectPointerType())
  2153. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2154. if (ResQT.isNull()) {
  2155. if (New->isCXXClassMember() && New->isOutOfLine())
  2156. Diag(New->getLocation(),
  2157. diag::err_member_def_does_not_match_ret_type) << New;
  2158. else
  2159. Diag(New->getLocation(), diag::err_ovl_diff_return_type);
  2160. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2161. return true;
  2162. }
  2163. else
  2164. NewQType = ResQT;
  2165. }
  2166. QualType OldReturnType = OldType->getReturnType();
  2167. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2168. if (OldReturnType != NewReturnType) {
  2169. // If this function has a deduced return type and has already been
  2170. // defined, copy the deduced value from the old declaration.
  2171. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2172. if (OldAT && OldAT->isDeduced()) {
  2173. New->setType(
  2174. SubstAutoType(New->getType(),
  2175. OldAT->isDependentType() ? Context.DependentTy
  2176. : OldAT->getDeducedType()));
  2177. NewQType = Context.getCanonicalType(
  2178. SubstAutoType(NewQType,
  2179. OldAT->isDependentType() ? Context.DependentTy
  2180. : OldAT->getDeducedType()));
  2181. }
  2182. }
  2183. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2184. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2185. if (OldMethod && NewMethod) {
  2186. // Preserve triviality.
  2187. NewMethod->setTrivial(OldMethod->isTrivial());
  2188. // MSVC allows explicit template specialization at class scope:
  2189. // 2 CXXMethodDecls referring to the same function will be injected.
  2190. // We don't want a redeclaration error.
  2191. bool IsClassScopeExplicitSpecialization =
  2192. OldMethod->isFunctionTemplateSpecialization() &&
  2193. NewMethod->isFunctionTemplateSpecialization();
  2194. bool isFriend = NewMethod->getFriendObjectKind();
  2195. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2196. !IsClassScopeExplicitSpecialization) {
  2197. // -- Member function declarations with the same name and the
  2198. // same parameter types cannot be overloaded if any of them
  2199. // is a static member function declaration.
  2200. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2201. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2202. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2203. return true;
  2204. }
  2205. // C++ [class.mem]p1:
  2206. // [...] A member shall not be declared twice in the
  2207. // member-specification, except that a nested class or member
  2208. // class template can be declared and then later defined.
  2209. if (ActiveTemplateInstantiations.empty()) {
  2210. unsigned NewDiag;
  2211. if (isa<CXXConstructorDecl>(OldMethod))
  2212. NewDiag = diag::err_constructor_redeclared;
  2213. else if (isa<CXXDestructorDecl>(NewMethod))
  2214. NewDiag = diag::err_destructor_redeclared;
  2215. else if (isa<CXXConversionDecl>(NewMethod))
  2216. NewDiag = diag::err_conv_function_redeclared;
  2217. else
  2218. NewDiag = diag::err_member_redeclared;
  2219. Diag(New->getLocation(), NewDiag);
  2220. } else {
  2221. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2222. << New << New->getType();
  2223. }
  2224. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2225. // Complain if this is an explicit declaration of a special
  2226. // member that was initially declared implicitly.
  2227. //
  2228. // As an exception, it's okay to befriend such methods in order
  2229. // to permit the implicit constructor/destructor/operator calls.
  2230. } else if (OldMethod->isImplicit()) {
  2231. if (isFriend) {
  2232. NewMethod->setImplicit();
  2233. } else {
  2234. Diag(NewMethod->getLocation(),
  2235. diag::err_definition_of_implicitly_declared_member)
  2236. << New << getSpecialMember(OldMethod);
  2237. return true;
  2238. }
  2239. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  2240. Diag(NewMethod->getLocation(),
  2241. diag::err_definition_of_explicitly_defaulted_member)
  2242. << getSpecialMember(OldMethod);
  2243. return true;
  2244. }
  2245. }
  2246. // C++11 [dcl.attr.noreturn]p1:
  2247. // The first declaration of a function shall specify the noreturn
  2248. // attribute if any declaration of that function specifies the noreturn
  2249. // attribute.
  2250. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2251. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2252. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2253. Diag(Old->getFirstDecl()->getLocation(),
  2254. diag::note_noreturn_missing_first_decl);
  2255. }
  2256. // C++11 [dcl.attr.depend]p2:
  2257. // The first declaration of a function shall specify the
  2258. // carries_dependency attribute for its declarator-id if any declaration
  2259. // of the function specifies the carries_dependency attribute.
  2260. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2261. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2262. Diag(CDA->getLocation(),
  2263. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2264. Diag(Old->getFirstDecl()->getLocation(),
  2265. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2266. }
  2267. // (C++98 8.3.5p3):
  2268. // All declarations for a function shall agree exactly in both the
  2269. // return type and the parameter-type-list.
  2270. // We also want to respect all the extended bits except noreturn.
  2271. // noreturn should now match unless the old type info didn't have it.
  2272. QualType OldQTypeForComparison = OldQType;
  2273. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2274. assert(OldQType == QualType(OldType, 0));
  2275. const FunctionType *OldTypeForComparison
  2276. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2277. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2278. assert(OldQTypeForComparison.isCanonical());
  2279. }
  2280. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2281. // As a special case, retain the language linkage from previous
  2282. // declarations of a friend function as an extension.
  2283. //
  2284. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2285. // and is useful because there's otherwise no way to specify language
  2286. // linkage within class scope.
  2287. //
  2288. // Check cautiously as the friend object kind isn't yet complete.
  2289. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2290. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2291. Diag(OldLocation, PrevDiag);
  2292. } else {
  2293. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2294. Diag(OldLocation, PrevDiag);
  2295. return true;
  2296. }
  2297. }
  2298. if (OldQTypeForComparison == NewQType)
  2299. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2300. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2301. New->isLocalExternDecl()) {
  2302. // It's OK if we couldn't merge types for a local function declaraton
  2303. // if either the old or new type is dependent. We'll merge the types
  2304. // when we instantiate the function.
  2305. return false;
  2306. }
  2307. // Fall through for conflicting redeclarations and redefinitions.
  2308. }
  2309. // C: Function types need to be compatible, not identical. This handles
  2310. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2311. if (!getLangOpts().CPlusPlus &&
  2312. Context.typesAreCompatible(OldQType, NewQType)) {
  2313. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2314. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2315. const FunctionProtoType *OldProto = 0;
  2316. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2317. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2318. // The old declaration provided a function prototype, but the
  2319. // new declaration does not. Merge in the prototype.
  2320. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2321. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2322. NewQType =
  2323. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2324. OldProto->getExtProtoInfo());
  2325. New->setType(NewQType);
  2326. New->setHasInheritedPrototype();
  2327. // Synthesize parameters with the same types.
  2328. SmallVector<ParmVarDecl*, 16> Params;
  2329. for (const auto &ParamType : OldProto->param_types()) {
  2330. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2331. SourceLocation(), 0, ParamType,
  2332. /*TInfo=*/0, SC_None, 0);
  2333. Param->setScopeInfo(0, Params.size());
  2334. Param->setImplicit();
  2335. Params.push_back(Param);
  2336. }
  2337. New->setParams(Params);
  2338. }
  2339. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2340. }
  2341. // GNU C permits a K&R definition to follow a prototype declaration
  2342. // if the declared types of the parameters in the K&R definition
  2343. // match the types in the prototype declaration, even when the
  2344. // promoted types of the parameters from the K&R definition differ
  2345. // from the types in the prototype. GCC then keeps the types from
  2346. // the prototype.
  2347. //
  2348. // If a variadic prototype is followed by a non-variadic K&R definition,
  2349. // the K&R definition becomes variadic. This is sort of an edge case, but
  2350. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2351. // C99 6.9.1p8.
  2352. if (!getLangOpts().CPlusPlus &&
  2353. Old->hasPrototype() && !New->hasPrototype() &&
  2354. New->getType()->getAs<FunctionProtoType>() &&
  2355. Old->getNumParams() == New->getNumParams()) {
  2356. SmallVector<QualType, 16> ArgTypes;
  2357. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2358. const FunctionProtoType *OldProto
  2359. = Old->getType()->getAs<FunctionProtoType>();
  2360. const FunctionProtoType *NewProto
  2361. = New->getType()->getAs<FunctionProtoType>();
  2362. // Determine whether this is the GNU C extension.
  2363. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2364. NewProto->getReturnType());
  2365. bool LooseCompatible = !MergedReturn.isNull();
  2366. for (unsigned Idx = 0, End = Old->getNumParams();
  2367. LooseCompatible && Idx != End; ++Idx) {
  2368. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2369. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2370. if (Context.typesAreCompatible(OldParm->getType(),
  2371. NewProto->getParamType(Idx))) {
  2372. ArgTypes.push_back(NewParm->getType());
  2373. } else if (Context.typesAreCompatible(OldParm->getType(),
  2374. NewParm->getType(),
  2375. /*CompareUnqualified=*/true)) {
  2376. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2377. NewProto->getParamType(Idx) };
  2378. Warnings.push_back(Warn);
  2379. ArgTypes.push_back(NewParm->getType());
  2380. } else
  2381. LooseCompatible = false;
  2382. }
  2383. if (LooseCompatible) {
  2384. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  2385. Diag(Warnings[Warn].NewParm->getLocation(),
  2386. diag::ext_param_promoted_not_compatible_with_prototype)
  2387. << Warnings[Warn].PromotedType
  2388. << Warnings[Warn].OldParm->getType();
  2389. if (Warnings[Warn].OldParm->getLocation().isValid())
  2390. Diag(Warnings[Warn].OldParm->getLocation(),
  2391. diag::note_previous_declaration);
  2392. }
  2393. if (MergeTypeWithOld)
  2394. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  2395. OldProto->getExtProtoInfo()));
  2396. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2397. }
  2398. // Fall through to diagnose conflicting types.
  2399. }
  2400. // A function that has already been declared has been redeclared or
  2401. // defined with a different type; show an appropriate diagnostic.
  2402. // If the previous declaration was an implicitly-generated builtin
  2403. // declaration, then at the very least we should use a specialized note.
  2404. unsigned BuiltinID;
  2405. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  2406. // If it's actually a library-defined builtin function like 'malloc'
  2407. // or 'printf', just warn about the incompatible redeclaration.
  2408. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  2409. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2410. Diag(OldLocation, diag::note_previous_builtin_declaration)
  2411. << Old << Old->getType();
  2412. // If this is a global redeclaration, just forget hereafter
  2413. // about the "builtin-ness" of the function.
  2414. //
  2415. // Doing this for local extern declarations is problematic. If
  2416. // the builtin declaration remains visible, a second invalid
  2417. // local declaration will produce a hard error; if it doesn't
  2418. // remain visible, a single bogus local redeclaration (which is
  2419. // actually only a warning) could break all the downstream code.
  2420. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  2421. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2422. return false;
  2423. }
  2424. PrevDiag = diag::note_previous_builtin_declaration;
  2425. }
  2426. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2427. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2428. return true;
  2429. }
  2430. /// \brief Completes the merge of two function declarations that are
  2431. /// known to be compatible.
  2432. ///
  2433. /// This routine handles the merging of attributes and other
  2434. /// properties of function declarations from the old declaration to
  2435. /// the new declaration, once we know that New is in fact a
  2436. /// redeclaration of Old.
  2437. ///
  2438. /// \returns false
  2439. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2440. Scope *S, bool MergeTypeWithOld) {
  2441. // Merge the attributes
  2442. mergeDeclAttributes(New, Old);
  2443. // Merge "pure" flag.
  2444. if (Old->isPure())
  2445. New->setPure();
  2446. // Merge "used" flag.
  2447. if (Old->getMostRecentDecl()->isUsed(false))
  2448. New->setIsUsed();
  2449. // Merge attributes from the parameters. These can mismatch with K&R
  2450. // declarations.
  2451. if (New->getNumParams() == Old->getNumParams())
  2452. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
  2453. mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
  2454. *this);
  2455. if (getLangOpts().CPlusPlus)
  2456. return MergeCXXFunctionDecl(New, Old, S);
  2457. // Merge the function types so the we get the composite types for the return
  2458. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  2459. // was visible.
  2460. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  2461. if (!Merged.isNull() && MergeTypeWithOld)
  2462. New->setType(Merged);
  2463. return false;
  2464. }
  2465. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2466. ObjCMethodDecl *oldMethod) {
  2467. // Merge the attributes, including deprecated/unavailable
  2468. AvailabilityMergeKind MergeKind =
  2469. isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  2470. : AMK_Override;
  2471. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  2472. // Merge attributes from the parameters.
  2473. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2474. oe = oldMethod->param_end();
  2475. for (ObjCMethodDecl::param_iterator
  2476. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2477. ni != ne && oi != oe; ++ni, ++oi)
  2478. mergeParamDeclAttributes(*ni, *oi, *this);
  2479. CheckObjCMethodOverride(newMethod, oldMethod);
  2480. }
  2481. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2482. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2483. /// emitting diagnostics as appropriate.
  2484. ///
  2485. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2486. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2487. /// is attached.
  2488. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  2489. bool MergeTypeWithOld) {
  2490. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2491. return;
  2492. QualType MergedT;
  2493. if (getLangOpts().CPlusPlus) {
  2494. if (New->getType()->isUndeducedType()) {
  2495. // We don't know what the new type is until the initializer is attached.
  2496. return;
  2497. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2498. // These could still be something that needs exception specs checked.
  2499. return MergeVarDeclExceptionSpecs(New, Old);
  2500. }
  2501. // C++ [basic.link]p10:
  2502. // [...] the types specified by all declarations referring to a given
  2503. // object or function shall be identical, except that declarations for an
  2504. // array object can specify array types that differ by the presence or
  2505. // absence of a major array bound (8.3.4).
  2506. else if (Old->getType()->isIncompleteArrayType() &&
  2507. New->getType()->isArrayType()) {
  2508. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2509. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2510. if (Context.hasSameType(OldArray->getElementType(),
  2511. NewArray->getElementType()))
  2512. MergedT = New->getType();
  2513. } else if (Old->getType()->isArrayType() &&
  2514. New->getType()->isIncompleteArrayType()) {
  2515. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  2516. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  2517. if (Context.hasSameType(OldArray->getElementType(),
  2518. NewArray->getElementType()))
  2519. MergedT = Old->getType();
  2520. } else if (New->getType()->isObjCObjectPointerType() &&
  2521. Old->getType()->isObjCObjectPointerType()) {
  2522. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2523. Old->getType());
  2524. }
  2525. } else {
  2526. // C 6.2.7p2:
  2527. // All declarations that refer to the same object or function shall have
  2528. // compatible type.
  2529. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2530. }
  2531. if (MergedT.isNull()) {
  2532. // It's OK if we couldn't merge types if either type is dependent, for a
  2533. // block-scope variable. In other cases (static data members of class
  2534. // templates, variable templates, ...), we require the types to be
  2535. // equivalent.
  2536. // FIXME: The C++ standard doesn't say anything about this.
  2537. if ((New->getType()->isDependentType() ||
  2538. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  2539. // If the old type was dependent, we can't merge with it, so the new type
  2540. // becomes dependent for now. We'll reproduce the original type when we
  2541. // instantiate the TypeSourceInfo for the variable.
  2542. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  2543. New->setType(Context.DependentTy);
  2544. return;
  2545. }
  2546. // FIXME: Even if this merging succeeds, some other non-visible declaration
  2547. // of this variable might have an incompatible type. For instance:
  2548. //
  2549. // extern int arr[];
  2550. // void f() { extern int arr[2]; }
  2551. // void g() { extern int arr[3]; }
  2552. //
  2553. // Neither C nor C++ requires a diagnostic for this, but we should still try
  2554. // to diagnose it.
  2555. Diag(New->getLocation(), diag::err_redefinition_different_type)
  2556. << New->getDeclName() << New->getType() << Old->getType();
  2557. Diag(Old->getLocation(), diag::note_previous_definition);
  2558. return New->setInvalidDecl();
  2559. }
  2560. // Don't actually update the type on the new declaration if the old
  2561. // declaration was an extern declaration in a different scope.
  2562. if (MergeTypeWithOld)
  2563. New->setType(MergedT);
  2564. }
  2565. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  2566. LookupResult &Previous) {
  2567. // C11 6.2.7p4:
  2568. // For an identifier with internal or external linkage declared
  2569. // in a scope in which a prior declaration of that identifier is
  2570. // visible, if the prior declaration specifies internal or
  2571. // external linkage, the type of the identifier at the later
  2572. // declaration becomes the composite type.
  2573. //
  2574. // If the variable isn't visible, we do not merge with its type.
  2575. if (Previous.isShadowed())
  2576. return false;
  2577. if (S.getLangOpts().CPlusPlus) {
  2578. // C++11 [dcl.array]p3:
  2579. // If there is a preceding declaration of the entity in the same
  2580. // scope in which the bound was specified, an omitted array bound
  2581. // is taken to be the same as in that earlier declaration.
  2582. return NewVD->isPreviousDeclInSameBlockScope() ||
  2583. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  2584. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  2585. } else {
  2586. // If the old declaration was function-local, don't merge with its
  2587. // type unless we're in the same function.
  2588. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  2589. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  2590. }
  2591. }
  2592. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2593. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2594. /// situation, merging decls or emitting diagnostics as appropriate.
  2595. ///
  2596. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2597. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2598. /// definitions here, since the initializer hasn't been attached.
  2599. ///
  2600. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  2601. // If the new decl is already invalid, don't do any other checking.
  2602. if (New->isInvalidDecl())
  2603. return;
  2604. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  2605. // Verify the old decl was also a variable or variable template.
  2606. VarDecl *Old = 0;
  2607. VarTemplateDecl *OldTemplate = 0;
  2608. if (Previous.isSingleResult()) {
  2609. if (NewTemplate) {
  2610. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  2611. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
  2612. } else
  2613. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  2614. }
  2615. if (!Old) {
  2616. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2617. << New->getDeclName();
  2618. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2619. diag::note_previous_definition);
  2620. return New->setInvalidDecl();
  2621. }
  2622. if (!shouldLinkPossiblyHiddenDecl(Old, New))
  2623. return;
  2624. // Ensure the template parameters are compatible.
  2625. if (NewTemplate &&
  2626. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  2627. OldTemplate->getTemplateParameters(),
  2628. /*Complain=*/true, TPL_TemplateMatch))
  2629. return;
  2630. // C++ [class.mem]p1:
  2631. // A member shall not be declared twice in the member-specification [...]
  2632. //
  2633. // Here, we need only consider static data members.
  2634. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  2635. Diag(New->getLocation(), diag::err_duplicate_member)
  2636. << New->getIdentifier();
  2637. Diag(Old->getLocation(), diag::note_previous_declaration);
  2638. New->setInvalidDecl();
  2639. }
  2640. mergeDeclAttributes(New, Old);
  2641. // Warn if an already-declared variable is made a weak_import in a subsequent
  2642. // declaration
  2643. if (New->hasAttr<WeakImportAttr>() &&
  2644. Old->getStorageClass() == SC_None &&
  2645. !Old->hasAttr<WeakImportAttr>()) {
  2646. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  2647. Diag(Old->getLocation(), diag::note_previous_definition);
  2648. // Remove weak_import attribute on new declaration.
  2649. New->dropAttr<WeakImportAttr>();
  2650. }
  2651. // Merge the types.
  2652. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  2653. if (New->isInvalidDecl())
  2654. return;
  2655. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  2656. if (New->getStorageClass() == SC_Static &&
  2657. !New->isStaticDataMember() &&
  2658. Old->hasExternalFormalLinkage()) {
  2659. Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
  2660. Diag(Old->getLocation(), diag::note_previous_definition);
  2661. return New->setInvalidDecl();
  2662. }
  2663. // C99 6.2.2p4:
  2664. // For an identifier declared with the storage-class specifier
  2665. // extern in a scope in which a prior declaration of that
  2666. // identifier is visible,23) if the prior declaration specifies
  2667. // internal or external linkage, the linkage of the identifier at
  2668. // the later declaration is the same as the linkage specified at
  2669. // the prior declaration. If no prior declaration is visible, or
  2670. // if the prior declaration specifies no linkage, then the
  2671. // identifier has external linkage.
  2672. if (New->hasExternalStorage() && Old->hasLinkage())
  2673. /* Okay */;
  2674. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  2675. !New->isStaticDataMember() &&
  2676. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  2677. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  2678. Diag(Old->getLocation(), diag::note_previous_definition);
  2679. return New->setInvalidDecl();
  2680. }
  2681. // Check if extern is followed by non-extern and vice-versa.
  2682. if (New->hasExternalStorage() &&
  2683. !Old->hasLinkage() && Old->isLocalVarDecl()) {
  2684. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  2685. Diag(Old->getLocation(), diag::note_previous_definition);
  2686. return New->setInvalidDecl();
  2687. }
  2688. if (Old->hasLinkage() && New->isLocalVarDecl() &&
  2689. !New->hasExternalStorage()) {
  2690. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  2691. Diag(Old->getLocation(), diag::note_previous_definition);
  2692. return New->setInvalidDecl();
  2693. }
  2694. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  2695. // FIXME: The test for external storage here seems wrong? We still
  2696. // need to check for mismatches.
  2697. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  2698. // Don't complain about out-of-line definitions of static members.
  2699. !(Old->getLexicalDeclContext()->isRecord() &&
  2700. !New->getLexicalDeclContext()->isRecord())) {
  2701. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  2702. Diag(Old->getLocation(), diag::note_previous_definition);
  2703. return New->setInvalidDecl();
  2704. }
  2705. if (New->getTLSKind() != Old->getTLSKind()) {
  2706. if (!Old->getTLSKind()) {
  2707. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  2708. Diag(Old->getLocation(), diag::note_previous_declaration);
  2709. } else if (!New->getTLSKind()) {
  2710. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  2711. Diag(Old->getLocation(), diag::note_previous_declaration);
  2712. } else {
  2713. // Do not allow redeclaration to change the variable between requiring
  2714. // static and dynamic initialization.
  2715. // FIXME: GCC allows this, but uses the TLS keyword on the first
  2716. // declaration to determine the kind. Do we need to be compatible here?
  2717. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  2718. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  2719. Diag(Old->getLocation(), diag::note_previous_declaration);
  2720. }
  2721. }
  2722. // C++ doesn't have tentative definitions, so go right ahead and check here.
  2723. const VarDecl *Def;
  2724. if (getLangOpts().CPlusPlus &&
  2725. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  2726. (Def = Old->getDefinition())) {
  2727. Diag(New->getLocation(), diag::err_redefinition) << New;
  2728. Diag(Def->getLocation(), diag::note_previous_definition);
  2729. New->setInvalidDecl();
  2730. return;
  2731. }
  2732. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2733. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2734. Diag(Old->getLocation(), diag::note_previous_definition);
  2735. New->setInvalidDecl();
  2736. return;
  2737. }
  2738. // Merge "used" flag.
  2739. if (Old->getMostRecentDecl()->isUsed(false))
  2740. New->setIsUsed();
  2741. // Keep a chain of previous declarations.
  2742. New->setPreviousDecl(Old);
  2743. if (NewTemplate)
  2744. NewTemplate->setPreviousDecl(OldTemplate);
  2745. // Inherit access appropriately.
  2746. New->setAccess(Old->getAccess());
  2747. if (NewTemplate)
  2748. NewTemplate->setAccess(New->getAccess());
  2749. }
  2750. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2751. /// no declarator (e.g. "struct foo;") is parsed.
  2752. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2753. DeclSpec &DS) {
  2754. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
  2755. }
  2756. static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) {
  2757. if (!S.Context.getLangOpts().CPlusPlus)
  2758. return;
  2759. if (isa<CXXRecordDecl>(Tag->getParent())) {
  2760. // If this tag is the direct child of a class, number it if
  2761. // it is anonymous.
  2762. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  2763. return;
  2764. MangleNumberingContext &MCtx =
  2765. S.Context.getManglingNumberContext(Tag->getParent());
  2766. S.Context.setManglingNumber(
  2767. Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
  2768. return;
  2769. }
  2770. // If this tag isn't a direct child of a class, number it if it is local.
  2771. Decl *ManglingContextDecl;
  2772. if (MangleNumberingContext *MCtx =
  2773. S.getCurrentMangleNumberContext(Tag->getDeclContext(),
  2774. ManglingContextDecl)) {
  2775. S.Context.setManglingNumber(
  2776. Tag,
  2777. MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber()));
  2778. }
  2779. }
  2780. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2781. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  2782. /// parameters to cope with template friend declarations.
  2783. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2784. DeclSpec &DS,
  2785. MultiTemplateParamsArg TemplateParams,
  2786. bool IsExplicitInstantiation) {
  2787. Decl *TagD = 0;
  2788. TagDecl *Tag = 0;
  2789. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  2790. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  2791. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  2792. DS.getTypeSpecType() == DeclSpec::TST_union ||
  2793. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  2794. TagD = DS.getRepAsDecl();
  2795. if (!TagD) // We probably had an error
  2796. return 0;
  2797. // Note that the above type specs guarantee that the
  2798. // type rep is a Decl, whereas in many of the others
  2799. // it's a Type.
  2800. if (isa<TagDecl>(TagD))
  2801. Tag = cast<TagDecl>(TagD);
  2802. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  2803. Tag = CTD->getTemplatedDecl();
  2804. }
  2805. if (Tag) {
  2806. HandleTagNumbering(*this, Tag, S);
  2807. Tag->setFreeStanding();
  2808. if (Tag->isInvalidDecl())
  2809. return Tag;
  2810. }
  2811. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  2812. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  2813. // or incomplete types shall not be restrict-qualified."
  2814. if (TypeQuals & DeclSpec::TQ_restrict)
  2815. Diag(DS.getRestrictSpecLoc(),
  2816. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  2817. << DS.getSourceRange();
  2818. }
  2819. if (DS.isConstexprSpecified()) {
  2820. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  2821. // and definitions of functions and variables.
  2822. if (Tag)
  2823. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  2824. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2825. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2826. DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
  2827. DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
  2828. else
  2829. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  2830. // Don't emit warnings after this error.
  2831. return TagD;
  2832. }
  2833. DiagnoseFunctionSpecifiers(DS);
  2834. if (DS.isFriendSpecified()) {
  2835. // If we're dealing with a decl but not a TagDecl, assume that
  2836. // whatever routines created it handled the friendship aspect.
  2837. if (TagD && !Tag)
  2838. return 0;
  2839. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  2840. }
  2841. CXXScopeSpec &SS = DS.getTypeSpecScope();
  2842. bool IsExplicitSpecialization =
  2843. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  2844. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  2845. !IsExplicitInstantiation && !IsExplicitSpecialization) {
  2846. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  2847. // nested-name-specifier unless it is an explicit instantiation
  2848. // or an explicit specialization.
  2849. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  2850. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  2851. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2852. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2853. DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
  2854. DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
  2855. << SS.getRange();
  2856. return 0;
  2857. }
  2858. // Track whether this decl-specifier declares anything.
  2859. bool DeclaresAnything = true;
  2860. // Handle anonymous struct definitions.
  2861. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  2862. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  2863. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  2864. if (getLangOpts().CPlusPlus ||
  2865. Record->getDeclContext()->isRecord())
  2866. return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
  2867. DeclaresAnything = false;
  2868. }
  2869. }
  2870. // Check for Microsoft C extension: anonymous struct member.
  2871. if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
  2872. CurContext->isRecord() &&
  2873. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  2874. // Handle 2 kinds of anonymous struct:
  2875. // struct STRUCT;
  2876. // and
  2877. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  2878. RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
  2879. if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
  2880. (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  2881. DS.getRepAsType().get()->isStructureType())) {
  2882. Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
  2883. << DS.getSourceRange();
  2884. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  2885. }
  2886. }
  2887. // Skip all the checks below if we have a type error.
  2888. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  2889. (TagD && TagD->isInvalidDecl()))
  2890. return TagD;
  2891. if (getLangOpts().CPlusPlus &&
  2892. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  2893. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  2894. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  2895. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  2896. DeclaresAnything = false;
  2897. if (!DS.isMissingDeclaratorOk()) {
  2898. // Customize diagnostic for a typedef missing a name.
  2899. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  2900. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  2901. << DS.getSourceRange();
  2902. else
  2903. DeclaresAnything = false;
  2904. }
  2905. if (DS.isModulePrivateSpecified() &&
  2906. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  2907. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  2908. << Tag->getTagKind()
  2909. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  2910. ActOnDocumentableDecl(TagD);
  2911. // C 6.7/2:
  2912. // A declaration [...] shall declare at least a declarator [...], a tag,
  2913. // or the members of an enumeration.
  2914. // C++ [dcl.dcl]p3:
  2915. // [If there are no declarators], and except for the declaration of an
  2916. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  2917. // names into the program, or shall redeclare a name introduced by a
  2918. // previous declaration.
  2919. if (!DeclaresAnything) {
  2920. // In C, we allow this as a (popular) extension / bug. Don't bother
  2921. // producing further diagnostics for redundant qualifiers after this.
  2922. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  2923. return TagD;
  2924. }
  2925. // C++ [dcl.stc]p1:
  2926. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  2927. // init-declarator-list of the declaration shall not be empty.
  2928. // C++ [dcl.fct.spec]p1:
  2929. // If a cv-qualifier appears in a decl-specifier-seq, the
  2930. // init-declarator-list of the declaration shall not be empty.
  2931. //
  2932. // Spurious qualifiers here appear to be valid in C.
  2933. unsigned DiagID = diag::warn_standalone_specifier;
  2934. if (getLangOpts().CPlusPlus)
  2935. DiagID = diag::ext_standalone_specifier;
  2936. // Note that a linkage-specification sets a storage class, but
  2937. // 'extern "C" struct foo;' is actually valid and not theoretically
  2938. // useless.
  2939. if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
  2940. if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  2941. Diag(DS.getStorageClassSpecLoc(), DiagID)
  2942. << DeclSpec::getSpecifierName(SCS);
  2943. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  2944. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  2945. << DeclSpec::getSpecifierName(TSCS);
  2946. if (DS.getTypeQualifiers()) {
  2947. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2948. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  2949. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2950. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  2951. // Restrict is covered above.
  2952. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  2953. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  2954. }
  2955. // Warn about ignored type attributes, for example:
  2956. // __attribute__((aligned)) struct A;
  2957. // Attributes should be placed after tag to apply to type declaration.
  2958. if (!DS.getAttributes().empty()) {
  2959. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  2960. if (TypeSpecType == DeclSpec::TST_class ||
  2961. TypeSpecType == DeclSpec::TST_struct ||
  2962. TypeSpecType == DeclSpec::TST_interface ||
  2963. TypeSpecType == DeclSpec::TST_union ||
  2964. TypeSpecType == DeclSpec::TST_enum) {
  2965. AttributeList* attrs = DS.getAttributes().getList();
  2966. while (attrs) {
  2967. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  2968. << attrs->getName()
  2969. << (TypeSpecType == DeclSpec::TST_class ? 0 :
  2970. TypeSpecType == DeclSpec::TST_struct ? 1 :
  2971. TypeSpecType == DeclSpec::TST_union ? 2 :
  2972. TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
  2973. attrs = attrs->getNext();
  2974. }
  2975. }
  2976. }
  2977. return TagD;
  2978. }
  2979. /// We are trying to inject an anonymous member into the given scope;
  2980. /// check if there's an existing declaration that can't be overloaded.
  2981. ///
  2982. /// \return true if this is a forbidden redeclaration
  2983. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  2984. Scope *S,
  2985. DeclContext *Owner,
  2986. DeclarationName Name,
  2987. SourceLocation NameLoc,
  2988. unsigned diagnostic) {
  2989. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  2990. Sema::ForRedeclaration);
  2991. if (!SemaRef.LookupName(R, S)) return false;
  2992. if (R.getAsSingle<TagDecl>())
  2993. return false;
  2994. // Pick a representative declaration.
  2995. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  2996. assert(PrevDecl && "Expected a non-null Decl");
  2997. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  2998. return false;
  2999. SemaRef.Diag(NameLoc, diagnostic) << Name;
  3000. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3001. return true;
  3002. }
  3003. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3004. /// anonymous struct or union AnonRecord into the owning context Owner
  3005. /// and scope S. This routine will be invoked just after we realize
  3006. /// that an unnamed union or struct is actually an anonymous union or
  3007. /// struct, e.g.,
  3008. ///
  3009. /// @code
  3010. /// union {
  3011. /// int i;
  3012. /// float f;
  3013. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3014. /// // f into the surrounding scope.x
  3015. /// @endcode
  3016. ///
  3017. /// This routine is recursive, injecting the names of nested anonymous
  3018. /// structs/unions into the owning context and scope as well.
  3019. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  3020. DeclContext *Owner,
  3021. RecordDecl *AnonRecord,
  3022. AccessSpecifier AS,
  3023. SmallVectorImpl<NamedDecl *> &Chaining,
  3024. bool MSAnonStruct) {
  3025. unsigned diagKind
  3026. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  3027. : diag::err_anonymous_struct_member_redecl;
  3028. bool Invalid = false;
  3029. // Look every FieldDecl and IndirectFieldDecl with a name.
  3030. for (auto *D : AnonRecord->decls()) {
  3031. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3032. cast<NamedDecl>(D)->getDeclName()) {
  3033. ValueDecl *VD = cast<ValueDecl>(D);
  3034. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3035. VD->getLocation(), diagKind)) {
  3036. // C++ [class.union]p2:
  3037. // The names of the members of an anonymous union shall be
  3038. // distinct from the names of any other entity in the
  3039. // scope in which the anonymous union is declared.
  3040. Invalid = true;
  3041. } else {
  3042. // C++ [class.union]p2:
  3043. // For the purpose of name lookup, after the anonymous union
  3044. // definition, the members of the anonymous union are
  3045. // considered to have been defined in the scope in which the
  3046. // anonymous union is declared.
  3047. unsigned OldChainingSize = Chaining.size();
  3048. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3049. for (auto *PI : IF->chain())
  3050. Chaining.push_back(PI);
  3051. else
  3052. Chaining.push_back(VD);
  3053. assert(Chaining.size() >= 2);
  3054. NamedDecl **NamedChain =
  3055. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3056. for (unsigned i = 0; i < Chaining.size(); i++)
  3057. NamedChain[i] = Chaining[i];
  3058. IndirectFieldDecl* IndirectField =
  3059. IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
  3060. VD->getIdentifier(), VD->getType(),
  3061. NamedChain, Chaining.size());
  3062. IndirectField->setAccess(AS);
  3063. IndirectField->setImplicit();
  3064. SemaRef.PushOnScopeChains(IndirectField, S);
  3065. // That includes picking up the appropriate access specifier.
  3066. if (AS != AS_none) IndirectField->setAccess(AS);
  3067. Chaining.resize(OldChainingSize);
  3068. }
  3069. }
  3070. }
  3071. return Invalid;
  3072. }
  3073. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3074. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3075. /// illegal input values are mapped to SC_None.
  3076. static StorageClass
  3077. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3078. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3079. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3080. "Parser allowed 'typedef' as storage class VarDecl.");
  3081. switch (StorageClassSpec) {
  3082. case DeclSpec::SCS_unspecified: return SC_None;
  3083. case DeclSpec::SCS_extern:
  3084. if (DS.isExternInLinkageSpec())
  3085. return SC_None;
  3086. return SC_Extern;
  3087. case DeclSpec::SCS_static: return SC_Static;
  3088. case DeclSpec::SCS_auto: return SC_Auto;
  3089. case DeclSpec::SCS_register: return SC_Register;
  3090. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3091. // Illegal SCSs map to None: error reporting is up to the caller.
  3092. case DeclSpec::SCS_mutable: // Fall through.
  3093. case DeclSpec::SCS_typedef: return SC_None;
  3094. }
  3095. llvm_unreachable("unknown storage class specifier");
  3096. }
  3097. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3098. assert(Record->hasInClassInitializer());
  3099. for (const auto *I : Record->decls()) {
  3100. const auto *FD = dyn_cast<FieldDecl>(I);
  3101. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3102. FD = IFD->getAnonField();
  3103. if (FD && FD->hasInClassInitializer())
  3104. return FD->getLocation();
  3105. }
  3106. llvm_unreachable("couldn't find in-class initializer");
  3107. }
  3108. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3109. SourceLocation DefaultInitLoc) {
  3110. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3111. return;
  3112. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3113. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3114. }
  3115. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3116. CXXRecordDecl *AnonUnion) {
  3117. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3118. return;
  3119. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3120. }
  3121. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3122. /// anonymous structure or union. Anonymous unions are a C++ feature
  3123. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3124. /// are a C11 feature and GNU C++ extension.
  3125. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3126. AccessSpecifier AS,
  3127. RecordDecl *Record,
  3128. const PrintingPolicy &Policy) {
  3129. DeclContext *Owner = Record->getDeclContext();
  3130. // Diagnose whether this anonymous struct/union is an extension.
  3131. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3132. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3133. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3134. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3135. else if (!Record->isUnion() && !getLangOpts().C11)
  3136. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  3137. // C and C++ require different kinds of checks for anonymous
  3138. // structs/unions.
  3139. bool Invalid = false;
  3140. if (getLangOpts().CPlusPlus) {
  3141. const char* PrevSpec = 0;
  3142. unsigned DiagID;
  3143. if (Record->isUnion()) {
  3144. // C++ [class.union]p6:
  3145. // Anonymous unions declared in a named namespace or in the
  3146. // global namespace shall be declared static.
  3147. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  3148. (isa<TranslationUnitDecl>(Owner) ||
  3149. (isa<NamespaceDecl>(Owner) &&
  3150. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  3151. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  3152. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  3153. // Recover by adding 'static'.
  3154. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  3155. PrevSpec, DiagID, Policy);
  3156. }
  3157. // C++ [class.union]p6:
  3158. // A storage class is not allowed in a declaration of an
  3159. // anonymous union in a class scope.
  3160. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  3161. isa<RecordDecl>(Owner)) {
  3162. Diag(DS.getStorageClassSpecLoc(),
  3163. diag::err_anonymous_union_with_storage_spec)
  3164. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  3165. // Recover by removing the storage specifier.
  3166. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  3167. SourceLocation(),
  3168. PrevSpec, DiagID, Context.getPrintingPolicy());
  3169. }
  3170. }
  3171. // Ignore const/volatile/restrict qualifiers.
  3172. if (DS.getTypeQualifiers()) {
  3173. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3174. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  3175. << Record->isUnion() << "const"
  3176. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  3177. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3178. Diag(DS.getVolatileSpecLoc(),
  3179. diag::ext_anonymous_struct_union_qualified)
  3180. << Record->isUnion() << "volatile"
  3181. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  3182. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  3183. Diag(DS.getRestrictSpecLoc(),
  3184. diag::ext_anonymous_struct_union_qualified)
  3185. << Record->isUnion() << "restrict"
  3186. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  3187. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3188. Diag(DS.getAtomicSpecLoc(),
  3189. diag::ext_anonymous_struct_union_qualified)
  3190. << Record->isUnion() << "_Atomic"
  3191. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  3192. DS.ClearTypeQualifiers();
  3193. }
  3194. // C++ [class.union]p2:
  3195. // The member-specification of an anonymous union shall only
  3196. // define non-static data members. [Note: nested types and
  3197. // functions cannot be declared within an anonymous union. ]
  3198. for (auto *Mem : Record->decls()) {
  3199. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  3200. // C++ [class.union]p3:
  3201. // An anonymous union shall not have private or protected
  3202. // members (clause 11).
  3203. assert(FD->getAccess() != AS_none);
  3204. if (FD->getAccess() != AS_public) {
  3205. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  3206. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  3207. Invalid = true;
  3208. }
  3209. // C++ [class.union]p1
  3210. // An object of a class with a non-trivial constructor, a non-trivial
  3211. // copy constructor, a non-trivial destructor, or a non-trivial copy
  3212. // assignment operator cannot be a member of a union, nor can an
  3213. // array of such objects.
  3214. if (CheckNontrivialField(FD))
  3215. Invalid = true;
  3216. } else if (Mem->isImplicit()) {
  3217. // Any implicit members are fine.
  3218. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  3219. // This is a type that showed up in an
  3220. // elaborated-type-specifier inside the anonymous struct or
  3221. // union, but which actually declares a type outside of the
  3222. // anonymous struct or union. It's okay.
  3223. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  3224. if (!MemRecord->isAnonymousStructOrUnion() &&
  3225. MemRecord->getDeclName()) {
  3226. // Visual C++ allows type definition in anonymous struct or union.
  3227. if (getLangOpts().MicrosoftExt)
  3228. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  3229. << (int)Record->isUnion();
  3230. else {
  3231. // This is a nested type declaration.
  3232. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  3233. << (int)Record->isUnion();
  3234. Invalid = true;
  3235. }
  3236. } else {
  3237. // This is an anonymous type definition within another anonymous type.
  3238. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  3239. // not part of standard C++.
  3240. Diag(MemRecord->getLocation(),
  3241. diag::ext_anonymous_record_with_anonymous_type)
  3242. << (int)Record->isUnion();
  3243. }
  3244. } else if (isa<AccessSpecDecl>(Mem)) {
  3245. // Any access specifier is fine.
  3246. } else {
  3247. // We have something that isn't a non-static data
  3248. // member. Complain about it.
  3249. unsigned DK = diag::err_anonymous_record_bad_member;
  3250. if (isa<TypeDecl>(Mem))
  3251. DK = diag::err_anonymous_record_with_type;
  3252. else if (isa<FunctionDecl>(Mem))
  3253. DK = diag::err_anonymous_record_with_function;
  3254. else if (isa<VarDecl>(Mem))
  3255. DK = diag::err_anonymous_record_with_static;
  3256. // Visual C++ allows type definition in anonymous struct or union.
  3257. if (getLangOpts().MicrosoftExt &&
  3258. DK == diag::err_anonymous_record_with_type)
  3259. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  3260. << (int)Record->isUnion();
  3261. else {
  3262. Diag(Mem->getLocation(), DK)
  3263. << (int)Record->isUnion();
  3264. Invalid = true;
  3265. }
  3266. }
  3267. }
  3268. // C++11 [class.union]p8 (DR1460):
  3269. // At most one variant member of a union may have a
  3270. // brace-or-equal-initializer.
  3271. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  3272. Owner->isRecord())
  3273. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  3274. cast<CXXRecordDecl>(Record));
  3275. }
  3276. if (!Record->isUnion() && !Owner->isRecord()) {
  3277. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  3278. << (int)getLangOpts().CPlusPlus;
  3279. Invalid = true;
  3280. }
  3281. // Mock up a declarator.
  3282. Declarator Dc(DS, Declarator::MemberContext);
  3283. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3284. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  3285. // Create a declaration for this anonymous struct/union.
  3286. NamedDecl *Anon = 0;
  3287. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  3288. Anon = FieldDecl::Create(Context, OwningClass,
  3289. DS.getLocStart(),
  3290. Record->getLocation(),
  3291. /*IdentifierInfo=*/0,
  3292. Context.getTypeDeclType(Record),
  3293. TInfo,
  3294. /*BitWidth=*/0, /*Mutable=*/false,
  3295. /*InitStyle=*/ICIS_NoInit);
  3296. Anon->setAccess(AS);
  3297. if (getLangOpts().CPlusPlus)
  3298. FieldCollector->Add(cast<FieldDecl>(Anon));
  3299. } else {
  3300. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  3301. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  3302. if (SCSpec == DeclSpec::SCS_mutable) {
  3303. // mutable can only appear on non-static class members, so it's always
  3304. // an error here
  3305. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  3306. Invalid = true;
  3307. SC = SC_None;
  3308. }
  3309. Anon = VarDecl::Create(Context, Owner,
  3310. DS.getLocStart(),
  3311. Record->getLocation(), /*IdentifierInfo=*/0,
  3312. Context.getTypeDeclType(Record),
  3313. TInfo, SC);
  3314. // Default-initialize the implicit variable. This initialization will be
  3315. // trivial in almost all cases, except if a union member has an in-class
  3316. // initializer:
  3317. // union { int n = 0; };
  3318. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  3319. }
  3320. Anon->setImplicit();
  3321. // Mark this as an anonymous struct/union type.
  3322. Record->setAnonymousStructOrUnion(true);
  3323. // Add the anonymous struct/union object to the current
  3324. // context. We'll be referencing this object when we refer to one of
  3325. // its members.
  3326. Owner->addDecl(Anon);
  3327. // Inject the members of the anonymous struct/union into the owning
  3328. // context and into the identifier resolver chain for name lookup
  3329. // purposes.
  3330. SmallVector<NamedDecl*, 2> Chain;
  3331. Chain.push_back(Anon);
  3332. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  3333. Chain, false))
  3334. Invalid = true;
  3335. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  3336. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  3337. Decl *ManglingContextDecl;
  3338. if (MangleNumberingContext *MCtx =
  3339. getCurrentMangleNumberContext(NewVD->getDeclContext(),
  3340. ManglingContextDecl)) {
  3341. Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
  3342. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  3343. }
  3344. }
  3345. }
  3346. if (Invalid)
  3347. Anon->setInvalidDecl();
  3348. return Anon;
  3349. }
  3350. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  3351. /// Microsoft C anonymous structure.
  3352. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  3353. /// Example:
  3354. ///
  3355. /// struct A { int a; };
  3356. /// struct B { struct A; int b; };
  3357. ///
  3358. /// void foo() {
  3359. /// B var;
  3360. /// var.a = 3;
  3361. /// }
  3362. ///
  3363. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  3364. RecordDecl *Record) {
  3365. // If there is no Record, get the record via the typedef.
  3366. if (!Record)
  3367. Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
  3368. // Mock up a declarator.
  3369. Declarator Dc(DS, Declarator::TypeNameContext);
  3370. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  3371. assert(TInfo && "couldn't build declarator info for anonymous struct");
  3372. // Create a declaration for this anonymous struct.
  3373. NamedDecl* Anon = FieldDecl::Create(Context,
  3374. cast<RecordDecl>(CurContext),
  3375. DS.getLocStart(),
  3376. DS.getLocStart(),
  3377. /*IdentifierInfo=*/0,
  3378. Context.getTypeDeclType(Record),
  3379. TInfo,
  3380. /*BitWidth=*/0, /*Mutable=*/false,
  3381. /*InitStyle=*/ICIS_NoInit);
  3382. Anon->setImplicit();
  3383. // Add the anonymous struct object to the current context.
  3384. CurContext->addDecl(Anon);
  3385. // Inject the members of the anonymous struct into the current
  3386. // context and into the identifier resolver chain for name lookup
  3387. // purposes.
  3388. SmallVector<NamedDecl*, 2> Chain;
  3389. Chain.push_back(Anon);
  3390. RecordDecl *RecordDef = Record->getDefinition();
  3391. if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
  3392. RecordDef, AS_none,
  3393. Chain, true))
  3394. Anon->setInvalidDecl();
  3395. return Anon;
  3396. }
  3397. /// GetNameForDeclarator - Determine the full declaration name for the
  3398. /// given Declarator.
  3399. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  3400. return GetNameFromUnqualifiedId(D.getName());
  3401. }
  3402. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  3403. DeclarationNameInfo
  3404. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  3405. DeclarationNameInfo NameInfo;
  3406. NameInfo.setLoc(Name.StartLocation);
  3407. switch (Name.getKind()) {
  3408. case UnqualifiedId::IK_ImplicitSelfParam:
  3409. case UnqualifiedId::IK_Identifier:
  3410. NameInfo.setName(Name.Identifier);
  3411. NameInfo.setLoc(Name.StartLocation);
  3412. return NameInfo;
  3413. case UnqualifiedId::IK_OperatorFunctionId:
  3414. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  3415. Name.OperatorFunctionId.Operator));
  3416. NameInfo.setLoc(Name.StartLocation);
  3417. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  3418. = Name.OperatorFunctionId.SymbolLocations[0];
  3419. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  3420. = Name.EndLocation.getRawEncoding();
  3421. return NameInfo;
  3422. case UnqualifiedId::IK_LiteralOperatorId:
  3423. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  3424. Name.Identifier));
  3425. NameInfo.setLoc(Name.StartLocation);
  3426. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  3427. return NameInfo;
  3428. case UnqualifiedId::IK_ConversionFunctionId: {
  3429. TypeSourceInfo *TInfo;
  3430. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  3431. if (Ty.isNull())
  3432. return DeclarationNameInfo();
  3433. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  3434. Context.getCanonicalType(Ty)));
  3435. NameInfo.setLoc(Name.StartLocation);
  3436. NameInfo.setNamedTypeInfo(TInfo);
  3437. return NameInfo;
  3438. }
  3439. case UnqualifiedId::IK_ConstructorName: {
  3440. TypeSourceInfo *TInfo;
  3441. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  3442. if (Ty.isNull())
  3443. return DeclarationNameInfo();
  3444. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3445. Context.getCanonicalType(Ty)));
  3446. NameInfo.setLoc(Name.StartLocation);
  3447. NameInfo.setNamedTypeInfo(TInfo);
  3448. return NameInfo;
  3449. }
  3450. case UnqualifiedId::IK_ConstructorTemplateId: {
  3451. // In well-formed code, we can only have a constructor
  3452. // template-id that refers to the current context, so go there
  3453. // to find the actual type being constructed.
  3454. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  3455. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  3456. return DeclarationNameInfo();
  3457. // Determine the type of the class being constructed.
  3458. QualType CurClassType = Context.getTypeDeclType(CurClass);
  3459. // FIXME: Check two things: that the template-id names the same type as
  3460. // CurClassType, and that the template-id does not occur when the name
  3461. // was qualified.
  3462. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  3463. Context.getCanonicalType(CurClassType)));
  3464. NameInfo.setLoc(Name.StartLocation);
  3465. // FIXME: should we retrieve TypeSourceInfo?
  3466. NameInfo.setNamedTypeInfo(0);
  3467. return NameInfo;
  3468. }
  3469. case UnqualifiedId::IK_DestructorName: {
  3470. TypeSourceInfo *TInfo;
  3471. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  3472. if (Ty.isNull())
  3473. return DeclarationNameInfo();
  3474. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  3475. Context.getCanonicalType(Ty)));
  3476. NameInfo.setLoc(Name.StartLocation);
  3477. NameInfo.setNamedTypeInfo(TInfo);
  3478. return NameInfo;
  3479. }
  3480. case UnqualifiedId::IK_TemplateId: {
  3481. TemplateName TName = Name.TemplateId->Template.get();
  3482. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  3483. return Context.getNameForTemplate(TName, TNameLoc);
  3484. }
  3485. } // switch (Name.getKind())
  3486. llvm_unreachable("Unknown name kind");
  3487. }
  3488. static QualType getCoreType(QualType Ty) {
  3489. do {
  3490. if (Ty->isPointerType() || Ty->isReferenceType())
  3491. Ty = Ty->getPointeeType();
  3492. else if (Ty->isArrayType())
  3493. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  3494. else
  3495. return Ty.withoutLocalFastQualifiers();
  3496. } while (true);
  3497. }
  3498. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  3499. /// and Definition have "nearly" matching parameters. This heuristic is
  3500. /// used to improve diagnostics in the case where an out-of-line function
  3501. /// definition doesn't match any declaration within the class or namespace.
  3502. /// Also sets Params to the list of indices to the parameters that differ
  3503. /// between the declaration and the definition. If hasSimilarParameters
  3504. /// returns true and Params is empty, then all of the parameters match.
  3505. static bool hasSimilarParameters(ASTContext &Context,
  3506. FunctionDecl *Declaration,
  3507. FunctionDecl *Definition,
  3508. SmallVectorImpl<unsigned> &Params) {
  3509. Params.clear();
  3510. if (Declaration->param_size() != Definition->param_size())
  3511. return false;
  3512. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  3513. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  3514. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  3515. // The parameter types are identical
  3516. if (Context.hasSameType(DefParamTy, DeclParamTy))
  3517. continue;
  3518. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  3519. QualType DefParamBaseTy = getCoreType(DefParamTy);
  3520. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  3521. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  3522. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  3523. (DeclTyName && DeclTyName == DefTyName))
  3524. Params.push_back(Idx);
  3525. else // The two parameters aren't even close
  3526. return false;
  3527. }
  3528. return true;
  3529. }
  3530. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  3531. /// declarator needs to be rebuilt in the current instantiation.
  3532. /// Any bits of declarator which appear before the name are valid for
  3533. /// consideration here. That's specifically the type in the decl spec
  3534. /// and the base type in any member-pointer chunks.
  3535. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  3536. DeclarationName Name) {
  3537. // The types we specifically need to rebuild are:
  3538. // - typenames, typeofs, and decltypes
  3539. // - types which will become injected class names
  3540. // Of course, we also need to rebuild any type referencing such a
  3541. // type. It's safest to just say "dependent", but we call out a
  3542. // few cases here.
  3543. DeclSpec &DS = D.getMutableDeclSpec();
  3544. switch (DS.getTypeSpecType()) {
  3545. case DeclSpec::TST_typename:
  3546. case DeclSpec::TST_typeofType:
  3547. case DeclSpec::TST_underlyingType:
  3548. case DeclSpec::TST_atomic: {
  3549. // Grab the type from the parser.
  3550. TypeSourceInfo *TSI = 0;
  3551. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  3552. if (T.isNull() || !T->isDependentType()) break;
  3553. // Make sure there's a type source info. This isn't really much
  3554. // of a waste; most dependent types should have type source info
  3555. // attached already.
  3556. if (!TSI)
  3557. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  3558. // Rebuild the type in the current instantiation.
  3559. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  3560. if (!TSI) return true;
  3561. // Store the new type back in the decl spec.
  3562. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  3563. DS.UpdateTypeRep(LocType);
  3564. break;
  3565. }
  3566. case DeclSpec::TST_decltype:
  3567. case DeclSpec::TST_typeofExpr: {
  3568. Expr *E = DS.getRepAsExpr();
  3569. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  3570. if (Result.isInvalid()) return true;
  3571. DS.UpdateExprRep(Result.get());
  3572. break;
  3573. }
  3574. default:
  3575. // Nothing to do for these decl specs.
  3576. break;
  3577. }
  3578. // It doesn't matter what order we do this in.
  3579. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  3580. DeclaratorChunk &Chunk = D.getTypeObject(I);
  3581. // The only type information in the declarator which can come
  3582. // before the declaration name is the base type of a member
  3583. // pointer.
  3584. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  3585. continue;
  3586. // Rebuild the scope specifier in-place.
  3587. CXXScopeSpec &SS = Chunk.Mem.Scope();
  3588. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  3589. return true;
  3590. }
  3591. return false;
  3592. }
  3593. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  3594. D.setFunctionDefinitionKind(FDK_Declaration);
  3595. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  3596. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  3597. Dcl && Dcl->getDeclContext()->isFileContext())
  3598. Dcl->setTopLevelDeclInObjCContainer();
  3599. return Dcl;
  3600. }
  3601. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  3602. /// If T is the name of a class, then each of the following shall have a
  3603. /// name different from T:
  3604. /// - every static data member of class T;
  3605. /// - every member function of class T
  3606. /// - every member of class T that is itself a type;
  3607. /// \returns true if the declaration name violates these rules.
  3608. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  3609. DeclarationNameInfo NameInfo) {
  3610. DeclarationName Name = NameInfo.getName();
  3611. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  3612. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  3613. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  3614. return true;
  3615. }
  3616. return false;
  3617. }
  3618. /// \brief Diagnose a declaration whose declarator-id has the given
  3619. /// nested-name-specifier.
  3620. ///
  3621. /// \param SS The nested-name-specifier of the declarator-id.
  3622. ///
  3623. /// \param DC The declaration context to which the nested-name-specifier
  3624. /// resolves.
  3625. ///
  3626. /// \param Name The name of the entity being declared.
  3627. ///
  3628. /// \param Loc The location of the name of the entity being declared.
  3629. ///
  3630. /// \returns true if we cannot safely recover from this error, false otherwise.
  3631. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  3632. DeclarationName Name,
  3633. SourceLocation Loc) {
  3634. DeclContext *Cur = CurContext;
  3635. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  3636. Cur = Cur->getParent();
  3637. // If the user provided a superfluous scope specifier that refers back to the
  3638. // class in which the entity is already declared, diagnose and ignore it.
  3639. //
  3640. // class X {
  3641. // void X::f();
  3642. // };
  3643. //
  3644. // Note, it was once ill-formed to give redundant qualification in all
  3645. // contexts, but that rule was removed by DR482.
  3646. if (Cur->Equals(DC)) {
  3647. if (Cur->isRecord()) {
  3648. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  3649. : diag::err_member_extra_qualification)
  3650. << Name << FixItHint::CreateRemoval(SS.getRange());
  3651. SS.clear();
  3652. } else {
  3653. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  3654. }
  3655. return false;
  3656. }
  3657. // Check whether the qualifying scope encloses the scope of the original
  3658. // declaration.
  3659. if (!Cur->Encloses(DC)) {
  3660. if (Cur->isRecord())
  3661. Diag(Loc, diag::err_member_qualification)
  3662. << Name << SS.getRange();
  3663. else if (isa<TranslationUnitDecl>(DC))
  3664. Diag(Loc, diag::err_invalid_declarator_global_scope)
  3665. << Name << SS.getRange();
  3666. else if (isa<FunctionDecl>(Cur))
  3667. Diag(Loc, diag::err_invalid_declarator_in_function)
  3668. << Name << SS.getRange();
  3669. else if (isa<BlockDecl>(Cur))
  3670. Diag(Loc, diag::err_invalid_declarator_in_block)
  3671. << Name << SS.getRange();
  3672. else
  3673. Diag(Loc, diag::err_invalid_declarator_scope)
  3674. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  3675. return true;
  3676. }
  3677. if (Cur->isRecord()) {
  3678. // Cannot qualify members within a class.
  3679. Diag(Loc, diag::err_member_qualification)
  3680. << Name << SS.getRange();
  3681. SS.clear();
  3682. // C++ constructors and destructors with incorrect scopes can break
  3683. // our AST invariants by having the wrong underlying types. If
  3684. // that's the case, then drop this declaration entirely.
  3685. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3686. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  3687. !Context.hasSameType(Name.getCXXNameType(),
  3688. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  3689. return true;
  3690. return false;
  3691. }
  3692. // C++11 [dcl.meaning]p1:
  3693. // [...] "The nested-name-specifier of the qualified declarator-id shall
  3694. // not begin with a decltype-specifer"
  3695. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  3696. while (SpecLoc.getPrefix())
  3697. SpecLoc = SpecLoc.getPrefix();
  3698. if (dyn_cast_or_null<DecltypeType>(
  3699. SpecLoc.getNestedNameSpecifier()->getAsType()))
  3700. Diag(Loc, diag::err_decltype_in_declarator)
  3701. << SpecLoc.getTypeLoc().getSourceRange();
  3702. return false;
  3703. }
  3704. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  3705. MultiTemplateParamsArg TemplateParamLists) {
  3706. // TODO: consider using NameInfo for diagnostic.
  3707. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  3708. DeclarationName Name = NameInfo.getName();
  3709. // All of these full declarators require an identifier. If it doesn't have
  3710. // one, the ParsedFreeStandingDeclSpec action should be used.
  3711. if (!Name) {
  3712. if (!D.isInvalidType()) // Reject this if we think it is valid.
  3713. Diag(D.getDeclSpec().getLocStart(),
  3714. diag::err_declarator_need_ident)
  3715. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  3716. return 0;
  3717. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  3718. return 0;
  3719. // The scope passed in may not be a decl scope. Zip up the scope tree until
  3720. // we find one that is.
  3721. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  3722. (S->getFlags() & Scope::TemplateParamScope) != 0)
  3723. S = S->getParent();
  3724. DeclContext *DC = CurContext;
  3725. if (D.getCXXScopeSpec().isInvalid())
  3726. D.setInvalidType();
  3727. else if (D.getCXXScopeSpec().isSet()) {
  3728. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  3729. UPPC_DeclarationQualifier))
  3730. return 0;
  3731. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  3732. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  3733. if (!DC || isa<EnumDecl>(DC)) {
  3734. // If we could not compute the declaration context, it's because the
  3735. // declaration context is dependent but does not refer to a class,
  3736. // class template, or class template partial specialization. Complain
  3737. // and return early, to avoid the coming semantic disaster.
  3738. Diag(D.getIdentifierLoc(),
  3739. diag::err_template_qualified_declarator_no_match)
  3740. << D.getCXXScopeSpec().getScopeRep()
  3741. << D.getCXXScopeSpec().getRange();
  3742. return 0;
  3743. }
  3744. bool IsDependentContext = DC->isDependentContext();
  3745. if (!IsDependentContext &&
  3746. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  3747. return 0;
  3748. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  3749. Diag(D.getIdentifierLoc(),
  3750. diag::err_member_def_undefined_record)
  3751. << Name << DC << D.getCXXScopeSpec().getRange();
  3752. D.setInvalidType();
  3753. } else if (!D.getDeclSpec().isFriendSpecified()) {
  3754. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  3755. Name, D.getIdentifierLoc())) {
  3756. if (DC->isRecord())
  3757. return 0;
  3758. D.setInvalidType();
  3759. }
  3760. }
  3761. // Check whether we need to rebuild the type of the given
  3762. // declaration in the current instantiation.
  3763. if (EnteringContext && IsDependentContext &&
  3764. TemplateParamLists.size() != 0) {
  3765. ContextRAII SavedContext(*this, DC);
  3766. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  3767. D.setInvalidType();
  3768. }
  3769. }
  3770. if (DiagnoseClassNameShadow(DC, NameInfo))
  3771. // If this is a typedef, we'll end up spewing multiple diagnostics.
  3772. // Just return early; it's safer.
  3773. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3774. return 0;
  3775. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  3776. QualType R = TInfo->getType();
  3777. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  3778. UPPC_DeclarationType))
  3779. D.setInvalidType();
  3780. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  3781. ForRedeclaration);
  3782. // See if this is a redefinition of a variable in the same scope.
  3783. if (!D.getCXXScopeSpec().isSet()) {
  3784. bool IsLinkageLookup = false;
  3785. bool CreateBuiltins = false;
  3786. // If the declaration we're planning to build will be a function
  3787. // or object with linkage, then look for another declaration with
  3788. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  3789. //
  3790. // If the declaration we're planning to build will be declared with
  3791. // external linkage in the translation unit, create any builtin with
  3792. // the same name.
  3793. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3794. /* Do nothing*/;
  3795. else if (CurContext->isFunctionOrMethod() &&
  3796. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  3797. R->isFunctionType())) {
  3798. IsLinkageLookup = true;
  3799. CreateBuiltins =
  3800. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  3801. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  3802. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3803. CreateBuiltins = true;
  3804. if (IsLinkageLookup)
  3805. Previous.clear(LookupRedeclarationWithLinkage);
  3806. LookupName(Previous, S, CreateBuiltins);
  3807. } else { // Something like "int foo::x;"
  3808. LookupQualifiedName(Previous, DC);
  3809. // C++ [dcl.meaning]p1:
  3810. // When the declarator-id is qualified, the declaration shall refer to a
  3811. // previously declared member of the class or namespace to which the
  3812. // qualifier refers (or, in the case of a namespace, of an element of the
  3813. // inline namespace set of that namespace (7.3.1)) or to a specialization
  3814. // thereof; [...]
  3815. //
  3816. // Note that we already checked the context above, and that we do not have
  3817. // enough information to make sure that Previous contains the declaration
  3818. // we want to match. For example, given:
  3819. //
  3820. // class X {
  3821. // void f();
  3822. // void f(float);
  3823. // };
  3824. //
  3825. // void X::f(int) { } // ill-formed
  3826. //
  3827. // In this case, Previous will point to the overload set
  3828. // containing the two f's declared in X, but neither of them
  3829. // matches.
  3830. // C++ [dcl.meaning]p1:
  3831. // [...] the member shall not merely have been introduced by a
  3832. // using-declaration in the scope of the class or namespace nominated by
  3833. // the nested-name-specifier of the declarator-id.
  3834. RemoveUsingDecls(Previous);
  3835. }
  3836. if (Previous.isSingleResult() &&
  3837. Previous.getFoundDecl()->isTemplateParameter()) {
  3838. // Maybe we will complain about the shadowed template parameter.
  3839. if (!D.isInvalidType())
  3840. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  3841. Previous.getFoundDecl());
  3842. // Just pretend that we didn't see the previous declaration.
  3843. Previous.clear();
  3844. }
  3845. // In C++, the previous declaration we find might be a tag type
  3846. // (class or enum). In this case, the new declaration will hide the
  3847. // tag type. Note that this does does not apply if we're declaring a
  3848. // typedef (C++ [dcl.typedef]p4).
  3849. if (Previous.isSingleTagDecl() &&
  3850. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  3851. Previous.clear();
  3852. // Check that there are no default arguments other than in the parameters
  3853. // of a function declaration (C++ only).
  3854. if (getLangOpts().CPlusPlus)
  3855. CheckExtraCXXDefaultArguments(D);
  3856. NamedDecl *New;
  3857. bool AddToScope = true;
  3858. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3859. if (TemplateParamLists.size()) {
  3860. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  3861. return 0;
  3862. }
  3863. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  3864. } else if (R->isFunctionType()) {
  3865. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  3866. TemplateParamLists,
  3867. AddToScope);
  3868. } else {
  3869. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  3870. AddToScope);
  3871. }
  3872. if (New == 0)
  3873. return 0;
  3874. // If this has an identifier and is not an invalid redeclaration or
  3875. // function template specialization, add it to the scope stack.
  3876. if (New->getDeclName() && AddToScope &&
  3877. !(D.isRedeclaration() && New->isInvalidDecl())) {
  3878. // Only make a locally-scoped extern declaration visible if it is the first
  3879. // declaration of this entity. Qualified lookup for such an entity should
  3880. // only find this declaration if there is no visible declaration of it.
  3881. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  3882. PushOnScopeChains(New, S, AddToContext);
  3883. if (!AddToContext)
  3884. CurContext->addHiddenDecl(New);
  3885. }
  3886. return New;
  3887. }
  3888. /// Helper method to turn variable array types into constant array
  3889. /// types in certain situations which would otherwise be errors (for
  3890. /// GCC compatibility).
  3891. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  3892. ASTContext &Context,
  3893. bool &SizeIsNegative,
  3894. llvm::APSInt &Oversized) {
  3895. // This method tries to turn a variable array into a constant
  3896. // array even when the size isn't an ICE. This is necessary
  3897. // for compatibility with code that depends on gcc's buggy
  3898. // constant expression folding, like struct {char x[(int)(char*)2];}
  3899. SizeIsNegative = false;
  3900. Oversized = 0;
  3901. if (T->isDependentType())
  3902. return QualType();
  3903. QualifierCollector Qs;
  3904. const Type *Ty = Qs.strip(T);
  3905. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  3906. QualType Pointee = PTy->getPointeeType();
  3907. QualType FixedType =
  3908. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  3909. Oversized);
  3910. if (FixedType.isNull()) return FixedType;
  3911. FixedType = Context.getPointerType(FixedType);
  3912. return Qs.apply(Context, FixedType);
  3913. }
  3914. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  3915. QualType Inner = PTy->getInnerType();
  3916. QualType FixedType =
  3917. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  3918. Oversized);
  3919. if (FixedType.isNull()) return FixedType;
  3920. FixedType = Context.getParenType(FixedType);
  3921. return Qs.apply(Context, FixedType);
  3922. }
  3923. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  3924. if (!VLATy)
  3925. return QualType();
  3926. // FIXME: We should probably handle this case
  3927. if (VLATy->getElementType()->isVariablyModifiedType())
  3928. return QualType();
  3929. llvm::APSInt Res;
  3930. if (!VLATy->getSizeExpr() ||
  3931. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  3932. return QualType();
  3933. // Check whether the array size is negative.
  3934. if (Res.isSigned() && Res.isNegative()) {
  3935. SizeIsNegative = true;
  3936. return QualType();
  3937. }
  3938. // Check whether the array is too large to be addressed.
  3939. unsigned ActiveSizeBits
  3940. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  3941. Res);
  3942. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  3943. Oversized = Res;
  3944. return QualType();
  3945. }
  3946. return Context.getConstantArrayType(VLATy->getElementType(),
  3947. Res, ArrayType::Normal, 0);
  3948. }
  3949. static void
  3950. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  3951. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  3952. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  3953. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  3954. DstPTL.getPointeeLoc());
  3955. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  3956. return;
  3957. }
  3958. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  3959. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  3960. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  3961. DstPTL.getInnerLoc());
  3962. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  3963. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  3964. return;
  3965. }
  3966. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  3967. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  3968. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  3969. TypeLoc DstElemTL = DstATL.getElementLoc();
  3970. DstElemTL.initializeFullCopy(SrcElemTL);
  3971. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  3972. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  3973. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  3974. }
  3975. /// Helper method to turn variable array types into constant array
  3976. /// types in certain situations which would otherwise be errors (for
  3977. /// GCC compatibility).
  3978. static TypeSourceInfo*
  3979. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  3980. ASTContext &Context,
  3981. bool &SizeIsNegative,
  3982. llvm::APSInt &Oversized) {
  3983. QualType FixedTy
  3984. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  3985. SizeIsNegative, Oversized);
  3986. if (FixedTy.isNull())
  3987. return 0;
  3988. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  3989. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  3990. FixedTInfo->getTypeLoc());
  3991. return FixedTInfo;
  3992. }
  3993. /// \brief Register the given locally-scoped extern "C" declaration so
  3994. /// that it can be found later for redeclarations. We include any extern "C"
  3995. /// declaration that is not visible in the translation unit here, not just
  3996. /// function-scope declarations.
  3997. void
  3998. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  3999. if (!getLangOpts().CPlusPlus &&
  4000. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4001. // Don't need to track declarations in the TU in C.
  4002. return;
  4003. // Note that we have a locally-scoped external with this name.
  4004. // FIXME: There can be multiple such declarations if they are functions marked
  4005. // __attribute__((overloadable)) declared in function scope in C.
  4006. LocallyScopedExternCDecls[ND->getDeclName()] = ND;
  4007. }
  4008. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4009. if (ExternalSource) {
  4010. // Load locally-scoped external decls from the external source.
  4011. // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
  4012. SmallVector<NamedDecl *, 4> Decls;
  4013. ExternalSource->ReadLocallyScopedExternCDecls(Decls);
  4014. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  4015. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  4016. = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
  4017. if (Pos == LocallyScopedExternCDecls.end())
  4018. LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
  4019. }
  4020. }
  4021. NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
  4022. return D ? D->getMostRecentDecl() : 0;
  4023. }
  4024. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4025. /// does not identify a function.
  4026. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4027. // FIXME: We should probably indicate the identifier in question to avoid
  4028. // confusion for constructs like "inline int a(), b;"
  4029. if (DS.isInlineSpecified())
  4030. Diag(DS.getInlineSpecLoc(),
  4031. diag::err_inline_non_function);
  4032. if (DS.isVirtualSpecified())
  4033. Diag(DS.getVirtualSpecLoc(),
  4034. diag::err_virtual_non_function);
  4035. if (DS.isExplicitSpecified())
  4036. Diag(DS.getExplicitSpecLoc(),
  4037. diag::err_explicit_non_function);
  4038. if (DS.isNoreturnSpecified())
  4039. Diag(DS.getNoreturnSpecLoc(),
  4040. diag::err_noreturn_non_function);
  4041. }
  4042. NamedDecl*
  4043. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4044. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4045. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4046. if (D.getCXXScopeSpec().isSet()) {
  4047. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4048. << D.getCXXScopeSpec().getRange();
  4049. D.setInvalidType();
  4050. // Pretend we didn't see the scope specifier.
  4051. DC = CurContext;
  4052. Previous.clear();
  4053. }
  4054. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4055. if (D.getDeclSpec().isConstexprSpecified())
  4056. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4057. << 1;
  4058. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4059. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4060. << D.getName().getSourceRange();
  4061. return 0;
  4062. }
  4063. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4064. if (!NewTD) return 0;
  4065. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4066. ProcessDeclAttributes(S, NewTD, D);
  4067. CheckTypedefForVariablyModifiedType(S, NewTD);
  4068. bool Redeclaration = D.isRedeclaration();
  4069. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4070. D.setRedeclaration(Redeclaration);
  4071. return ND;
  4072. }
  4073. void
  4074. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4075. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4076. // then it shall have block scope.
  4077. // Note that variably modified types must be fixed before merging the decl so
  4078. // that redeclarations will match.
  4079. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4080. QualType T = TInfo->getType();
  4081. if (T->isVariablyModifiedType()) {
  4082. getCurFunction()->setHasBranchProtectedScope();
  4083. if (S->getFnParent() == 0) {
  4084. bool SizeIsNegative;
  4085. llvm::APSInt Oversized;
  4086. TypeSourceInfo *FixedTInfo =
  4087. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  4088. SizeIsNegative,
  4089. Oversized);
  4090. if (FixedTInfo) {
  4091. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  4092. NewTD->setTypeSourceInfo(FixedTInfo);
  4093. } else {
  4094. if (SizeIsNegative)
  4095. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  4096. else if (T->isVariableArrayType())
  4097. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  4098. else if (Oversized.getBoolValue())
  4099. Diag(NewTD->getLocation(), diag::err_array_too_large)
  4100. << Oversized.toString(10);
  4101. else
  4102. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  4103. NewTD->setInvalidDecl();
  4104. }
  4105. }
  4106. }
  4107. }
  4108. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  4109. /// declares a typedef-name, either using the 'typedef' type specifier or via
  4110. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  4111. NamedDecl*
  4112. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  4113. LookupResult &Previous, bool &Redeclaration) {
  4114. // Merge the decl with the existing one if appropriate. If the decl is
  4115. // in an outer scope, it isn't the same thing.
  4116. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  4117. /*AllowInlineNamespace*/false);
  4118. filterNonConflictingPreviousDecls(Context, NewTD, Previous);
  4119. if (!Previous.empty()) {
  4120. Redeclaration = true;
  4121. MergeTypedefNameDecl(NewTD, Previous);
  4122. }
  4123. // If this is the C FILE type, notify the AST context.
  4124. if (IdentifierInfo *II = NewTD->getIdentifier())
  4125. if (!NewTD->isInvalidDecl() &&
  4126. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  4127. if (II->isStr("FILE"))
  4128. Context.setFILEDecl(NewTD);
  4129. else if (II->isStr("jmp_buf"))
  4130. Context.setjmp_bufDecl(NewTD);
  4131. else if (II->isStr("sigjmp_buf"))
  4132. Context.setsigjmp_bufDecl(NewTD);
  4133. else if (II->isStr("ucontext_t"))
  4134. Context.setucontext_tDecl(NewTD);
  4135. }
  4136. return NewTD;
  4137. }
  4138. /// \brief Determines whether the given declaration is an out-of-scope
  4139. /// previous declaration.
  4140. ///
  4141. /// This routine should be invoked when name lookup has found a
  4142. /// previous declaration (PrevDecl) that is not in the scope where a
  4143. /// new declaration by the same name is being introduced. If the new
  4144. /// declaration occurs in a local scope, previous declarations with
  4145. /// linkage may still be considered previous declarations (C99
  4146. /// 6.2.2p4-5, C++ [basic.link]p6).
  4147. ///
  4148. /// \param PrevDecl the previous declaration found by name
  4149. /// lookup
  4150. ///
  4151. /// \param DC the context in which the new declaration is being
  4152. /// declared.
  4153. ///
  4154. /// \returns true if PrevDecl is an out-of-scope previous declaration
  4155. /// for a new delcaration with the same name.
  4156. static bool
  4157. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  4158. ASTContext &Context) {
  4159. if (!PrevDecl)
  4160. return false;
  4161. if (!PrevDecl->hasLinkage())
  4162. return false;
  4163. if (Context.getLangOpts().CPlusPlus) {
  4164. // C++ [basic.link]p6:
  4165. // If there is a visible declaration of an entity with linkage
  4166. // having the same name and type, ignoring entities declared
  4167. // outside the innermost enclosing namespace scope, the block
  4168. // scope declaration declares that same entity and receives the
  4169. // linkage of the previous declaration.
  4170. DeclContext *OuterContext = DC->getRedeclContext();
  4171. if (!OuterContext->isFunctionOrMethod())
  4172. // This rule only applies to block-scope declarations.
  4173. return false;
  4174. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  4175. if (PrevOuterContext->isRecord())
  4176. // We found a member function: ignore it.
  4177. return false;
  4178. // Find the innermost enclosing namespace for the new and
  4179. // previous declarations.
  4180. OuterContext = OuterContext->getEnclosingNamespaceContext();
  4181. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  4182. // The previous declaration is in a different namespace, so it
  4183. // isn't the same function.
  4184. if (!OuterContext->Equals(PrevOuterContext))
  4185. return false;
  4186. }
  4187. return true;
  4188. }
  4189. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  4190. CXXScopeSpec &SS = D.getCXXScopeSpec();
  4191. if (!SS.isSet()) return;
  4192. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  4193. }
  4194. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  4195. QualType type = decl->getType();
  4196. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  4197. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  4198. // Various kinds of declaration aren't allowed to be __autoreleasing.
  4199. unsigned kind = -1U;
  4200. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4201. if (var->hasAttr<BlocksAttr>())
  4202. kind = 0; // __block
  4203. else if (!var->hasLocalStorage())
  4204. kind = 1; // global
  4205. } else if (isa<ObjCIvarDecl>(decl)) {
  4206. kind = 3; // ivar
  4207. } else if (isa<FieldDecl>(decl)) {
  4208. kind = 2; // field
  4209. }
  4210. if (kind != -1U) {
  4211. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  4212. << kind;
  4213. }
  4214. } else if (lifetime == Qualifiers::OCL_None) {
  4215. // Try to infer lifetime.
  4216. if (!type->isObjCLifetimeType())
  4217. return false;
  4218. lifetime = type->getObjCARCImplicitLifetime();
  4219. type = Context.getLifetimeQualifiedType(type, lifetime);
  4220. decl->setType(type);
  4221. }
  4222. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  4223. // Thread-local variables cannot have lifetime.
  4224. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  4225. var->getTLSKind()) {
  4226. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  4227. << var->getType();
  4228. return true;
  4229. }
  4230. }
  4231. return false;
  4232. }
  4233. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  4234. // Ensure that an auto decl is deduced otherwise the checks below might cache
  4235. // the wrong linkage.
  4236. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  4237. // 'weak' only applies to declarations with external linkage.
  4238. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  4239. if (!ND.isExternallyVisible()) {
  4240. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  4241. ND.dropAttr<WeakAttr>();
  4242. }
  4243. }
  4244. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  4245. if (ND.isExternallyVisible()) {
  4246. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  4247. ND.dropAttr<WeakRefAttr>();
  4248. }
  4249. }
  4250. // 'selectany' only applies to externally visible varable declarations.
  4251. // It does not apply to functions.
  4252. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  4253. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  4254. S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
  4255. ND.dropAttr<SelectAnyAttr>();
  4256. }
  4257. }
  4258. // dll attributes require external linkage.
  4259. if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) {
  4260. if (!ND.isExternallyVisible()) {
  4261. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4262. << &ND << Attr;
  4263. ND.setInvalidDecl();
  4264. }
  4265. }
  4266. if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) {
  4267. if (!ND.isExternallyVisible()) {
  4268. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  4269. << &ND << Attr;
  4270. ND.setInvalidDecl();
  4271. }
  4272. }
  4273. }
  4274. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  4275. NamedDecl *NewDecl,
  4276. bool IsSpecialization) {
  4277. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
  4278. OldDecl = OldTD->getTemplatedDecl();
  4279. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
  4280. NewDecl = NewTD->getTemplatedDecl();
  4281. if (!OldDecl || !NewDecl)
  4282. return;
  4283. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  4284. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  4285. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  4286. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  4287. // dllimport and dllexport are inheritable attributes so we have to exclude
  4288. // inherited attribute instances.
  4289. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  4290. (NewExportAttr && !NewExportAttr->isInherited());
  4291. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  4292. // the only exception being explicit specializations.
  4293. // Implicitly generated declarations are also excluded for now because there
  4294. // is no other way to switch these to use dllimport or dllexport.
  4295. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  4296. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  4297. S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration)
  4298. << NewDecl
  4299. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  4300. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4301. NewDecl->setInvalidDecl();
  4302. return;
  4303. }
  4304. // A redeclaration is not allowed to drop a dllimport attribute, the only
  4305. // exception being inline function definitions.
  4306. // NB: MSVC converts such a declaration to dllexport.
  4307. bool IsInline =
  4308. isa<FunctionDecl>(NewDecl) && cast<FunctionDecl>(NewDecl)->isInlined();
  4309. if (OldImportAttr && !HasNewAttr && !IsInline) {
  4310. S.Diag(NewDecl->getLocation(),
  4311. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  4312. << NewDecl << OldImportAttr;
  4313. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  4314. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  4315. OldDecl->dropAttr<DLLImportAttr>();
  4316. NewDecl->dropAttr<DLLImportAttr>();
  4317. }
  4318. }
  4319. /// Given that we are within the definition of the given function,
  4320. /// will that definition behave like C99's 'inline', where the
  4321. /// definition is discarded except for optimization purposes?
  4322. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  4323. // Try to avoid calling GetGVALinkageForFunction.
  4324. // All cases of this require the 'inline' keyword.
  4325. if (!FD->isInlined()) return false;
  4326. // This is only possible in C++ with the gnu_inline attribute.
  4327. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  4328. return false;
  4329. // Okay, go ahead and call the relatively-more-expensive function.
  4330. #ifndef NDEBUG
  4331. // AST quite reasonably asserts that it's working on a function
  4332. // definition. We don't really have a way to tell it that we're
  4333. // currently defining the function, so just lie to it in +Asserts
  4334. // builds. This is an awful hack.
  4335. FD->setLazyBody(1);
  4336. #endif
  4337. bool isC99Inline =
  4338. S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  4339. #ifndef NDEBUG
  4340. FD->setLazyBody(0);
  4341. #endif
  4342. return isC99Inline;
  4343. }
  4344. /// Determine whether a variable is extern "C" prior to attaching
  4345. /// an initializer. We can't just call isExternC() here, because that
  4346. /// will also compute and cache whether the declaration is externally
  4347. /// visible, which might change when we attach the initializer.
  4348. ///
  4349. /// This can only be used if the declaration is known to not be a
  4350. /// redeclaration of an internal linkage declaration.
  4351. ///
  4352. /// For instance:
  4353. ///
  4354. /// auto x = []{};
  4355. ///
  4356. /// Attaching the initializer here makes this declaration not externally
  4357. /// visible, because its type has internal linkage.
  4358. ///
  4359. /// FIXME: This is a hack.
  4360. template<typename T>
  4361. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  4362. if (S.getLangOpts().CPlusPlus) {
  4363. // In C++, the overloadable attribute negates the effects of extern "C".
  4364. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  4365. return false;
  4366. }
  4367. return D->isExternC();
  4368. }
  4369. static bool shouldConsiderLinkage(const VarDecl *VD) {
  4370. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  4371. if (DC->isFunctionOrMethod())
  4372. return VD->hasExternalStorage();
  4373. if (DC->isFileContext())
  4374. return true;
  4375. if (DC->isRecord())
  4376. return false;
  4377. llvm_unreachable("Unexpected context");
  4378. }
  4379. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  4380. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  4381. if (DC->isFileContext() || DC->isFunctionOrMethod())
  4382. return true;
  4383. if (DC->isRecord())
  4384. return false;
  4385. llvm_unreachable("Unexpected context");
  4386. }
  4387. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  4388. AttributeList::Kind Kind) {
  4389. for (const AttributeList *L = AttrList; L; L = L->getNext())
  4390. if (L->getKind() == Kind)
  4391. return true;
  4392. return false;
  4393. }
  4394. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  4395. AttributeList::Kind Kind) {
  4396. // Check decl attributes on the DeclSpec.
  4397. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  4398. return true;
  4399. // Walk the declarator structure, checking decl attributes that were in a type
  4400. // position to the decl itself.
  4401. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  4402. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  4403. return true;
  4404. }
  4405. // Finally, check attributes on the decl itself.
  4406. return hasParsedAttr(S, PD.getAttributes(), Kind);
  4407. }
  4408. /// Adjust the \c DeclContext for a function or variable that might be a
  4409. /// function-local external declaration.
  4410. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  4411. if (!DC->isFunctionOrMethod())
  4412. return false;
  4413. // If this is a local extern function or variable declared within a function
  4414. // template, don't add it into the enclosing namespace scope until it is
  4415. // instantiated; it might have a dependent type right now.
  4416. if (DC->isDependentContext())
  4417. return true;
  4418. // C++11 [basic.link]p7:
  4419. // When a block scope declaration of an entity with linkage is not found to
  4420. // refer to some other declaration, then that entity is a member of the
  4421. // innermost enclosing namespace.
  4422. //
  4423. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  4424. // semantically-enclosing namespace, not a lexically-enclosing one.
  4425. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  4426. DC = DC->getParent();
  4427. return true;
  4428. }
  4429. NamedDecl *
  4430. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4431. TypeSourceInfo *TInfo, LookupResult &Previous,
  4432. MultiTemplateParamsArg TemplateParamLists,
  4433. bool &AddToScope) {
  4434. QualType R = TInfo->getType();
  4435. DeclarationName Name = GetNameForDeclarator(D).getName();
  4436. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  4437. VarDecl::StorageClass SC =
  4438. StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  4439. // dllimport globals without explicit storage class are treated as extern. We
  4440. // have to change the storage class this early to get the right DeclContext.
  4441. if (SC == SC_None && !DC->isRecord() &&
  4442. hasParsedAttr(S, D, AttributeList::AT_DLLImport))
  4443. SC = SC_Extern;
  4444. DeclContext *OriginalDC = DC;
  4445. bool IsLocalExternDecl = SC == SC_Extern &&
  4446. adjustContextForLocalExternDecl(DC);
  4447. if (getLangOpts().OpenCL) {
  4448. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  4449. QualType NR = R;
  4450. while (NR->isPointerType()) {
  4451. if (NR->isFunctionPointerType()) {
  4452. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
  4453. D.setInvalidType();
  4454. break;
  4455. }
  4456. NR = NR->getPointeeType();
  4457. }
  4458. if (!getOpenCLOptions().cl_khr_fp16) {
  4459. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  4460. // half array type (unless the cl_khr_fp16 extension is enabled).
  4461. if (Context.getBaseElementType(R)->isHalfType()) {
  4462. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  4463. D.setInvalidType();
  4464. }
  4465. }
  4466. }
  4467. if (SCSpec == DeclSpec::SCS_mutable) {
  4468. // mutable can only appear on non-static class members, so it's always
  4469. // an error here
  4470. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  4471. D.setInvalidType();
  4472. SC = SC_None;
  4473. }
  4474. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  4475. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  4476. D.getDeclSpec().getStorageClassSpecLoc())) {
  4477. // In C++11, the 'register' storage class specifier is deprecated.
  4478. // Suppress the warning in system macros, it's used in macros in some
  4479. // popular C system headers, such as in glibc's htonl() macro.
  4480. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4481. diag::warn_deprecated_register)
  4482. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4483. }
  4484. IdentifierInfo *II = Name.getAsIdentifierInfo();
  4485. if (!II) {
  4486. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  4487. << Name;
  4488. return 0;
  4489. }
  4490. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4491. if (!DC->isRecord() && S->getFnParent() == 0) {
  4492. // C99 6.9p2: The storage-class specifiers auto and register shall not
  4493. // appear in the declaration specifiers in an external declaration.
  4494. // Global Register+Asm is a GNU extension we support.
  4495. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  4496. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  4497. D.setInvalidType();
  4498. }
  4499. }
  4500. if (getLangOpts().OpenCL) {
  4501. // Set up the special work-group-local storage class for variables in the
  4502. // OpenCL __local address space.
  4503. if (R.getAddressSpace() == LangAS::opencl_local) {
  4504. SC = SC_OpenCLWorkGroupLocal;
  4505. }
  4506. // OpenCL v1.2 s6.9.b p4:
  4507. // The sampler type cannot be used with the __local and __global address
  4508. // space qualifiers.
  4509. if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
  4510. R.getAddressSpace() == LangAS::opencl_global)) {
  4511. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  4512. }
  4513. // OpenCL 1.2 spec, p6.9 r:
  4514. // The event type cannot be used to declare a program scope variable.
  4515. // The event type cannot be used with the __local, __constant and __global
  4516. // address space qualifiers.
  4517. if (R->isEventT()) {
  4518. if (S->getParent() == 0) {
  4519. Diag(D.getLocStart(), diag::err_event_t_global_var);
  4520. D.setInvalidType();
  4521. }
  4522. if (R.getAddressSpace()) {
  4523. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  4524. D.setInvalidType();
  4525. }
  4526. }
  4527. }
  4528. bool IsExplicitSpecialization = false;
  4529. bool IsVariableTemplateSpecialization = false;
  4530. bool IsPartialSpecialization = false;
  4531. bool IsVariableTemplate = false;
  4532. VarDecl *NewVD = 0;
  4533. VarTemplateDecl *NewTemplate = 0;
  4534. TemplateParameterList *TemplateParams = 0;
  4535. if (!getLangOpts().CPlusPlus) {
  4536. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  4537. D.getIdentifierLoc(), II,
  4538. R, TInfo, SC);
  4539. if (D.isInvalidType())
  4540. NewVD->setInvalidDecl();
  4541. } else {
  4542. bool Invalid = false;
  4543. if (DC->isRecord() && !CurContext->isRecord()) {
  4544. // This is an out-of-line definition of a static data member.
  4545. switch (SC) {
  4546. case SC_None:
  4547. break;
  4548. case SC_Static:
  4549. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4550. diag::err_static_out_of_line)
  4551. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4552. break;
  4553. case SC_Auto:
  4554. case SC_Register:
  4555. case SC_Extern:
  4556. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  4557. // to names of variables declared in a block or to function parameters.
  4558. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  4559. // of class members
  4560. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4561. diag::err_storage_class_for_static_member)
  4562. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4563. break;
  4564. case SC_PrivateExtern:
  4565. llvm_unreachable("C storage class in c++!");
  4566. case SC_OpenCLWorkGroupLocal:
  4567. llvm_unreachable("OpenCL storage class in c++!");
  4568. }
  4569. }
  4570. if (SC == SC_Static && CurContext->isRecord()) {
  4571. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  4572. if (RD->isLocalClass())
  4573. Diag(D.getIdentifierLoc(),
  4574. diag::err_static_data_member_not_allowed_in_local_class)
  4575. << Name << RD->getDeclName();
  4576. // C++98 [class.union]p1: If a union contains a static data member,
  4577. // the program is ill-formed. C++11 drops this restriction.
  4578. if (RD->isUnion())
  4579. Diag(D.getIdentifierLoc(),
  4580. getLangOpts().CPlusPlus11
  4581. ? diag::warn_cxx98_compat_static_data_member_in_union
  4582. : diag::ext_static_data_member_in_union) << Name;
  4583. // We conservatively disallow static data members in anonymous structs.
  4584. else if (!RD->getDeclName())
  4585. Diag(D.getIdentifierLoc(),
  4586. diag::err_static_data_member_not_allowed_in_anon_struct)
  4587. << Name << RD->isUnion();
  4588. }
  4589. }
  4590. // Match up the template parameter lists with the scope specifier, then
  4591. // determine whether we have a template or a template specialization.
  4592. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  4593. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  4594. D.getCXXScopeSpec(),
  4595. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  4596. ? D.getName().TemplateId
  4597. : 0,
  4598. TemplateParamLists,
  4599. /*never a friend*/ false, IsExplicitSpecialization, Invalid);
  4600. if (TemplateParams) {
  4601. if (!TemplateParams->size() &&
  4602. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  4603. // There is an extraneous 'template<>' for this variable. Complain
  4604. // about it, but allow the declaration of the variable.
  4605. Diag(TemplateParams->getTemplateLoc(),
  4606. diag::err_template_variable_noparams)
  4607. << II
  4608. << SourceRange(TemplateParams->getTemplateLoc(),
  4609. TemplateParams->getRAngleLoc());
  4610. TemplateParams = 0;
  4611. } else {
  4612. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  4613. // This is an explicit specialization or a partial specialization.
  4614. // FIXME: Check that we can declare a specialization here.
  4615. IsVariableTemplateSpecialization = true;
  4616. IsPartialSpecialization = TemplateParams->size() > 0;
  4617. } else { // if (TemplateParams->size() > 0)
  4618. // This is a template declaration.
  4619. IsVariableTemplate = true;
  4620. // Check that we can declare a template here.
  4621. if (CheckTemplateDeclScope(S, TemplateParams))
  4622. return 0;
  4623. // Only C++1y supports variable templates (N3651).
  4624. Diag(D.getIdentifierLoc(),
  4625. getLangOpts().CPlusPlus1y
  4626. ? diag::warn_cxx11_compat_variable_template
  4627. : diag::ext_variable_template);
  4628. }
  4629. }
  4630. } else {
  4631. assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId &&
  4632. "should have a 'template<>' for this decl");
  4633. }
  4634. if (IsVariableTemplateSpecialization) {
  4635. SourceLocation TemplateKWLoc =
  4636. TemplateParamLists.size() > 0
  4637. ? TemplateParamLists[0]->getTemplateLoc()
  4638. : SourceLocation();
  4639. DeclResult Res = ActOnVarTemplateSpecialization(
  4640. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  4641. IsPartialSpecialization);
  4642. if (Res.isInvalid())
  4643. return 0;
  4644. NewVD = cast<VarDecl>(Res.get());
  4645. AddToScope = false;
  4646. } else
  4647. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  4648. D.getIdentifierLoc(), II, R, TInfo, SC);
  4649. // If this is supposed to be a variable template, create it as such.
  4650. if (IsVariableTemplate) {
  4651. NewTemplate =
  4652. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  4653. TemplateParams, NewVD);
  4654. NewVD->setDescribedVarTemplate(NewTemplate);
  4655. }
  4656. // If this decl has an auto type in need of deduction, make a note of the
  4657. // Decl so we can diagnose uses of it in its own initializer.
  4658. if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
  4659. ParsingInitForAutoVars.insert(NewVD);
  4660. if (D.isInvalidType() || Invalid) {
  4661. NewVD->setInvalidDecl();
  4662. if (NewTemplate)
  4663. NewTemplate->setInvalidDecl();
  4664. }
  4665. SetNestedNameSpecifier(NewVD, D);
  4666. // If we have any template parameter lists that don't directly belong to
  4667. // the variable (matching the scope specifier), store them.
  4668. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  4669. if (TemplateParamLists.size() > VDTemplateParamLists)
  4670. NewVD->setTemplateParameterListsInfo(
  4671. Context, TemplateParamLists.size() - VDTemplateParamLists,
  4672. TemplateParamLists.data());
  4673. if (D.getDeclSpec().isConstexprSpecified())
  4674. NewVD->setConstexpr(true);
  4675. }
  4676. // Set the lexical context. If the declarator has a C++ scope specifier, the
  4677. // lexical context will be different from the semantic context.
  4678. NewVD->setLexicalDeclContext(CurContext);
  4679. if (NewTemplate)
  4680. NewTemplate->setLexicalDeclContext(CurContext);
  4681. if (IsLocalExternDecl)
  4682. NewVD->setLocalExternDecl();
  4683. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  4684. if (NewVD->hasLocalStorage()) {
  4685. // C++11 [dcl.stc]p4:
  4686. // When thread_local is applied to a variable of block scope the
  4687. // storage-class-specifier static is implied if it does not appear
  4688. // explicitly.
  4689. // Core issue: 'static' is not implied if the variable is declared
  4690. // 'extern'.
  4691. if (SCSpec == DeclSpec::SCS_unspecified &&
  4692. TSCS == DeclSpec::TSCS_thread_local &&
  4693. DC->isFunctionOrMethod())
  4694. NewVD->setTSCSpec(TSCS);
  4695. else
  4696. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  4697. diag::err_thread_non_global)
  4698. << DeclSpec::getSpecifierName(TSCS);
  4699. } else if (!Context.getTargetInfo().isTLSSupported())
  4700. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  4701. diag::err_thread_unsupported);
  4702. else
  4703. NewVD->setTSCSpec(TSCS);
  4704. }
  4705. // C99 6.7.4p3
  4706. // An inline definition of a function with external linkage shall
  4707. // not contain a definition of a modifiable object with static or
  4708. // thread storage duration...
  4709. // We only apply this when the function is required to be defined
  4710. // elsewhere, i.e. when the function is not 'extern inline'. Note
  4711. // that a local variable with thread storage duration still has to
  4712. // be marked 'static'. Also note that it's possible to get these
  4713. // semantics in C++ using __attribute__((gnu_inline)).
  4714. if (SC == SC_Static && S->getFnParent() != 0 &&
  4715. !NewVD->getType().isConstQualified()) {
  4716. FunctionDecl *CurFD = getCurFunctionDecl();
  4717. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  4718. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4719. diag::warn_static_local_in_extern_inline);
  4720. MaybeSuggestAddingStaticToDecl(CurFD);
  4721. }
  4722. }
  4723. if (D.getDeclSpec().isModulePrivateSpecified()) {
  4724. if (IsVariableTemplateSpecialization)
  4725. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  4726. << (IsPartialSpecialization ? 1 : 0)
  4727. << FixItHint::CreateRemoval(
  4728. D.getDeclSpec().getModulePrivateSpecLoc());
  4729. else if (IsExplicitSpecialization)
  4730. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  4731. << 2
  4732. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  4733. else if (NewVD->hasLocalStorage())
  4734. Diag(NewVD->getLocation(), diag::err_module_private_local)
  4735. << 0 << NewVD->getDeclName()
  4736. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  4737. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  4738. else {
  4739. NewVD->setModulePrivate();
  4740. if (NewTemplate)
  4741. NewTemplate->setModulePrivate();
  4742. }
  4743. }
  4744. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4745. ProcessDeclAttributes(S, NewVD, D);
  4746. if (getLangOpts().CUDA) {
  4747. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  4748. // storage [duration]."
  4749. if (SC == SC_None && S->getFnParent() != 0 &&
  4750. (NewVD->hasAttr<CUDASharedAttr>() ||
  4751. NewVD->hasAttr<CUDAConstantAttr>())) {
  4752. NewVD->setStorageClass(SC_Static);
  4753. }
  4754. }
  4755. // Ensure that dllimport globals without explicit storage class are treated as
  4756. // extern. The storage class is set above using parsed attributes. Now we can
  4757. // check the VarDecl itself.
  4758. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  4759. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  4760. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  4761. // In auto-retain/release, infer strong retension for variables of
  4762. // retainable type.
  4763. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  4764. NewVD->setInvalidDecl();
  4765. // Handle GNU asm-label extension (encoded as an attribute).
  4766. if (Expr *E = (Expr*)D.getAsmLabel()) {
  4767. // The parser guarantees this is a string.
  4768. StringLiteral *SE = cast<StringLiteral>(E);
  4769. StringRef Label = SE->getString();
  4770. if (S->getFnParent() != 0) {
  4771. switch (SC) {
  4772. case SC_None:
  4773. case SC_Auto:
  4774. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  4775. break;
  4776. case SC_Register:
  4777. // Local Named register
  4778. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  4779. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  4780. break;
  4781. case SC_Static:
  4782. case SC_Extern:
  4783. case SC_PrivateExtern:
  4784. case SC_OpenCLWorkGroupLocal:
  4785. break;
  4786. }
  4787. } else if (SC == SC_Register) {
  4788. // Global Named register
  4789. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  4790. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  4791. }
  4792. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  4793. Context, Label, 0));
  4794. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  4795. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  4796. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  4797. if (I != ExtnameUndeclaredIdentifiers.end()) {
  4798. NewVD->addAttr(I->second);
  4799. ExtnameUndeclaredIdentifiers.erase(I);
  4800. }
  4801. }
  4802. // Diagnose shadowed variables before filtering for scope.
  4803. if (D.getCXXScopeSpec().isEmpty())
  4804. CheckShadow(S, NewVD, Previous);
  4805. // Don't consider existing declarations that are in a different
  4806. // scope and are out-of-semantic-context declarations (if the new
  4807. // declaration has linkage).
  4808. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  4809. D.getCXXScopeSpec().isNotEmpty() ||
  4810. IsExplicitSpecialization ||
  4811. IsVariableTemplateSpecialization);
  4812. // Check whether the previous declaration is in the same block scope. This
  4813. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  4814. if (getLangOpts().CPlusPlus &&
  4815. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  4816. NewVD->setPreviousDeclInSameBlockScope(
  4817. Previous.isSingleResult() && !Previous.isShadowed() &&
  4818. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  4819. if (!getLangOpts().CPlusPlus) {
  4820. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  4821. } else {
  4822. // If this is an explicit specialization of a static data member, check it.
  4823. if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
  4824. CheckMemberSpecialization(NewVD, Previous))
  4825. NewVD->setInvalidDecl();
  4826. // Merge the decl with the existing one if appropriate.
  4827. if (!Previous.empty()) {
  4828. if (Previous.isSingleResult() &&
  4829. isa<FieldDecl>(Previous.getFoundDecl()) &&
  4830. D.getCXXScopeSpec().isSet()) {
  4831. // The user tried to define a non-static data member
  4832. // out-of-line (C++ [dcl.meaning]p1).
  4833. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  4834. << D.getCXXScopeSpec().getRange();
  4835. Previous.clear();
  4836. NewVD->setInvalidDecl();
  4837. }
  4838. } else if (D.getCXXScopeSpec().isSet()) {
  4839. // No previous declaration in the qualifying scope.
  4840. Diag(D.getIdentifierLoc(), diag::err_no_member)
  4841. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  4842. << D.getCXXScopeSpec().getRange();
  4843. NewVD->setInvalidDecl();
  4844. }
  4845. if (!IsVariableTemplateSpecialization)
  4846. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  4847. if (NewTemplate) {
  4848. VarTemplateDecl *PrevVarTemplate =
  4849. NewVD->getPreviousDecl()
  4850. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  4851. : 0;
  4852. // Check the template parameter list of this declaration, possibly
  4853. // merging in the template parameter list from the previous variable
  4854. // template declaration.
  4855. if (CheckTemplateParameterList(
  4856. TemplateParams,
  4857. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  4858. : 0,
  4859. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  4860. DC->isDependentContext())
  4861. ? TPC_ClassTemplateMember
  4862. : TPC_VarTemplate))
  4863. NewVD->setInvalidDecl();
  4864. // If we are providing an explicit specialization of a static variable
  4865. // template, make a note of that.
  4866. if (PrevVarTemplate &&
  4867. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  4868. PrevVarTemplate->setMemberSpecialization();
  4869. }
  4870. }
  4871. ProcessPragmaWeak(S, NewVD);
  4872. // If this is the first declaration of an extern C variable, update
  4873. // the map of such variables.
  4874. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  4875. isIncompleteDeclExternC(*this, NewVD))
  4876. RegisterLocallyScopedExternCDecl(NewVD, S);
  4877. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4878. Decl *ManglingContextDecl;
  4879. if (MangleNumberingContext *MCtx =
  4880. getCurrentMangleNumberContext(NewVD->getDeclContext(),
  4881. ManglingContextDecl)) {
  4882. Context.setManglingNumber(
  4883. NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber()));
  4884. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4885. }
  4886. }
  4887. if (D.isRedeclaration() && !Previous.empty()) {
  4888. checkDLLAttributeRedeclaration(
  4889. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  4890. IsExplicitSpecialization);
  4891. }
  4892. if (NewTemplate) {
  4893. if (NewVD->isInvalidDecl())
  4894. NewTemplate->setInvalidDecl();
  4895. ActOnDocumentableDecl(NewTemplate);
  4896. return NewTemplate;
  4897. }
  4898. return NewVD;
  4899. }
  4900. /// \brief Diagnose variable or built-in function shadowing. Implements
  4901. /// -Wshadow.
  4902. ///
  4903. /// This method is called whenever a VarDecl is added to a "useful"
  4904. /// scope.
  4905. ///
  4906. /// \param S the scope in which the shadowing name is being declared
  4907. /// \param R the lookup of the name
  4908. ///
  4909. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  4910. // Return if warning is ignored.
  4911. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
  4912. DiagnosticsEngine::Ignored)
  4913. return;
  4914. // Don't diagnose declarations at file scope.
  4915. if (D->hasGlobalStorage())
  4916. return;
  4917. DeclContext *NewDC = D->getDeclContext();
  4918. // Only diagnose if we're shadowing an unambiguous field or variable.
  4919. if (R.getResultKind() != LookupResult::Found)
  4920. return;
  4921. NamedDecl* ShadowedDecl = R.getFoundDecl();
  4922. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  4923. return;
  4924. // Fields are not shadowed by variables in C++ static methods.
  4925. if (isa<FieldDecl>(ShadowedDecl))
  4926. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  4927. if (MD->isStatic())
  4928. return;
  4929. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  4930. if (shadowedVar->isExternC()) {
  4931. // For shadowing external vars, make sure that we point to the global
  4932. // declaration, not a locally scoped extern declaration.
  4933. for (auto I : shadowedVar->redecls())
  4934. if (I->isFileVarDecl()) {
  4935. ShadowedDecl = I;
  4936. break;
  4937. }
  4938. }
  4939. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  4940. // Only warn about certain kinds of shadowing for class members.
  4941. if (NewDC && NewDC->isRecord()) {
  4942. // In particular, don't warn about shadowing non-class members.
  4943. if (!OldDC->isRecord())
  4944. return;
  4945. // TODO: should we warn about static data members shadowing
  4946. // static data members from base classes?
  4947. // TODO: don't diagnose for inaccessible shadowed members.
  4948. // This is hard to do perfectly because we might friend the
  4949. // shadowing context, but that's just a false negative.
  4950. }
  4951. // Determine what kind of declaration we're shadowing.
  4952. unsigned Kind;
  4953. if (isa<RecordDecl>(OldDC)) {
  4954. if (isa<FieldDecl>(ShadowedDecl))
  4955. Kind = 3; // field
  4956. else
  4957. Kind = 2; // static data member
  4958. } else if (OldDC->isFileContext())
  4959. Kind = 1; // global
  4960. else
  4961. Kind = 0; // local
  4962. DeclarationName Name = R.getLookupName();
  4963. // Emit warning and note.
  4964. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  4965. return;
  4966. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  4967. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  4968. }
  4969. /// \brief Check -Wshadow without the advantage of a previous lookup.
  4970. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  4971. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
  4972. DiagnosticsEngine::Ignored)
  4973. return;
  4974. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  4975. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  4976. LookupName(R, S);
  4977. CheckShadow(S, D, R);
  4978. }
  4979. /// Check for conflict between this global or extern "C" declaration and
  4980. /// previous global or extern "C" declarations. This is only used in C++.
  4981. template<typename T>
  4982. static bool checkGlobalOrExternCConflict(
  4983. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  4984. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  4985. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  4986. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  4987. // The common case: this global doesn't conflict with any extern "C"
  4988. // declaration.
  4989. return false;
  4990. }
  4991. if (Prev) {
  4992. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  4993. // Both the old and new declarations have C language linkage. This is a
  4994. // redeclaration.
  4995. Previous.clear();
  4996. Previous.addDecl(Prev);
  4997. return true;
  4998. }
  4999. // This is a global, non-extern "C" declaration, and there is a previous
  5000. // non-global extern "C" declaration. Diagnose if this is a variable
  5001. // declaration.
  5002. if (!isa<VarDecl>(ND))
  5003. return false;
  5004. } else {
  5005. // The declaration is extern "C". Check for any declaration in the
  5006. // translation unit which might conflict.
  5007. if (IsGlobal) {
  5008. // We have already performed the lookup into the translation unit.
  5009. IsGlobal = false;
  5010. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5011. I != E; ++I) {
  5012. if (isa<VarDecl>(*I)) {
  5013. Prev = *I;
  5014. break;
  5015. }
  5016. }
  5017. } else {
  5018. DeclContext::lookup_result R =
  5019. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  5020. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  5021. I != E; ++I) {
  5022. if (isa<VarDecl>(*I)) {
  5023. Prev = *I;
  5024. break;
  5025. }
  5026. // FIXME: If we have any other entity with this name in global scope,
  5027. // the declaration is ill-formed, but that is a defect: it breaks the
  5028. // 'stat' hack, for instance. Only variables can have mangled name
  5029. // clashes with extern "C" declarations, so only they deserve a
  5030. // diagnostic.
  5031. }
  5032. }
  5033. if (!Prev)
  5034. return false;
  5035. }
  5036. // Use the first declaration's location to ensure we point at something which
  5037. // is lexically inside an extern "C" linkage-spec.
  5038. assert(Prev && "should have found a previous declaration to diagnose");
  5039. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  5040. Prev = FD->getFirstDecl();
  5041. else
  5042. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  5043. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  5044. << IsGlobal << ND;
  5045. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  5046. << IsGlobal;
  5047. return false;
  5048. }
  5049. /// Apply special rules for handling extern "C" declarations. Returns \c true
  5050. /// if we have found that this is a redeclaration of some prior entity.
  5051. ///
  5052. /// Per C++ [dcl.link]p6:
  5053. /// Two declarations [for a function or variable] with C language linkage
  5054. /// with the same name that appear in different scopes refer to the same
  5055. /// [entity]. An entity with C language linkage shall not be declared with
  5056. /// the same name as an entity in global scope.
  5057. template<typename T>
  5058. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  5059. LookupResult &Previous) {
  5060. if (!S.getLangOpts().CPlusPlus) {
  5061. // In C, when declaring a global variable, look for a corresponding 'extern'
  5062. // variable declared in function scope. We don't need this in C++, because
  5063. // we find local extern decls in the surrounding file-scope DeclContext.
  5064. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5065. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  5066. Previous.clear();
  5067. Previous.addDecl(Prev);
  5068. return true;
  5069. }
  5070. }
  5071. return false;
  5072. }
  5073. // A declaration in the translation unit can conflict with an extern "C"
  5074. // declaration.
  5075. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  5076. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  5077. // An extern "C" declaration can conflict with a declaration in the
  5078. // translation unit or can be a redeclaration of an extern "C" declaration
  5079. // in another scope.
  5080. if (isIncompleteDeclExternC(S,ND))
  5081. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  5082. // Neither global nor extern "C": nothing to do.
  5083. return false;
  5084. }
  5085. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  5086. // If the decl is already known invalid, don't check it.
  5087. if (NewVD->isInvalidDecl())
  5088. return;
  5089. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  5090. QualType T = TInfo->getType();
  5091. // Defer checking an 'auto' type until its initializer is attached.
  5092. if (T->isUndeducedType())
  5093. return;
  5094. if (NewVD->hasAttrs())
  5095. CheckAlignasUnderalignment(NewVD);
  5096. if (T->isObjCObjectType()) {
  5097. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  5098. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  5099. T = Context.getObjCObjectPointerType(T);
  5100. NewVD->setType(T);
  5101. }
  5102. // Emit an error if an address space was applied to decl with local storage.
  5103. // This includes arrays of objects with address space qualifiers, but not
  5104. // automatic variables that point to other address spaces.
  5105. // ISO/IEC TR 18037 S5.1.2
  5106. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  5107. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  5108. NewVD->setInvalidDecl();
  5109. return;
  5110. }
  5111. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  5112. // __constant address space.
  5113. if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
  5114. && T.getAddressSpace() != LangAS::opencl_constant
  5115. && !T->isSamplerT()){
  5116. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
  5117. NewVD->setInvalidDecl();
  5118. return;
  5119. }
  5120. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  5121. // scope.
  5122. if ((getLangOpts().OpenCLVersion >= 120)
  5123. && NewVD->isStaticLocal()) {
  5124. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  5125. NewVD->setInvalidDecl();
  5126. return;
  5127. }
  5128. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  5129. && !NewVD->hasAttr<BlocksAttr>()) {
  5130. if (getLangOpts().getGC() != LangOptions::NonGC)
  5131. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  5132. else {
  5133. assert(!getLangOpts().ObjCAutoRefCount);
  5134. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  5135. }
  5136. }
  5137. bool isVM = T->isVariablyModifiedType();
  5138. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  5139. NewVD->hasAttr<BlocksAttr>())
  5140. getCurFunction()->setHasBranchProtectedScope();
  5141. if ((isVM && NewVD->hasLinkage()) ||
  5142. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  5143. bool SizeIsNegative;
  5144. llvm::APSInt Oversized;
  5145. TypeSourceInfo *FixedTInfo =
  5146. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5147. SizeIsNegative, Oversized);
  5148. if (FixedTInfo == 0 && T->isVariableArrayType()) {
  5149. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  5150. // FIXME: This won't give the correct result for
  5151. // int a[10][n];
  5152. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  5153. if (NewVD->isFileVarDecl())
  5154. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  5155. << SizeRange;
  5156. else if (NewVD->isStaticLocal())
  5157. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  5158. << SizeRange;
  5159. else
  5160. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  5161. << SizeRange;
  5162. NewVD->setInvalidDecl();
  5163. return;
  5164. }
  5165. if (FixedTInfo == 0) {
  5166. if (NewVD->isFileVarDecl())
  5167. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  5168. else
  5169. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  5170. NewVD->setInvalidDecl();
  5171. return;
  5172. }
  5173. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  5174. NewVD->setType(FixedTInfo->getType());
  5175. NewVD->setTypeSourceInfo(FixedTInfo);
  5176. }
  5177. if (T->isVoidType()) {
  5178. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  5179. // of objects and functions.
  5180. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  5181. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  5182. << T;
  5183. NewVD->setInvalidDecl();
  5184. return;
  5185. }
  5186. }
  5187. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  5188. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  5189. NewVD->setInvalidDecl();
  5190. return;
  5191. }
  5192. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  5193. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  5194. NewVD->setInvalidDecl();
  5195. return;
  5196. }
  5197. if (NewVD->isConstexpr() && !T->isDependentType() &&
  5198. RequireLiteralType(NewVD->getLocation(), T,
  5199. diag::err_constexpr_var_non_literal)) {
  5200. NewVD->setInvalidDecl();
  5201. return;
  5202. }
  5203. }
  5204. /// \brief Perform semantic checking on a newly-created variable
  5205. /// declaration.
  5206. ///
  5207. /// This routine performs all of the type-checking required for a
  5208. /// variable declaration once it has been built. It is used both to
  5209. /// check variables after they have been parsed and their declarators
  5210. /// have been translated into a declaration, and to check variables
  5211. /// that have been instantiated from a template.
  5212. ///
  5213. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  5214. ///
  5215. /// Returns true if the variable declaration is a redeclaration.
  5216. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  5217. CheckVariableDeclarationType(NewVD);
  5218. // If the decl is already known invalid, don't check it.
  5219. if (NewVD->isInvalidDecl())
  5220. return false;
  5221. // If we did not find anything by this name, look for a non-visible
  5222. // extern "C" declaration with the same name.
  5223. if (Previous.empty() &&
  5224. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  5225. Previous.setShadowed();
  5226. // Filter out any non-conflicting previous declarations.
  5227. filterNonConflictingPreviousDecls(Context, NewVD, Previous);
  5228. if (!Previous.empty()) {
  5229. MergeVarDecl(NewVD, Previous);
  5230. return true;
  5231. }
  5232. return false;
  5233. }
  5234. /// \brief Data used with FindOverriddenMethod
  5235. struct FindOverriddenMethodData {
  5236. Sema *S;
  5237. CXXMethodDecl *Method;
  5238. };
  5239. /// \brief Member lookup function that determines whether a given C++
  5240. /// method overrides a method in a base class, to be used with
  5241. /// CXXRecordDecl::lookupInBases().
  5242. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  5243. CXXBasePath &Path,
  5244. void *UserData) {
  5245. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  5246. FindOverriddenMethodData *Data
  5247. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  5248. DeclarationName Name = Data->Method->getDeclName();
  5249. // FIXME: Do we care about other names here too?
  5250. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5251. // We really want to find the base class destructor here.
  5252. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  5253. CanQualType CT = Data->S->Context.getCanonicalType(T);
  5254. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  5255. }
  5256. for (Path.Decls = BaseRecord->lookup(Name);
  5257. !Path.Decls.empty();
  5258. Path.Decls = Path.Decls.slice(1)) {
  5259. NamedDecl *D = Path.Decls.front();
  5260. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  5261. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  5262. return true;
  5263. }
  5264. }
  5265. return false;
  5266. }
  5267. namespace {
  5268. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  5269. }
  5270. /// \brief Report an error regarding overriding, along with any relevant
  5271. /// overriden methods.
  5272. ///
  5273. /// \param DiagID the primary error to report.
  5274. /// \param MD the overriding method.
  5275. /// \param OEK which overrides to include as notes.
  5276. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  5277. OverrideErrorKind OEK = OEK_All) {
  5278. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  5279. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  5280. E = MD->end_overridden_methods();
  5281. I != E; ++I) {
  5282. // This check (& the OEK parameter) could be replaced by a predicate, but
  5283. // without lambdas that would be overkill. This is still nicer than writing
  5284. // out the diag loop 3 times.
  5285. if ((OEK == OEK_All) ||
  5286. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  5287. (OEK == OEK_Deleted && (*I)->isDeleted()))
  5288. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  5289. }
  5290. }
  5291. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  5292. /// and if so, check that it's a valid override and remember it.
  5293. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  5294. // Look for virtual methods in base classes that this method might override.
  5295. CXXBasePaths Paths;
  5296. FindOverriddenMethodData Data;
  5297. Data.Method = MD;
  5298. Data.S = this;
  5299. bool hasDeletedOverridenMethods = false;
  5300. bool hasNonDeletedOverridenMethods = false;
  5301. bool AddedAny = false;
  5302. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  5303. for (auto *I : Paths.found_decls()) {
  5304. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  5305. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  5306. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  5307. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  5308. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  5309. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  5310. hasDeletedOverridenMethods |= OldMD->isDeleted();
  5311. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  5312. AddedAny = true;
  5313. }
  5314. }
  5315. }
  5316. }
  5317. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  5318. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  5319. }
  5320. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  5321. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  5322. }
  5323. return AddedAny;
  5324. }
  5325. namespace {
  5326. // Struct for holding all of the extra arguments needed by
  5327. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  5328. struct ActOnFDArgs {
  5329. Scope *S;
  5330. Declarator &D;
  5331. MultiTemplateParamsArg TemplateParamLists;
  5332. bool AddToScope;
  5333. };
  5334. }
  5335. namespace {
  5336. // Callback to only accept typo corrections that have a non-zero edit distance.
  5337. // Also only accept corrections that have the same parent decl.
  5338. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  5339. public:
  5340. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  5341. CXXRecordDecl *Parent)
  5342. : Context(Context), OriginalFD(TypoFD),
  5343. ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
  5344. bool ValidateCandidate(const TypoCorrection &candidate) override {
  5345. if (candidate.getEditDistance() == 0)
  5346. return false;
  5347. SmallVector<unsigned, 1> MismatchedParams;
  5348. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  5349. CDeclEnd = candidate.end();
  5350. CDecl != CDeclEnd; ++CDecl) {
  5351. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5352. if (FD && !FD->hasBody() &&
  5353. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  5354. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  5355. CXXRecordDecl *Parent = MD->getParent();
  5356. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  5357. return true;
  5358. } else if (!ExpectedParent) {
  5359. return true;
  5360. }
  5361. }
  5362. }
  5363. return false;
  5364. }
  5365. private:
  5366. ASTContext &Context;
  5367. FunctionDecl *OriginalFD;
  5368. CXXRecordDecl *ExpectedParent;
  5369. };
  5370. }
  5371. /// \brief Generate diagnostics for an invalid function redeclaration.
  5372. ///
  5373. /// This routine handles generating the diagnostic messages for an invalid
  5374. /// function redeclaration, including finding possible similar declarations
  5375. /// or performing typo correction if there are no previous declarations with
  5376. /// the same name.
  5377. ///
  5378. /// Returns a NamedDecl iff typo correction was performed and substituting in
  5379. /// the new declaration name does not cause new errors.
  5380. static NamedDecl *DiagnoseInvalidRedeclaration(
  5381. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  5382. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  5383. DeclarationName Name = NewFD->getDeclName();
  5384. DeclContext *NewDC = NewFD->getDeclContext();
  5385. SmallVector<unsigned, 1> MismatchedParams;
  5386. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  5387. TypoCorrection Correction;
  5388. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  5389. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  5390. : diag::err_member_decl_does_not_match;
  5391. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  5392. IsLocalFriend ? Sema::LookupLocalFriendName
  5393. : Sema::LookupOrdinaryName,
  5394. Sema::ForRedeclaration);
  5395. NewFD->setInvalidDecl();
  5396. if (IsLocalFriend)
  5397. SemaRef.LookupName(Prev, S);
  5398. else
  5399. SemaRef.LookupQualifiedName(Prev, NewDC);
  5400. assert(!Prev.isAmbiguous() &&
  5401. "Cannot have an ambiguity in previous-declaration lookup");
  5402. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  5403. DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
  5404. MD ? MD->getParent() : 0);
  5405. if (!Prev.empty()) {
  5406. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  5407. Func != FuncEnd; ++Func) {
  5408. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  5409. if (FD &&
  5410. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5411. // Add 1 to the index so that 0 can mean the mismatch didn't
  5412. // involve a parameter
  5413. unsigned ParamNum =
  5414. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  5415. NearMatches.push_back(std::make_pair(FD, ParamNum));
  5416. }
  5417. }
  5418. // If the qualified name lookup yielded nothing, try typo correction
  5419. } else if ((Correction = SemaRef.CorrectTypo(
  5420. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  5421. &ExtraArgs.D.getCXXScopeSpec(), Validator,
  5422. Sema::CTK_ErrorRecovery, IsLocalFriend ? 0 : NewDC))) {
  5423. // Set up everything for the call to ActOnFunctionDeclarator
  5424. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  5425. ExtraArgs.D.getIdentifierLoc());
  5426. Previous.clear();
  5427. Previous.setLookupName(Correction.getCorrection());
  5428. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  5429. CDeclEnd = Correction.end();
  5430. CDecl != CDeclEnd; ++CDecl) {
  5431. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  5432. if (FD && !FD->hasBody() &&
  5433. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  5434. Previous.addDecl(FD);
  5435. }
  5436. }
  5437. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  5438. NamedDecl *Result;
  5439. // Retry building the function declaration with the new previous
  5440. // declarations, and with errors suppressed.
  5441. {
  5442. // Trap errors.
  5443. Sema::SFINAETrap Trap(SemaRef);
  5444. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  5445. // pieces need to verify the typo-corrected C++ declaration and hopefully
  5446. // eliminate the need for the parameter pack ExtraArgs.
  5447. Result = SemaRef.ActOnFunctionDeclarator(
  5448. ExtraArgs.S, ExtraArgs.D,
  5449. Correction.getCorrectionDecl()->getDeclContext(),
  5450. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  5451. ExtraArgs.AddToScope);
  5452. if (Trap.hasErrorOccurred())
  5453. Result = 0;
  5454. }
  5455. if (Result) {
  5456. // Determine which correction we picked.
  5457. Decl *Canonical = Result->getCanonicalDecl();
  5458. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  5459. I != E; ++I)
  5460. if ((*I)->getCanonicalDecl() == Canonical)
  5461. Correction.setCorrectionDecl(*I);
  5462. SemaRef.diagnoseTypo(
  5463. Correction,
  5464. SemaRef.PDiag(IsLocalFriend
  5465. ? diag::err_no_matching_local_friend_suggest
  5466. : diag::err_member_decl_does_not_match_suggest)
  5467. << Name << NewDC << IsDefinition);
  5468. return Result;
  5469. }
  5470. // Pretend the typo correction never occurred
  5471. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  5472. ExtraArgs.D.getIdentifierLoc());
  5473. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  5474. Previous.clear();
  5475. Previous.setLookupName(Name);
  5476. }
  5477. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  5478. << Name << NewDC << IsDefinition << NewFD->getLocation();
  5479. bool NewFDisConst = false;
  5480. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  5481. NewFDisConst = NewMD->isConst();
  5482. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  5483. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  5484. NearMatch != NearMatchEnd; ++NearMatch) {
  5485. FunctionDecl *FD = NearMatch->first;
  5486. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  5487. bool FDisConst = MD && MD->isConst();
  5488. bool IsMember = MD || !IsLocalFriend;
  5489. // FIXME: These notes are poorly worded for the local friend case.
  5490. if (unsigned Idx = NearMatch->second) {
  5491. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  5492. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  5493. if (Loc.isInvalid()) Loc = FD->getLocation();
  5494. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  5495. : diag::note_local_decl_close_param_match)
  5496. << Idx << FDParam->getType()
  5497. << NewFD->getParamDecl(Idx - 1)->getType();
  5498. } else if (FDisConst != NewFDisConst) {
  5499. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  5500. << NewFDisConst << FD->getSourceRange().getEnd();
  5501. } else
  5502. SemaRef.Diag(FD->getLocation(),
  5503. IsMember ? diag::note_member_def_close_match
  5504. : diag::note_local_decl_close_match);
  5505. }
  5506. return 0;
  5507. }
  5508. static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
  5509. Declarator &D) {
  5510. switch (D.getDeclSpec().getStorageClassSpec()) {
  5511. default: llvm_unreachable("Unknown storage class!");
  5512. case DeclSpec::SCS_auto:
  5513. case DeclSpec::SCS_register:
  5514. case DeclSpec::SCS_mutable:
  5515. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5516. diag::err_typecheck_sclass_func);
  5517. D.setInvalidType();
  5518. break;
  5519. case DeclSpec::SCS_unspecified: break;
  5520. case DeclSpec::SCS_extern:
  5521. if (D.getDeclSpec().isExternInLinkageSpec())
  5522. return SC_None;
  5523. return SC_Extern;
  5524. case DeclSpec::SCS_static: {
  5525. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  5526. // C99 6.7.1p5:
  5527. // The declaration of an identifier for a function that has
  5528. // block scope shall have no explicit storage-class specifier
  5529. // other than extern
  5530. // See also (C++ [dcl.stc]p4).
  5531. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5532. diag::err_static_block_func);
  5533. break;
  5534. } else
  5535. return SC_Static;
  5536. }
  5537. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  5538. }
  5539. // No explicit storage class has already been returned
  5540. return SC_None;
  5541. }
  5542. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  5543. DeclContext *DC, QualType &R,
  5544. TypeSourceInfo *TInfo,
  5545. FunctionDecl::StorageClass SC,
  5546. bool &IsVirtualOkay) {
  5547. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  5548. DeclarationName Name = NameInfo.getName();
  5549. FunctionDecl *NewFD = 0;
  5550. bool isInline = D.getDeclSpec().isInlineSpecified();
  5551. if (!SemaRef.getLangOpts().CPlusPlus) {
  5552. // Determine whether the function was written with a
  5553. // prototype. This true when:
  5554. // - there is a prototype in the declarator, or
  5555. // - the type R of the function is some kind of typedef or other reference
  5556. // to a type name (which eventually refers to a function type).
  5557. bool HasPrototype =
  5558. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  5559. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  5560. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  5561. D.getLocStart(), NameInfo, R,
  5562. TInfo, SC, isInline,
  5563. HasPrototype, false);
  5564. if (D.isInvalidType())
  5565. NewFD->setInvalidDecl();
  5566. // Set the lexical context.
  5567. NewFD->setLexicalDeclContext(SemaRef.CurContext);
  5568. return NewFD;
  5569. }
  5570. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  5571. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  5572. // Check that the return type is not an abstract class type.
  5573. // For record types, this is done by the AbstractClassUsageDiagnoser once
  5574. // the class has been completely parsed.
  5575. if (!DC->isRecord() &&
  5576. SemaRef.RequireNonAbstractType(
  5577. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  5578. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  5579. D.setInvalidType();
  5580. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  5581. // This is a C++ constructor declaration.
  5582. assert(DC->isRecord() &&
  5583. "Constructors can only be declared in a member context");
  5584. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  5585. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  5586. D.getLocStart(), NameInfo,
  5587. R, TInfo, isExplicit, isInline,
  5588. /*isImplicitlyDeclared=*/false,
  5589. isConstexpr);
  5590. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5591. // This is a C++ destructor declaration.
  5592. if (DC->isRecord()) {
  5593. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  5594. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  5595. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  5596. SemaRef.Context, Record,
  5597. D.getLocStart(),
  5598. NameInfo, R, TInfo, isInline,
  5599. /*isImplicitlyDeclared=*/false);
  5600. // If the class is complete, then we now create the implicit exception
  5601. // specification. If the class is incomplete or dependent, we can't do
  5602. // it yet.
  5603. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  5604. Record->getDefinition() && !Record->isBeingDefined() &&
  5605. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  5606. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  5607. }
  5608. IsVirtualOkay = true;
  5609. return NewDD;
  5610. } else {
  5611. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  5612. D.setInvalidType();
  5613. // Create a FunctionDecl to satisfy the function definition parsing
  5614. // code path.
  5615. return FunctionDecl::Create(SemaRef.Context, DC,
  5616. D.getLocStart(),
  5617. D.getIdentifierLoc(), Name, R, TInfo,
  5618. SC, isInline,
  5619. /*hasPrototype=*/true, isConstexpr);
  5620. }
  5621. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  5622. if (!DC->isRecord()) {
  5623. SemaRef.Diag(D.getIdentifierLoc(),
  5624. diag::err_conv_function_not_member);
  5625. return 0;
  5626. }
  5627. SemaRef.CheckConversionDeclarator(D, R, SC);
  5628. IsVirtualOkay = true;
  5629. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  5630. D.getLocStart(), NameInfo,
  5631. R, TInfo, isInline, isExplicit,
  5632. isConstexpr, SourceLocation());
  5633. } else if (DC->isRecord()) {
  5634. // If the name of the function is the same as the name of the record,
  5635. // then this must be an invalid constructor that has a return type.
  5636. // (The parser checks for a return type and makes the declarator a
  5637. // constructor if it has no return type).
  5638. if (Name.getAsIdentifierInfo() &&
  5639. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  5640. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  5641. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  5642. << SourceRange(D.getIdentifierLoc());
  5643. return 0;
  5644. }
  5645. // This is a C++ method declaration.
  5646. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  5647. cast<CXXRecordDecl>(DC),
  5648. D.getLocStart(), NameInfo, R,
  5649. TInfo, SC, isInline,
  5650. isConstexpr, SourceLocation());
  5651. IsVirtualOkay = !Ret->isStatic();
  5652. return Ret;
  5653. } else {
  5654. // Determine whether the function was written with a
  5655. // prototype. This true when:
  5656. // - we're in C++ (where every function has a prototype),
  5657. return FunctionDecl::Create(SemaRef.Context, DC,
  5658. D.getLocStart(),
  5659. NameInfo, R, TInfo, SC, isInline,
  5660. true/*HasPrototype*/, isConstexpr);
  5661. }
  5662. }
  5663. enum OpenCLParamType {
  5664. ValidKernelParam,
  5665. PtrPtrKernelParam,
  5666. PtrKernelParam,
  5667. PrivatePtrKernelParam,
  5668. InvalidKernelParam,
  5669. RecordKernelParam
  5670. };
  5671. static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
  5672. if (PT->isPointerType()) {
  5673. QualType PointeeType = PT->getPointeeType();
  5674. if (PointeeType->isPointerType())
  5675. return PtrPtrKernelParam;
  5676. return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
  5677. : PtrKernelParam;
  5678. }
  5679. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  5680. // be used as builtin types.
  5681. if (PT->isImageType())
  5682. return PtrKernelParam;
  5683. if (PT->isBooleanType())
  5684. return InvalidKernelParam;
  5685. if (PT->isEventT())
  5686. return InvalidKernelParam;
  5687. if (PT->isHalfType())
  5688. return InvalidKernelParam;
  5689. if (PT->isRecordType())
  5690. return RecordKernelParam;
  5691. return ValidKernelParam;
  5692. }
  5693. static void checkIsValidOpenCLKernelParameter(
  5694. Sema &S,
  5695. Declarator &D,
  5696. ParmVarDecl *Param,
  5697. llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
  5698. QualType PT = Param->getType();
  5699. // Cache the valid types we encounter to avoid rechecking structs that are
  5700. // used again
  5701. if (ValidTypes.count(PT.getTypePtr()))
  5702. return;
  5703. switch (getOpenCLKernelParameterType(PT)) {
  5704. case PtrPtrKernelParam:
  5705. // OpenCL v1.2 s6.9.a:
  5706. // A kernel function argument cannot be declared as a
  5707. // pointer to a pointer type.
  5708. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  5709. D.setInvalidType();
  5710. return;
  5711. case PrivatePtrKernelParam:
  5712. // OpenCL v1.2 s6.9.a:
  5713. // A kernel function argument cannot be declared as a
  5714. // pointer to the private address space.
  5715. S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
  5716. D.setInvalidType();
  5717. return;
  5718. // OpenCL v1.2 s6.9.k:
  5719. // Arguments to kernel functions in a program cannot be declared with the
  5720. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  5721. // uintptr_t or a struct and/or union that contain fields declared to be
  5722. // one of these built-in scalar types.
  5723. case InvalidKernelParam:
  5724. // OpenCL v1.2 s6.8 n:
  5725. // A kernel function argument cannot be declared
  5726. // of event_t type.
  5727. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  5728. D.setInvalidType();
  5729. return;
  5730. case PtrKernelParam:
  5731. case ValidKernelParam:
  5732. ValidTypes.insert(PT.getTypePtr());
  5733. return;
  5734. case RecordKernelParam:
  5735. break;
  5736. }
  5737. // Track nested structs we will inspect
  5738. SmallVector<const Decl *, 4> VisitStack;
  5739. // Track where we are in the nested structs. Items will migrate from
  5740. // VisitStack to HistoryStack as we do the DFS for bad field.
  5741. SmallVector<const FieldDecl *, 4> HistoryStack;
  5742. HistoryStack.push_back((const FieldDecl *) 0);
  5743. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  5744. VisitStack.push_back(PD);
  5745. assert(VisitStack.back() && "First decl null?");
  5746. do {
  5747. const Decl *Next = VisitStack.pop_back_val();
  5748. if (!Next) {
  5749. assert(!HistoryStack.empty());
  5750. // Found a marker, we have gone up a level
  5751. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  5752. ValidTypes.insert(Hist->getType().getTypePtr());
  5753. continue;
  5754. }
  5755. // Adds everything except the original parameter declaration (which is not a
  5756. // field itself) to the history stack.
  5757. const RecordDecl *RD;
  5758. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  5759. HistoryStack.push_back(Field);
  5760. RD = Field->getType()->castAs<RecordType>()->getDecl();
  5761. } else {
  5762. RD = cast<RecordDecl>(Next);
  5763. }
  5764. // Add a null marker so we know when we've gone back up a level
  5765. VisitStack.push_back((const Decl *) 0);
  5766. for (const auto *FD : RD->fields()) {
  5767. QualType QT = FD->getType();
  5768. if (ValidTypes.count(QT.getTypePtr()))
  5769. continue;
  5770. OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
  5771. if (ParamType == ValidKernelParam)
  5772. continue;
  5773. if (ParamType == RecordKernelParam) {
  5774. VisitStack.push_back(FD);
  5775. continue;
  5776. }
  5777. // OpenCL v1.2 s6.9.p:
  5778. // Arguments to kernel functions that are declared to be a struct or union
  5779. // do not allow OpenCL objects to be passed as elements of the struct or
  5780. // union.
  5781. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  5782. ParamType == PrivatePtrKernelParam) {
  5783. S.Diag(Param->getLocation(),
  5784. diag::err_record_with_pointers_kernel_param)
  5785. << PT->isUnionType()
  5786. << PT;
  5787. } else {
  5788. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  5789. }
  5790. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  5791. << PD->getDeclName();
  5792. // We have an error, now let's go back up through history and show where
  5793. // the offending field came from
  5794. for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
  5795. E = HistoryStack.end(); I != E; ++I) {
  5796. const FieldDecl *OuterField = *I;
  5797. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  5798. << OuterField->getType();
  5799. }
  5800. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  5801. << QT->isPointerType()
  5802. << QT;
  5803. D.setInvalidType();
  5804. return;
  5805. }
  5806. } while (!VisitStack.empty());
  5807. }
  5808. NamedDecl*
  5809. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  5810. TypeSourceInfo *TInfo, LookupResult &Previous,
  5811. MultiTemplateParamsArg TemplateParamLists,
  5812. bool &AddToScope) {
  5813. QualType R = TInfo->getType();
  5814. assert(R.getTypePtr()->isFunctionType());
  5815. // TODO: consider using NameInfo for diagnostic.
  5816. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  5817. DeclarationName Name = NameInfo.getName();
  5818. FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
  5819. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  5820. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5821. diag::err_invalid_thread)
  5822. << DeclSpec::getSpecifierName(TSCS);
  5823. if (D.isFirstDeclarationOfMember())
  5824. adjustMemberFunctionCC(R, D.isStaticMember());
  5825. bool isFriend = false;
  5826. FunctionTemplateDecl *FunctionTemplate = 0;
  5827. bool isExplicitSpecialization = false;
  5828. bool isFunctionTemplateSpecialization = false;
  5829. bool isDependentClassScopeExplicitSpecialization = false;
  5830. bool HasExplicitTemplateArgs = false;
  5831. TemplateArgumentListInfo TemplateArgs;
  5832. bool isVirtualOkay = false;
  5833. DeclContext *OriginalDC = DC;
  5834. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  5835. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  5836. isVirtualOkay);
  5837. if (!NewFD) return 0;
  5838. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  5839. NewFD->setTopLevelDeclInObjCContainer();
  5840. // Set the lexical context. If this is a function-scope declaration, or has a
  5841. // C++ scope specifier, or is the object of a friend declaration, the lexical
  5842. // context will be different from the semantic context.
  5843. NewFD->setLexicalDeclContext(CurContext);
  5844. if (IsLocalExternDecl)
  5845. NewFD->setLocalExternDecl();
  5846. if (getLangOpts().CPlusPlus) {
  5847. bool isInline = D.getDeclSpec().isInlineSpecified();
  5848. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  5849. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  5850. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  5851. isFriend = D.getDeclSpec().isFriendSpecified();
  5852. if (isFriend && !isInline && D.isFunctionDefinition()) {
  5853. // C++ [class.friend]p5
  5854. // A function can be defined in a friend declaration of a
  5855. // class . . . . Such a function is implicitly inline.
  5856. NewFD->setImplicitlyInline();
  5857. }
  5858. // If this is a method defined in an __interface, and is not a constructor
  5859. // or an overloaded operator, then set the pure flag (isVirtual will already
  5860. // return true).
  5861. if (const CXXRecordDecl *Parent =
  5862. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  5863. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  5864. NewFD->setPure(true);
  5865. }
  5866. SetNestedNameSpecifier(NewFD, D);
  5867. isExplicitSpecialization = false;
  5868. isFunctionTemplateSpecialization = false;
  5869. if (D.isInvalidType())
  5870. NewFD->setInvalidDecl();
  5871. // Match up the template parameter lists with the scope specifier, then
  5872. // determine whether we have a template or a template specialization.
  5873. bool Invalid = false;
  5874. if (TemplateParameterList *TemplateParams =
  5875. MatchTemplateParametersToScopeSpecifier(
  5876. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5877. D.getCXXScopeSpec(),
  5878. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5879. ? D.getName().TemplateId
  5880. : 0,
  5881. TemplateParamLists, isFriend, isExplicitSpecialization,
  5882. Invalid)) {
  5883. if (TemplateParams->size() > 0) {
  5884. // This is a function template
  5885. // Check that we can declare a template here.
  5886. if (CheckTemplateDeclScope(S, TemplateParams))
  5887. return 0;
  5888. // A destructor cannot be a template.
  5889. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  5890. Diag(NewFD->getLocation(), diag::err_destructor_template);
  5891. return 0;
  5892. }
  5893. // If we're adding a template to a dependent context, we may need to
  5894. // rebuilding some of the types used within the template parameter list,
  5895. // now that we know what the current instantiation is.
  5896. if (DC->isDependentContext()) {
  5897. ContextRAII SavedContext(*this, DC);
  5898. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  5899. Invalid = true;
  5900. }
  5901. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  5902. NewFD->getLocation(),
  5903. Name, TemplateParams,
  5904. NewFD);
  5905. FunctionTemplate->setLexicalDeclContext(CurContext);
  5906. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  5907. // For source fidelity, store the other template param lists.
  5908. if (TemplateParamLists.size() > 1) {
  5909. NewFD->setTemplateParameterListsInfo(Context,
  5910. TemplateParamLists.size() - 1,
  5911. TemplateParamLists.data());
  5912. }
  5913. } else {
  5914. // This is a function template specialization.
  5915. isFunctionTemplateSpecialization = true;
  5916. // For source fidelity, store all the template param lists.
  5917. if (TemplateParamLists.size() > 0)
  5918. NewFD->setTemplateParameterListsInfo(Context,
  5919. TemplateParamLists.size(),
  5920. TemplateParamLists.data());
  5921. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  5922. if (isFriend) {
  5923. // We want to remove the "template<>", found here.
  5924. SourceRange RemoveRange = TemplateParams->getSourceRange();
  5925. // If we remove the template<> and the name is not a
  5926. // template-id, we're actually silently creating a problem:
  5927. // the friend declaration will refer to an untemplated decl,
  5928. // and clearly the user wants a template specialization. So
  5929. // we need to insert '<>' after the name.
  5930. SourceLocation InsertLoc;
  5931. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5932. InsertLoc = D.getName().getSourceRange().getEnd();
  5933. InsertLoc = getLocForEndOfToken(InsertLoc);
  5934. }
  5935. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  5936. << Name << RemoveRange
  5937. << FixItHint::CreateRemoval(RemoveRange)
  5938. << FixItHint::CreateInsertion(InsertLoc, "<>");
  5939. }
  5940. }
  5941. }
  5942. else {
  5943. // All template param lists were matched against the scope specifier:
  5944. // this is NOT (an explicit specialization of) a template.
  5945. if (TemplateParamLists.size() > 0)
  5946. // For source fidelity, store all the template param lists.
  5947. NewFD->setTemplateParameterListsInfo(Context,
  5948. TemplateParamLists.size(),
  5949. TemplateParamLists.data());
  5950. }
  5951. if (Invalid) {
  5952. NewFD->setInvalidDecl();
  5953. if (FunctionTemplate)
  5954. FunctionTemplate->setInvalidDecl();
  5955. }
  5956. // C++ [dcl.fct.spec]p5:
  5957. // The virtual specifier shall only be used in declarations of
  5958. // nonstatic class member functions that appear within a
  5959. // member-specification of a class declaration; see 10.3.
  5960. //
  5961. if (isVirtual && !NewFD->isInvalidDecl()) {
  5962. if (!isVirtualOkay) {
  5963. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  5964. diag::err_virtual_non_function);
  5965. } else if (!CurContext->isRecord()) {
  5966. // 'virtual' was specified outside of the class.
  5967. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  5968. diag::err_virtual_out_of_class)
  5969. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  5970. } else if (NewFD->getDescribedFunctionTemplate()) {
  5971. // C++ [temp.mem]p3:
  5972. // A member function template shall not be virtual.
  5973. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  5974. diag::err_virtual_member_function_template)
  5975. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  5976. } else {
  5977. // Okay: Add virtual to the method.
  5978. NewFD->setVirtualAsWritten(true);
  5979. }
  5980. if (getLangOpts().CPlusPlus1y &&
  5981. NewFD->getReturnType()->isUndeducedType())
  5982. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  5983. }
  5984. if (getLangOpts().CPlusPlus1y &&
  5985. (NewFD->isDependentContext() ||
  5986. (isFriend && CurContext->isDependentContext())) &&
  5987. NewFD->getReturnType()->isUndeducedType()) {
  5988. // If the function template is referenced directly (for instance, as a
  5989. // member of the current instantiation), pretend it has a dependent type.
  5990. // This is not really justified by the standard, but is the only sane
  5991. // thing to do.
  5992. // FIXME: For a friend function, we have not marked the function as being
  5993. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  5994. const FunctionProtoType *FPT =
  5995. NewFD->getType()->castAs<FunctionProtoType>();
  5996. QualType Result =
  5997. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  5998. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  5999. FPT->getExtProtoInfo()));
  6000. }
  6001. // C++ [dcl.fct.spec]p3:
  6002. // The inline specifier shall not appear on a block scope function
  6003. // declaration.
  6004. if (isInline && !NewFD->isInvalidDecl()) {
  6005. if (CurContext->isFunctionOrMethod()) {
  6006. // 'inline' is not allowed on block scope function declaration.
  6007. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6008. diag::err_inline_declaration_block_scope) << Name
  6009. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6010. }
  6011. }
  6012. // C++ [dcl.fct.spec]p6:
  6013. // The explicit specifier shall be used only in the declaration of a
  6014. // constructor or conversion function within its class definition;
  6015. // see 12.3.1 and 12.3.2.
  6016. if (isExplicit && !NewFD->isInvalidDecl()) {
  6017. if (!CurContext->isRecord()) {
  6018. // 'explicit' was specified outside of the class.
  6019. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6020. diag::err_explicit_out_of_class)
  6021. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6022. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  6023. !isa<CXXConversionDecl>(NewFD)) {
  6024. // 'explicit' was specified on a function that wasn't a constructor
  6025. // or conversion function.
  6026. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  6027. diag::err_explicit_non_ctor_or_conv_function)
  6028. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  6029. }
  6030. }
  6031. if (isConstexpr) {
  6032. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  6033. // are implicitly inline.
  6034. NewFD->setImplicitlyInline();
  6035. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  6036. // be either constructors or to return a literal type. Therefore,
  6037. // destructors cannot be declared constexpr.
  6038. if (isa<CXXDestructorDecl>(NewFD))
  6039. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  6040. }
  6041. // If __module_private__ was specified, mark the function accordingly.
  6042. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6043. if (isFunctionTemplateSpecialization) {
  6044. SourceLocation ModulePrivateLoc
  6045. = D.getDeclSpec().getModulePrivateSpecLoc();
  6046. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  6047. << 0
  6048. << FixItHint::CreateRemoval(ModulePrivateLoc);
  6049. } else {
  6050. NewFD->setModulePrivate();
  6051. if (FunctionTemplate)
  6052. FunctionTemplate->setModulePrivate();
  6053. }
  6054. }
  6055. if (isFriend) {
  6056. if (FunctionTemplate) {
  6057. FunctionTemplate->setObjectOfFriendDecl();
  6058. FunctionTemplate->setAccess(AS_public);
  6059. }
  6060. NewFD->setObjectOfFriendDecl();
  6061. NewFD->setAccess(AS_public);
  6062. }
  6063. // If a function is defined as defaulted or deleted, mark it as such now.
  6064. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  6065. // definition kind to FDK_Definition.
  6066. switch (D.getFunctionDefinitionKind()) {
  6067. case FDK_Declaration:
  6068. case FDK_Definition:
  6069. break;
  6070. case FDK_Defaulted:
  6071. NewFD->setDefaulted();
  6072. break;
  6073. case FDK_Deleted:
  6074. NewFD->setDeletedAsWritten();
  6075. break;
  6076. }
  6077. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  6078. D.isFunctionDefinition()) {
  6079. // C++ [class.mfct]p2:
  6080. // A member function may be defined (8.4) in its class definition, in
  6081. // which case it is an inline member function (7.1.2)
  6082. NewFD->setImplicitlyInline();
  6083. }
  6084. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  6085. !CurContext->isRecord()) {
  6086. // C++ [class.static]p1:
  6087. // A data or function member of a class may be declared static
  6088. // in a class definition, in which case it is a static member of
  6089. // the class.
  6090. // Complain about the 'static' specifier if it's on an out-of-line
  6091. // member function definition.
  6092. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6093. diag::err_static_out_of_line)
  6094. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6095. }
  6096. // C++11 [except.spec]p15:
  6097. // A deallocation function with no exception-specification is treated
  6098. // as if it were specified with noexcept(true).
  6099. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  6100. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  6101. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  6102. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
  6103. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  6104. EPI.ExceptionSpecType = EST_BasicNoexcept;
  6105. NewFD->setType(Context.getFunctionType(FPT->getReturnType(),
  6106. FPT->getParamTypes(), EPI));
  6107. }
  6108. }
  6109. // Filter out previous declarations that don't match the scope.
  6110. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  6111. D.getCXXScopeSpec().isNotEmpty() ||
  6112. isExplicitSpecialization ||
  6113. isFunctionTemplateSpecialization);
  6114. // Handle GNU asm-label extension (encoded as an attribute).
  6115. if (Expr *E = (Expr*) D.getAsmLabel()) {
  6116. // The parser guarantees this is a string.
  6117. StringLiteral *SE = cast<StringLiteral>(E);
  6118. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  6119. SE->getString(), 0));
  6120. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6121. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6122. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  6123. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6124. NewFD->addAttr(I->second);
  6125. ExtnameUndeclaredIdentifiers.erase(I);
  6126. }
  6127. }
  6128. // Copy the parameter declarations from the declarator D to the function
  6129. // declaration NewFD, if they are available. First scavenge them into Params.
  6130. SmallVector<ParmVarDecl*, 16> Params;
  6131. if (D.isFunctionDeclarator()) {
  6132. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6133. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  6134. // function that takes no arguments, not a function that takes a
  6135. // single void argument.
  6136. // We let through "const void" here because Sema::GetTypeForDeclarator
  6137. // already checks for that case.
  6138. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  6139. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  6140. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  6141. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  6142. Param->setDeclContext(NewFD);
  6143. Params.push_back(Param);
  6144. if (Param->isInvalidDecl())
  6145. NewFD->setInvalidDecl();
  6146. }
  6147. }
  6148. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  6149. // When we're declaring a function with a typedef, typeof, etc as in the
  6150. // following example, we'll need to synthesize (unnamed)
  6151. // parameters for use in the declaration.
  6152. //
  6153. // @code
  6154. // typedef void fn(int);
  6155. // fn f;
  6156. // @endcode
  6157. // Synthesize a parameter for each argument type.
  6158. for (const auto &AI : FT->param_types()) {
  6159. ParmVarDecl *Param =
  6160. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  6161. Param->setScopeInfo(0, Params.size());
  6162. Params.push_back(Param);
  6163. }
  6164. } else {
  6165. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  6166. "Should not need args for typedef of non-prototype fn");
  6167. }
  6168. // Finally, we know we have the right number of parameters, install them.
  6169. NewFD->setParams(Params);
  6170. // Find all anonymous symbols defined during the declaration of this function
  6171. // and add to NewFD. This lets us track decls such 'enum Y' in:
  6172. //
  6173. // void f(enum Y {AA} x) {}
  6174. //
  6175. // which would otherwise incorrectly end up in the translation unit scope.
  6176. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  6177. DeclsInPrototypeScope.clear();
  6178. if (D.getDeclSpec().isNoreturnSpecified())
  6179. NewFD->addAttr(
  6180. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  6181. Context, 0));
  6182. // Functions returning a variably modified type violate C99 6.7.5.2p2
  6183. // because all functions have linkage.
  6184. if (!NewFD->isInvalidDecl() &&
  6185. NewFD->getReturnType()->isVariablyModifiedType()) {
  6186. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  6187. NewFD->setInvalidDecl();
  6188. }
  6189. if (D.isFunctionDefinition() && CodeSegStack.CurrentValue &&
  6190. !NewFD->hasAttr<SectionAttr>()) {
  6191. NewFD->addAttr(
  6192. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  6193. CodeSegStack.CurrentValue->getString(),
  6194. CodeSegStack.CurrentPragmaLocation));
  6195. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  6196. PSF_Implicit | PSF_Execute | PSF_Read, NewFD))
  6197. NewFD->dropAttr<SectionAttr>();
  6198. }
  6199. // Handle attributes.
  6200. ProcessDeclAttributes(S, NewFD, D);
  6201. QualType RetType = NewFD->getReturnType();
  6202. const CXXRecordDecl *Ret = RetType->isRecordType() ?
  6203. RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
  6204. if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
  6205. Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
  6206. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6207. // Attach WarnUnusedResult to functions returning types with that attribute.
  6208. // Don't apply the attribute to that type's own non-static member functions
  6209. // (to avoid warning on things like assignment operators)
  6210. if (!MD || MD->getParent() != Ret)
  6211. NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
  6212. }
  6213. if (getLangOpts().OpenCL) {
  6214. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  6215. // type declaration will generate a compilation error.
  6216. unsigned AddressSpace = RetType.getAddressSpace();
  6217. if (AddressSpace == LangAS::opencl_local ||
  6218. AddressSpace == LangAS::opencl_global ||
  6219. AddressSpace == LangAS::opencl_constant) {
  6220. Diag(NewFD->getLocation(),
  6221. diag::err_opencl_return_value_with_address_space);
  6222. NewFD->setInvalidDecl();
  6223. }
  6224. }
  6225. if (!getLangOpts().CPlusPlus) {
  6226. // Perform semantic checking on the function declaration.
  6227. bool isExplicitSpecialization=false;
  6228. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6229. CheckMain(NewFD, D.getDeclSpec());
  6230. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6231. CheckMSVCRTEntryPoint(NewFD);
  6232. if (!NewFD->isInvalidDecl())
  6233. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6234. isExplicitSpecialization));
  6235. else if (!Previous.empty())
  6236. // Make graceful recovery from an invalid redeclaration.
  6237. D.setRedeclaration(true);
  6238. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6239. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6240. "previous declaration set still overloaded");
  6241. } else {
  6242. // C++11 [replacement.functions]p3:
  6243. // The program's definitions shall not be specified as inline.
  6244. //
  6245. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  6246. //
  6247. // Suppress the diagnostic if the function is __attribute__((used)), since
  6248. // that forces an external definition to be emitted.
  6249. if (D.getDeclSpec().isInlineSpecified() &&
  6250. NewFD->isReplaceableGlobalAllocationFunction() &&
  6251. !NewFD->hasAttr<UsedAttr>())
  6252. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6253. diag::ext_operator_new_delete_declared_inline)
  6254. << NewFD->getDeclName();
  6255. // If the declarator is a template-id, translate the parser's template
  6256. // argument list into our AST format.
  6257. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  6258. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  6259. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  6260. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  6261. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  6262. TemplateId->NumArgs);
  6263. translateTemplateArguments(TemplateArgsPtr,
  6264. TemplateArgs);
  6265. HasExplicitTemplateArgs = true;
  6266. if (NewFD->isInvalidDecl()) {
  6267. HasExplicitTemplateArgs = false;
  6268. } else if (FunctionTemplate) {
  6269. // Function template with explicit template arguments.
  6270. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  6271. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  6272. HasExplicitTemplateArgs = false;
  6273. } else {
  6274. assert((isFunctionTemplateSpecialization ||
  6275. D.getDeclSpec().isFriendSpecified()) &&
  6276. "should have a 'template<>' for this decl");
  6277. // "friend void foo<>(int);" is an implicit specialization decl.
  6278. isFunctionTemplateSpecialization = true;
  6279. }
  6280. } else if (isFriend && isFunctionTemplateSpecialization) {
  6281. // This combination is only possible in a recovery case; the user
  6282. // wrote something like:
  6283. // template <> friend void foo(int);
  6284. // which we're recovering from as if the user had written:
  6285. // friend void foo<>(int);
  6286. // Go ahead and fake up a template id.
  6287. HasExplicitTemplateArgs = true;
  6288. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  6289. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  6290. }
  6291. // If it's a friend (and only if it's a friend), it's possible
  6292. // that either the specialized function type or the specialized
  6293. // template is dependent, and therefore matching will fail. In
  6294. // this case, don't check the specialization yet.
  6295. bool InstantiationDependent = false;
  6296. if (isFunctionTemplateSpecialization && isFriend &&
  6297. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  6298. TemplateSpecializationType::anyDependentTemplateArguments(
  6299. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  6300. InstantiationDependent))) {
  6301. assert(HasExplicitTemplateArgs &&
  6302. "friend function specialization without template args");
  6303. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  6304. Previous))
  6305. NewFD->setInvalidDecl();
  6306. } else if (isFunctionTemplateSpecialization) {
  6307. if (CurContext->isDependentContext() && CurContext->isRecord()
  6308. && !isFriend) {
  6309. isDependentClassScopeExplicitSpecialization = true;
  6310. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  6311. diag::ext_function_specialization_in_class :
  6312. diag::err_function_specialization_in_class)
  6313. << NewFD->getDeclName();
  6314. } else if (CheckFunctionTemplateSpecialization(NewFD,
  6315. (HasExplicitTemplateArgs ? &TemplateArgs : 0),
  6316. Previous))
  6317. NewFD->setInvalidDecl();
  6318. // C++ [dcl.stc]p1:
  6319. // A storage-class-specifier shall not be specified in an explicit
  6320. // specialization (14.7.3)
  6321. FunctionTemplateSpecializationInfo *Info =
  6322. NewFD->getTemplateSpecializationInfo();
  6323. if (Info && SC != SC_None) {
  6324. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  6325. Diag(NewFD->getLocation(),
  6326. diag::err_explicit_specialization_inconsistent_storage_class)
  6327. << SC
  6328. << FixItHint::CreateRemoval(
  6329. D.getDeclSpec().getStorageClassSpecLoc());
  6330. else
  6331. Diag(NewFD->getLocation(),
  6332. diag::ext_explicit_specialization_storage_class)
  6333. << FixItHint::CreateRemoval(
  6334. D.getDeclSpec().getStorageClassSpecLoc());
  6335. }
  6336. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  6337. if (CheckMemberSpecialization(NewFD, Previous))
  6338. NewFD->setInvalidDecl();
  6339. }
  6340. // Perform semantic checking on the function declaration.
  6341. if (!isDependentClassScopeExplicitSpecialization) {
  6342. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  6343. CheckMain(NewFD, D.getDeclSpec());
  6344. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  6345. CheckMSVCRTEntryPoint(NewFD);
  6346. if (!NewFD->isInvalidDecl())
  6347. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  6348. isExplicitSpecialization));
  6349. }
  6350. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  6351. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  6352. "previous declaration set still overloaded");
  6353. NamedDecl *PrincipalDecl = (FunctionTemplate
  6354. ? cast<NamedDecl>(FunctionTemplate)
  6355. : NewFD);
  6356. if (isFriend && D.isRedeclaration()) {
  6357. AccessSpecifier Access = AS_public;
  6358. if (!NewFD->isInvalidDecl())
  6359. Access = NewFD->getPreviousDecl()->getAccess();
  6360. NewFD->setAccess(Access);
  6361. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  6362. }
  6363. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  6364. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  6365. PrincipalDecl->setNonMemberOperator();
  6366. // If we have a function template, check the template parameter
  6367. // list. This will check and merge default template arguments.
  6368. if (FunctionTemplate) {
  6369. FunctionTemplateDecl *PrevTemplate =
  6370. FunctionTemplate->getPreviousDecl();
  6371. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  6372. PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
  6373. D.getDeclSpec().isFriendSpecified()
  6374. ? (D.isFunctionDefinition()
  6375. ? TPC_FriendFunctionTemplateDefinition
  6376. : TPC_FriendFunctionTemplate)
  6377. : (D.getCXXScopeSpec().isSet() &&
  6378. DC && DC->isRecord() &&
  6379. DC->isDependentContext())
  6380. ? TPC_ClassTemplateMember
  6381. : TPC_FunctionTemplate);
  6382. }
  6383. if (NewFD->isInvalidDecl()) {
  6384. // Ignore all the rest of this.
  6385. } else if (!D.isRedeclaration()) {
  6386. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  6387. AddToScope };
  6388. // Fake up an access specifier if it's supposed to be a class member.
  6389. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  6390. NewFD->setAccess(AS_public);
  6391. // Qualified decls generally require a previous declaration.
  6392. if (D.getCXXScopeSpec().isSet()) {
  6393. // ...with the major exception of templated-scope or
  6394. // dependent-scope friend declarations.
  6395. // TODO: we currently also suppress this check in dependent
  6396. // contexts because (1) the parameter depth will be off when
  6397. // matching friend templates and (2) we might actually be
  6398. // selecting a friend based on a dependent factor. But there
  6399. // are situations where these conditions don't apply and we
  6400. // can actually do this check immediately.
  6401. if (isFriend &&
  6402. (TemplateParamLists.size() ||
  6403. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  6404. CurContext->isDependentContext())) {
  6405. // ignore these
  6406. } else {
  6407. // The user tried to provide an out-of-line definition for a
  6408. // function that is a member of a class or namespace, but there
  6409. // was no such member function declared (C++ [class.mfct]p2,
  6410. // C++ [namespace.memdef]p2). For example:
  6411. //
  6412. // class X {
  6413. // void f() const;
  6414. // };
  6415. //
  6416. // void X::f() { } // ill-formed
  6417. //
  6418. // Complain about this problem, and attempt to suggest close
  6419. // matches (e.g., those that differ only in cv-qualifiers and
  6420. // whether the parameter types are references).
  6421. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  6422. *this, Previous, NewFD, ExtraArgs, false, 0)) {
  6423. AddToScope = ExtraArgs.AddToScope;
  6424. return Result;
  6425. }
  6426. }
  6427. // Unqualified local friend declarations are required to resolve
  6428. // to something.
  6429. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  6430. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  6431. *this, Previous, NewFD, ExtraArgs, true, S)) {
  6432. AddToScope = ExtraArgs.AddToScope;
  6433. return Result;
  6434. }
  6435. }
  6436. } else if (!D.isFunctionDefinition() &&
  6437. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  6438. !isFriend && !isFunctionTemplateSpecialization &&
  6439. !isExplicitSpecialization) {
  6440. // An out-of-line member function declaration must also be a
  6441. // definition (C++ [class.mfct]p2).
  6442. // Note that this is not the case for explicit specializations of
  6443. // function templates or member functions of class templates, per
  6444. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  6445. // extension for compatibility with old SWIG code which likes to
  6446. // generate them.
  6447. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  6448. << D.getCXXScopeSpec().getRange();
  6449. }
  6450. }
  6451. ProcessPragmaWeak(S, NewFD);
  6452. checkAttributesAfterMerging(*this, *NewFD);
  6453. AddKnownFunctionAttributes(NewFD);
  6454. if (NewFD->hasAttr<OverloadableAttr>() &&
  6455. !NewFD->getType()->getAs<FunctionProtoType>()) {
  6456. Diag(NewFD->getLocation(),
  6457. diag::err_attribute_overloadable_no_prototype)
  6458. << NewFD;
  6459. // Turn this into a variadic function with no parameters.
  6460. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  6461. FunctionProtoType::ExtProtoInfo EPI(
  6462. Context.getDefaultCallingConvention(true, false));
  6463. EPI.Variadic = true;
  6464. EPI.ExtInfo = FT->getExtInfo();
  6465. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  6466. NewFD->setType(R);
  6467. }
  6468. // If there's a #pragma GCC visibility in scope, and this isn't a class
  6469. // member, set the visibility of this function.
  6470. if (!DC->isRecord() && NewFD->isExternallyVisible())
  6471. AddPushedVisibilityAttribute(NewFD);
  6472. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  6473. // marking the function.
  6474. AddCFAuditedAttribute(NewFD);
  6475. // If this is a function definition, check if we have to apply optnone due to
  6476. // a pragma.
  6477. if(D.isFunctionDefinition())
  6478. AddRangeBasedOptnone(NewFD);
  6479. // If this is the first declaration of an extern C variable, update
  6480. // the map of such variables.
  6481. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  6482. isIncompleteDeclExternC(*this, NewFD))
  6483. RegisterLocallyScopedExternCDecl(NewFD, S);
  6484. // Set this FunctionDecl's range up to the right paren.
  6485. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  6486. if (D.isRedeclaration() && !Previous.empty()) {
  6487. checkDLLAttributeRedeclaration(
  6488. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  6489. isExplicitSpecialization || isFunctionTemplateSpecialization);
  6490. }
  6491. if (getLangOpts().CPlusPlus) {
  6492. if (FunctionTemplate) {
  6493. if (NewFD->isInvalidDecl())
  6494. FunctionTemplate->setInvalidDecl();
  6495. return FunctionTemplate;
  6496. }
  6497. }
  6498. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  6499. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  6500. if ((getLangOpts().OpenCLVersion >= 120)
  6501. && (SC == SC_Static)) {
  6502. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  6503. D.setInvalidType();
  6504. }
  6505. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  6506. if (!NewFD->getReturnType()->isVoidType()) {
  6507. Diag(D.getIdentifierLoc(),
  6508. diag::err_expected_kernel_void_return_type);
  6509. D.setInvalidType();
  6510. }
  6511. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  6512. for (auto Param : NewFD->params())
  6513. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  6514. }
  6515. MarkUnusedFileScopedDecl(NewFD);
  6516. if (getLangOpts().CUDA)
  6517. if (IdentifierInfo *II = NewFD->getIdentifier())
  6518. if (!NewFD->isInvalidDecl() &&
  6519. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6520. if (II->isStr("cudaConfigureCall")) {
  6521. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  6522. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  6523. Context.setcudaConfigureCallDecl(NewFD);
  6524. }
  6525. }
  6526. // Here we have an function template explicit specialization at class scope.
  6527. // The actually specialization will be postponed to template instatiation
  6528. // time via the ClassScopeFunctionSpecializationDecl node.
  6529. if (isDependentClassScopeExplicitSpecialization) {
  6530. ClassScopeFunctionSpecializationDecl *NewSpec =
  6531. ClassScopeFunctionSpecializationDecl::Create(
  6532. Context, CurContext, SourceLocation(),
  6533. cast<CXXMethodDecl>(NewFD),
  6534. HasExplicitTemplateArgs, TemplateArgs);
  6535. CurContext->addDecl(NewSpec);
  6536. AddToScope = false;
  6537. }
  6538. return NewFD;
  6539. }
  6540. /// \brief Perform semantic checking of a new function declaration.
  6541. ///
  6542. /// Performs semantic analysis of the new function declaration
  6543. /// NewFD. This routine performs all semantic checking that does not
  6544. /// require the actual declarator involved in the declaration, and is
  6545. /// used both for the declaration of functions as they are parsed
  6546. /// (called via ActOnDeclarator) and for the declaration of functions
  6547. /// that have been instantiated via C++ template instantiation (called
  6548. /// via InstantiateDecl).
  6549. ///
  6550. /// \param IsExplicitSpecialization whether this new function declaration is
  6551. /// an explicit specialization of the previous declaration.
  6552. ///
  6553. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  6554. ///
  6555. /// \returns true if the function declaration is a redeclaration.
  6556. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  6557. LookupResult &Previous,
  6558. bool IsExplicitSpecialization) {
  6559. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  6560. "Variably modified return types are not handled here");
  6561. // Determine whether the type of this function should be merged with
  6562. // a previous visible declaration. This never happens for functions in C++,
  6563. // and always happens in C if the previous declaration was visible.
  6564. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  6565. !Previous.isShadowed();
  6566. // Filter out any non-conflicting previous declarations.
  6567. filterNonConflictingPreviousDecls(Context, NewFD, Previous);
  6568. bool Redeclaration = false;
  6569. NamedDecl *OldDecl = 0;
  6570. // Merge or overload the declaration with an existing declaration of
  6571. // the same name, if appropriate.
  6572. if (!Previous.empty()) {
  6573. // Determine whether NewFD is an overload of PrevDecl or
  6574. // a declaration that requires merging. If it's an overload,
  6575. // there's no more work to do here; we'll just add the new
  6576. // function to the scope.
  6577. if (!AllowOverloadingOfFunction(Previous, Context)) {
  6578. NamedDecl *Candidate = Previous.getFoundDecl();
  6579. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  6580. Redeclaration = true;
  6581. OldDecl = Candidate;
  6582. }
  6583. } else {
  6584. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  6585. /*NewIsUsingDecl*/ false)) {
  6586. case Ovl_Match:
  6587. Redeclaration = true;
  6588. break;
  6589. case Ovl_NonFunction:
  6590. Redeclaration = true;
  6591. break;
  6592. case Ovl_Overload:
  6593. Redeclaration = false;
  6594. break;
  6595. }
  6596. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  6597. // If a function name is overloadable in C, then every function
  6598. // with that name must be marked "overloadable".
  6599. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  6600. << Redeclaration << NewFD;
  6601. NamedDecl *OverloadedDecl = 0;
  6602. if (Redeclaration)
  6603. OverloadedDecl = OldDecl;
  6604. else if (!Previous.empty())
  6605. OverloadedDecl = Previous.getRepresentativeDecl();
  6606. if (OverloadedDecl)
  6607. Diag(OverloadedDecl->getLocation(),
  6608. diag::note_attribute_overloadable_prev_overload);
  6609. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  6610. }
  6611. }
  6612. }
  6613. // Check for a previous extern "C" declaration with this name.
  6614. if (!Redeclaration &&
  6615. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  6616. filterNonConflictingPreviousDecls(Context, NewFD, Previous);
  6617. if (!Previous.empty()) {
  6618. // This is an extern "C" declaration with the same name as a previous
  6619. // declaration, and thus redeclares that entity...
  6620. Redeclaration = true;
  6621. OldDecl = Previous.getFoundDecl();
  6622. MergeTypeWithPrevious = false;
  6623. // ... except in the presence of __attribute__((overloadable)).
  6624. if (OldDecl->hasAttr<OverloadableAttr>()) {
  6625. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  6626. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  6627. << Redeclaration << NewFD;
  6628. Diag(Previous.getFoundDecl()->getLocation(),
  6629. diag::note_attribute_overloadable_prev_overload);
  6630. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  6631. }
  6632. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  6633. Redeclaration = false;
  6634. OldDecl = 0;
  6635. }
  6636. }
  6637. }
  6638. }
  6639. // C++11 [dcl.constexpr]p8:
  6640. // A constexpr specifier for a non-static member function that is not
  6641. // a constructor declares that member function to be const.
  6642. //
  6643. // This needs to be delayed until we know whether this is an out-of-line
  6644. // definition of a static member function.
  6645. //
  6646. // This rule is not present in C++1y, so we produce a backwards
  6647. // compatibility warning whenever it happens in C++11.
  6648. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6649. if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
  6650. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  6651. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  6652. CXXMethodDecl *OldMD = 0;
  6653. if (OldDecl)
  6654. OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction());
  6655. if (!OldMD || !OldMD->isStatic()) {
  6656. const FunctionProtoType *FPT =
  6657. MD->getType()->castAs<FunctionProtoType>();
  6658. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  6659. EPI.TypeQuals |= Qualifiers::Const;
  6660. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  6661. FPT->getParamTypes(), EPI));
  6662. // Warn that we did this, if we're not performing template instantiation.
  6663. // In that case, we'll have warned already when the template was defined.
  6664. if (ActiveTemplateInstantiations.empty()) {
  6665. SourceLocation AddConstLoc;
  6666. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  6667. .IgnoreParens().getAs<FunctionTypeLoc>())
  6668. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  6669. Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
  6670. << FixItHint::CreateInsertion(AddConstLoc, " const");
  6671. }
  6672. }
  6673. }
  6674. if (Redeclaration) {
  6675. // NewFD and OldDecl represent declarations that need to be
  6676. // merged.
  6677. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  6678. NewFD->setInvalidDecl();
  6679. return Redeclaration;
  6680. }
  6681. Previous.clear();
  6682. Previous.addDecl(OldDecl);
  6683. if (FunctionTemplateDecl *OldTemplateDecl
  6684. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  6685. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  6686. FunctionTemplateDecl *NewTemplateDecl
  6687. = NewFD->getDescribedFunctionTemplate();
  6688. assert(NewTemplateDecl && "Template/non-template mismatch");
  6689. if (CXXMethodDecl *Method
  6690. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  6691. Method->setAccess(OldTemplateDecl->getAccess());
  6692. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  6693. }
  6694. // If this is an explicit specialization of a member that is a function
  6695. // template, mark it as a member specialization.
  6696. if (IsExplicitSpecialization &&
  6697. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  6698. NewTemplateDecl->setMemberSpecialization();
  6699. assert(OldTemplateDecl->isMemberSpecialization());
  6700. }
  6701. } else {
  6702. // This needs to happen first so that 'inline' propagates.
  6703. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  6704. if (isa<CXXMethodDecl>(NewFD)) {
  6705. // A valid redeclaration of a C++ method must be out-of-line,
  6706. // but (unfortunately) it's not necessarily a definition
  6707. // because of templates, which means that the previous
  6708. // declaration is not necessarily from the class definition.
  6709. // For just setting the access, that doesn't matter.
  6710. CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
  6711. NewFD->setAccess(oldMethod->getAccess());
  6712. // Update the key-function state if necessary for this ABI.
  6713. if (NewFD->isInlined() &&
  6714. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  6715. // setNonKeyFunction needs to work with the original
  6716. // declaration from the class definition, and isVirtual() is
  6717. // just faster in that case, so map back to that now.
  6718. oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
  6719. if (oldMethod->isVirtual()) {
  6720. Context.setNonKeyFunction(oldMethod);
  6721. }
  6722. }
  6723. }
  6724. }
  6725. }
  6726. // Semantic checking for this function declaration (in isolation).
  6727. if (getLangOpts().CPlusPlus) {
  6728. // C++-specific checks.
  6729. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  6730. CheckConstructor(Constructor);
  6731. } else if (CXXDestructorDecl *Destructor =
  6732. dyn_cast<CXXDestructorDecl>(NewFD)) {
  6733. CXXRecordDecl *Record = Destructor->getParent();
  6734. QualType ClassType = Context.getTypeDeclType(Record);
  6735. // FIXME: Shouldn't we be able to perform this check even when the class
  6736. // type is dependent? Both gcc and edg can handle that.
  6737. if (!ClassType->isDependentType()) {
  6738. DeclarationName Name
  6739. = Context.DeclarationNames.getCXXDestructorName(
  6740. Context.getCanonicalType(ClassType));
  6741. if (NewFD->getDeclName() != Name) {
  6742. Diag(NewFD->getLocation(), diag::err_destructor_name);
  6743. NewFD->setInvalidDecl();
  6744. return Redeclaration;
  6745. }
  6746. }
  6747. } else if (CXXConversionDecl *Conversion
  6748. = dyn_cast<CXXConversionDecl>(NewFD)) {
  6749. ActOnConversionDeclarator(Conversion);
  6750. }
  6751. // Find any virtual functions that this function overrides.
  6752. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  6753. if (!Method->isFunctionTemplateSpecialization() &&
  6754. !Method->getDescribedFunctionTemplate() &&
  6755. Method->isCanonicalDecl()) {
  6756. if (AddOverriddenMethods(Method->getParent(), Method)) {
  6757. // If the function was marked as "static", we have a problem.
  6758. if (NewFD->getStorageClass() == SC_Static) {
  6759. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  6760. }
  6761. }
  6762. }
  6763. if (Method->isStatic())
  6764. checkThisInStaticMemberFunctionType(Method);
  6765. }
  6766. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  6767. if (NewFD->isOverloadedOperator() &&
  6768. CheckOverloadedOperatorDeclaration(NewFD)) {
  6769. NewFD->setInvalidDecl();
  6770. return Redeclaration;
  6771. }
  6772. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  6773. if (NewFD->getLiteralIdentifier() &&
  6774. CheckLiteralOperatorDeclaration(NewFD)) {
  6775. NewFD->setInvalidDecl();
  6776. return Redeclaration;
  6777. }
  6778. // In C++, check default arguments now that we have merged decls. Unless
  6779. // the lexical context is the class, because in this case this is done
  6780. // during delayed parsing anyway.
  6781. if (!CurContext->isRecord())
  6782. CheckCXXDefaultArguments(NewFD);
  6783. // If this function declares a builtin function, check the type of this
  6784. // declaration against the expected type for the builtin.
  6785. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  6786. ASTContext::GetBuiltinTypeError Error;
  6787. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  6788. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  6789. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  6790. // The type of this function differs from the type of the builtin,
  6791. // so forget about the builtin entirely.
  6792. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  6793. }
  6794. }
  6795. // If this function is declared as being extern "C", then check to see if
  6796. // the function returns a UDT (class, struct, or union type) that is not C
  6797. // compatible, and if it does, warn the user.
  6798. // But, issue any diagnostic on the first declaration only.
  6799. if (NewFD->isExternC() && Previous.empty()) {
  6800. QualType R = NewFD->getReturnType();
  6801. if (R->isIncompleteType() && !R->isVoidType())
  6802. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  6803. << NewFD << R;
  6804. else if (!R.isPODType(Context) && !R->isVoidType() &&
  6805. !R->isObjCObjectPointerType())
  6806. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  6807. }
  6808. }
  6809. return Redeclaration;
  6810. }
  6811. static SourceRange getResultSourceRange(const FunctionDecl *FD) {
  6812. const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
  6813. if (!TSI)
  6814. return SourceRange();
  6815. TypeLoc TL = TSI->getTypeLoc();
  6816. FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
  6817. if (!FunctionTL)
  6818. return SourceRange();
  6819. TypeLoc ResultTL = FunctionTL.getReturnLoc();
  6820. if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
  6821. return ResultTL.getSourceRange();
  6822. return SourceRange();
  6823. }
  6824. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  6825. // C++11 [basic.start.main]p3:
  6826. // A program that [...] declares main to be inline, static or
  6827. // constexpr is ill-formed.
  6828. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  6829. // appear in a declaration of main.
  6830. // static main is not an error under C99, but we should warn about it.
  6831. // We accept _Noreturn main as an extension.
  6832. if (FD->getStorageClass() == SC_Static)
  6833. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  6834. ? diag::err_static_main : diag::warn_static_main)
  6835. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  6836. if (FD->isInlineSpecified())
  6837. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  6838. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  6839. if (DS.isNoreturnSpecified()) {
  6840. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  6841. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  6842. Diag(NoreturnLoc, diag::ext_noreturn_main);
  6843. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  6844. << FixItHint::CreateRemoval(NoreturnRange);
  6845. }
  6846. if (FD->isConstexpr()) {
  6847. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  6848. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  6849. FD->setConstexpr(false);
  6850. }
  6851. if (getLangOpts().OpenCL) {
  6852. Diag(FD->getLocation(), diag::err_opencl_no_main)
  6853. << FD->hasAttr<OpenCLKernelAttr>();
  6854. FD->setInvalidDecl();
  6855. return;
  6856. }
  6857. QualType T = FD->getType();
  6858. assert(T->isFunctionType() && "function decl is not of function type");
  6859. const FunctionType* FT = T->castAs<FunctionType>();
  6860. // All the standards say that main() should should return 'int'.
  6861. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) {
  6862. // In C and C++, main magically returns 0 if you fall off the end;
  6863. // set the flag which tells us that.
  6864. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  6865. FD->setHasImplicitReturnZero(true);
  6866. // In C with GNU extensions we allow main() to have non-integer return
  6867. // type, but we should warn about the extension, and we disable the
  6868. // implicit-return-zero rule.
  6869. } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  6870. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  6871. SourceRange ResultRange = getResultSourceRange(FD);
  6872. if (ResultRange.isValid())
  6873. Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
  6874. << FixItHint::CreateReplacement(ResultRange, "int");
  6875. // Otherwise, this is just a flat-out error.
  6876. } else {
  6877. SourceRange ResultRange = getResultSourceRange(FD);
  6878. if (ResultRange.isValid())
  6879. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  6880. << FixItHint::CreateReplacement(ResultRange, "int");
  6881. else
  6882. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
  6883. FD->setInvalidDecl(true);
  6884. }
  6885. // Treat protoless main() as nullary.
  6886. if (isa<FunctionNoProtoType>(FT)) return;
  6887. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  6888. unsigned nparams = FTP->getNumParams();
  6889. assert(FD->getNumParams() == nparams);
  6890. bool HasExtraParameters = (nparams > 3);
  6891. // Darwin passes an undocumented fourth argument of type char**. If
  6892. // other platforms start sprouting these, the logic below will start
  6893. // getting shifty.
  6894. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  6895. HasExtraParameters = false;
  6896. if (HasExtraParameters) {
  6897. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  6898. FD->setInvalidDecl(true);
  6899. nparams = 3;
  6900. }
  6901. // FIXME: a lot of the following diagnostics would be improved
  6902. // if we had some location information about types.
  6903. QualType CharPP =
  6904. Context.getPointerType(Context.getPointerType(Context.CharTy));
  6905. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  6906. for (unsigned i = 0; i < nparams; ++i) {
  6907. QualType AT = FTP->getParamType(i);
  6908. bool mismatch = true;
  6909. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  6910. mismatch = false;
  6911. else if (Expected[i] == CharPP) {
  6912. // As an extension, the following forms are okay:
  6913. // char const **
  6914. // char const * const *
  6915. // char * const *
  6916. QualifierCollector qs;
  6917. const PointerType* PT;
  6918. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  6919. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  6920. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  6921. Context.CharTy)) {
  6922. qs.removeConst();
  6923. mismatch = !qs.empty();
  6924. }
  6925. }
  6926. if (mismatch) {
  6927. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  6928. // TODO: suggest replacing given type with expected type
  6929. FD->setInvalidDecl(true);
  6930. }
  6931. }
  6932. if (nparams == 1 && !FD->isInvalidDecl()) {
  6933. Diag(FD->getLocation(), diag::warn_main_one_arg);
  6934. }
  6935. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  6936. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  6937. FD->setInvalidDecl();
  6938. }
  6939. }
  6940. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  6941. QualType T = FD->getType();
  6942. assert(T->isFunctionType() && "function decl is not of function type");
  6943. const FunctionType *FT = T->castAs<FunctionType>();
  6944. // Set an implicit return of 'zero' if the function can return some integral,
  6945. // enumeration, pointer or nullptr type.
  6946. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  6947. FT->getReturnType()->isAnyPointerType() ||
  6948. FT->getReturnType()->isNullPtrType())
  6949. // DllMain is exempt because a return value of zero means it failed.
  6950. if (FD->getName() != "DllMain")
  6951. FD->setHasImplicitReturnZero(true);
  6952. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  6953. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  6954. FD->setInvalidDecl();
  6955. }
  6956. }
  6957. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  6958. // FIXME: Need strict checking. In C89, we need to check for
  6959. // any assignment, increment, decrement, function-calls, or
  6960. // commas outside of a sizeof. In C99, it's the same list,
  6961. // except that the aforementioned are allowed in unevaluated
  6962. // expressions. Everything else falls under the
  6963. // "may accept other forms of constant expressions" exception.
  6964. // (We never end up here for C++, so the constant expression
  6965. // rules there don't matter.)
  6966. const Expr *Culprit;
  6967. if (Init->isConstantInitializer(Context, false, &Culprit))
  6968. return false;
  6969. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  6970. << Culprit->getSourceRange();
  6971. return true;
  6972. }
  6973. namespace {
  6974. // Visits an initialization expression to see if OrigDecl is evaluated in
  6975. // its own initialization and throws a warning if it does.
  6976. class SelfReferenceChecker
  6977. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  6978. Sema &S;
  6979. Decl *OrigDecl;
  6980. bool isRecordType;
  6981. bool isPODType;
  6982. bool isReferenceType;
  6983. public:
  6984. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  6985. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  6986. S(S), OrigDecl(OrigDecl) {
  6987. isPODType = false;
  6988. isRecordType = false;
  6989. isReferenceType = false;
  6990. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  6991. isPODType = VD->getType().isPODType(S.Context);
  6992. isRecordType = VD->getType()->isRecordType();
  6993. isReferenceType = VD->getType()->isReferenceType();
  6994. }
  6995. }
  6996. // For most expressions, the cast is directly above the DeclRefExpr.
  6997. // For conditional operators, the cast can be outside the conditional
  6998. // operator if both expressions are DeclRefExpr's.
  6999. void HandleValue(Expr *E) {
  7000. if (isReferenceType)
  7001. return;
  7002. E = E->IgnoreParenImpCasts();
  7003. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  7004. HandleDeclRefExpr(DRE);
  7005. return;
  7006. }
  7007. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  7008. HandleValue(CO->getTrueExpr());
  7009. HandleValue(CO->getFalseExpr());
  7010. return;
  7011. }
  7012. if (isa<MemberExpr>(E)) {
  7013. Expr *Base = E->IgnoreParenImpCasts();
  7014. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7015. // Check for static member variables and don't warn on them.
  7016. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7017. return;
  7018. Base = ME->getBase()->IgnoreParenImpCasts();
  7019. }
  7020. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  7021. HandleDeclRefExpr(DRE);
  7022. return;
  7023. }
  7024. }
  7025. // Reference types are handled here since all uses of references are
  7026. // bad, not just r-value uses.
  7027. void VisitDeclRefExpr(DeclRefExpr *E) {
  7028. if (isReferenceType)
  7029. HandleDeclRefExpr(E);
  7030. }
  7031. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  7032. if (E->getCastKind() == CK_LValueToRValue ||
  7033. (isRecordType && E->getCastKind() == CK_NoOp))
  7034. HandleValue(E->getSubExpr());
  7035. Inherited::VisitImplicitCastExpr(E);
  7036. }
  7037. void VisitMemberExpr(MemberExpr *E) {
  7038. // Don't warn on arrays since they can be treated as pointers.
  7039. if (E->getType()->canDecayToPointerType()) return;
  7040. // Warn when a non-static method call is followed by non-static member
  7041. // field accesses, which is followed by a DeclRefExpr.
  7042. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  7043. bool Warn = (MD && !MD->isStatic());
  7044. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  7045. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  7046. if (!isa<FieldDecl>(ME->getMemberDecl()))
  7047. Warn = false;
  7048. Base = ME->getBase()->IgnoreParenImpCasts();
  7049. }
  7050. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  7051. if (Warn)
  7052. HandleDeclRefExpr(DRE);
  7053. return;
  7054. }
  7055. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  7056. // Visit that expression.
  7057. Visit(Base);
  7058. }
  7059. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  7060. if (E->getNumArgs() > 0)
  7061. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
  7062. HandleDeclRefExpr(DRE);
  7063. Inherited::VisitCXXOperatorCallExpr(E);
  7064. }
  7065. void VisitUnaryOperator(UnaryOperator *E) {
  7066. // For POD record types, addresses of its own members are well-defined.
  7067. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  7068. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  7069. if (!isPODType)
  7070. HandleValue(E->getSubExpr());
  7071. return;
  7072. }
  7073. Inherited::VisitUnaryOperator(E);
  7074. }
  7075. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  7076. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  7077. Decl* ReferenceDecl = DRE->getDecl();
  7078. if (OrigDecl != ReferenceDecl) return;
  7079. unsigned diag;
  7080. if (isReferenceType) {
  7081. diag = diag::warn_uninit_self_reference_in_reference_init;
  7082. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  7083. diag = diag::warn_static_self_reference_in_init;
  7084. } else {
  7085. diag = diag::warn_uninit_self_reference_in_init;
  7086. }
  7087. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  7088. S.PDiag(diag)
  7089. << DRE->getNameInfo().getName()
  7090. << OrigDecl->getLocation()
  7091. << DRE->getSourceRange());
  7092. }
  7093. };
  7094. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  7095. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  7096. bool DirectInit) {
  7097. // Parameters arguments are occassionially constructed with itself,
  7098. // for instance, in recursive functions. Skip them.
  7099. if (isa<ParmVarDecl>(OrigDecl))
  7100. return;
  7101. E = E->IgnoreParens();
  7102. // Skip checking T a = a where T is not a record or reference type.
  7103. // Doing so is a way to silence uninitialized warnings.
  7104. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  7105. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  7106. if (ICE->getCastKind() == CK_LValueToRValue)
  7107. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  7108. if (DRE->getDecl() == OrigDecl)
  7109. return;
  7110. SelfReferenceChecker(S, OrigDecl).Visit(E);
  7111. }
  7112. }
  7113. /// AddInitializerToDecl - Adds the initializer Init to the
  7114. /// declaration dcl. If DirectInit is true, this is C++ direct
  7115. /// initialization rather than copy initialization.
  7116. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  7117. bool DirectInit, bool TypeMayContainAuto) {
  7118. // If there is no declaration, there was an error parsing it. Just ignore
  7119. // the initializer.
  7120. if (RealDecl == 0 || RealDecl->isInvalidDecl())
  7121. return;
  7122. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  7123. // With declarators parsed the way they are, the parser cannot
  7124. // distinguish between a normal initializer and a pure-specifier.
  7125. // Thus this grotesque test.
  7126. IntegerLiteral *IL;
  7127. if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
  7128. Context.getCanonicalType(IL->getType()) == Context.IntTy)
  7129. CheckPureMethod(Method, Init->getSourceRange());
  7130. else {
  7131. Diag(Method->getLocation(), diag::err_member_function_initialization)
  7132. << Method->getDeclName() << Init->getSourceRange();
  7133. Method->setInvalidDecl();
  7134. }
  7135. return;
  7136. }
  7137. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  7138. if (!VDecl) {
  7139. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  7140. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  7141. RealDecl->setInvalidDecl();
  7142. return;
  7143. }
  7144. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  7145. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  7146. if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
  7147. Expr *DeduceInit = Init;
  7148. // Initializer could be a C++ direct-initializer. Deduction only works if it
  7149. // contains exactly one expression.
  7150. if (CXXDirectInit) {
  7151. if (CXXDirectInit->getNumExprs() == 0) {
  7152. // It isn't possible to write this directly, but it is possible to
  7153. // end up in this situation with "auto x(some_pack...);"
  7154. Diag(CXXDirectInit->getLocStart(),
  7155. VDecl->isInitCapture() ? diag::err_init_capture_no_expression
  7156. : diag::err_auto_var_init_no_expression)
  7157. << VDecl->getDeclName() << VDecl->getType()
  7158. << VDecl->getSourceRange();
  7159. RealDecl->setInvalidDecl();
  7160. return;
  7161. } else if (CXXDirectInit->getNumExprs() > 1) {
  7162. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  7163. VDecl->isInitCapture()
  7164. ? diag::err_init_capture_multiple_expressions
  7165. : diag::err_auto_var_init_multiple_expressions)
  7166. << VDecl->getDeclName() << VDecl->getType()
  7167. << VDecl->getSourceRange();
  7168. RealDecl->setInvalidDecl();
  7169. return;
  7170. } else {
  7171. DeduceInit = CXXDirectInit->getExpr(0);
  7172. if (isa<InitListExpr>(DeduceInit))
  7173. Diag(CXXDirectInit->getLocStart(),
  7174. diag::err_auto_var_init_paren_braces)
  7175. << VDecl->getDeclName() << VDecl->getType()
  7176. << VDecl->getSourceRange();
  7177. }
  7178. }
  7179. // Expressions default to 'id' when we're in a debugger.
  7180. bool DefaultedToAuto = false;
  7181. if (getLangOpts().DebuggerCastResultToId &&
  7182. Init->getType() == Context.UnknownAnyTy) {
  7183. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  7184. if (Result.isInvalid()) {
  7185. VDecl->setInvalidDecl();
  7186. return;
  7187. }
  7188. Init = Result.take();
  7189. DefaultedToAuto = true;
  7190. }
  7191. QualType DeducedType;
  7192. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  7193. DAR_Failed)
  7194. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  7195. if (DeducedType.isNull()) {
  7196. RealDecl->setInvalidDecl();
  7197. return;
  7198. }
  7199. VDecl->setType(DeducedType);
  7200. assert(VDecl->isLinkageValid());
  7201. // In ARC, infer lifetime.
  7202. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  7203. VDecl->setInvalidDecl();
  7204. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  7205. // 'id' instead of a specific object type prevents most of our usual checks.
  7206. // We only want to warn outside of template instantiations, though:
  7207. // inside a template, the 'id' could have come from a parameter.
  7208. if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
  7209. DeducedType->isObjCIdType()) {
  7210. SourceLocation Loc =
  7211. VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
  7212. Diag(Loc, diag::warn_auto_var_is_id)
  7213. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  7214. }
  7215. // If this is a redeclaration, check that the type we just deduced matches
  7216. // the previously declared type.
  7217. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  7218. // We never need to merge the type, because we cannot form an incomplete
  7219. // array of auto, nor deduce such a type.
  7220. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
  7221. }
  7222. // Check the deduced type is valid for a variable declaration.
  7223. CheckVariableDeclarationType(VDecl);
  7224. if (VDecl->isInvalidDecl())
  7225. return;
  7226. }
  7227. // dllimport cannot be used on variable definitions.
  7228. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  7229. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  7230. VDecl->setInvalidDecl();
  7231. return;
  7232. }
  7233. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  7234. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  7235. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  7236. VDecl->setInvalidDecl();
  7237. return;
  7238. }
  7239. if (!VDecl->getType()->isDependentType()) {
  7240. // A definition must end up with a complete type, which means it must be
  7241. // complete with the restriction that an array type might be completed by
  7242. // the initializer; note that later code assumes this restriction.
  7243. QualType BaseDeclType = VDecl->getType();
  7244. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  7245. BaseDeclType = Array->getElementType();
  7246. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  7247. diag::err_typecheck_decl_incomplete_type)) {
  7248. RealDecl->setInvalidDecl();
  7249. return;
  7250. }
  7251. // The variable can not have an abstract class type.
  7252. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  7253. diag::err_abstract_type_in_decl,
  7254. AbstractVariableType))
  7255. VDecl->setInvalidDecl();
  7256. }
  7257. const VarDecl *Def;
  7258. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  7259. Diag(VDecl->getLocation(), diag::err_redefinition)
  7260. << VDecl->getDeclName();
  7261. Diag(Def->getLocation(), diag::note_previous_definition);
  7262. VDecl->setInvalidDecl();
  7263. return;
  7264. }
  7265. const VarDecl* PrevInit = 0;
  7266. if (getLangOpts().CPlusPlus) {
  7267. // C++ [class.static.data]p4
  7268. // If a static data member is of const integral or const
  7269. // enumeration type, its declaration in the class definition can
  7270. // specify a constant-initializer which shall be an integral
  7271. // constant expression (5.19). In that case, the member can appear
  7272. // in integral constant expressions. The member shall still be
  7273. // defined in a namespace scope if it is used in the program and the
  7274. // namespace scope definition shall not contain an initializer.
  7275. //
  7276. // We already performed a redefinition check above, but for static
  7277. // data members we also need to check whether there was an in-class
  7278. // declaration with an initializer.
  7279. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  7280. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  7281. << VDecl->getDeclName();
  7282. Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
  7283. return;
  7284. }
  7285. if (VDecl->hasLocalStorage())
  7286. getCurFunction()->setHasBranchProtectedScope();
  7287. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  7288. VDecl->setInvalidDecl();
  7289. return;
  7290. }
  7291. }
  7292. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  7293. // a kernel function cannot be initialized."
  7294. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  7295. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  7296. VDecl->setInvalidDecl();
  7297. return;
  7298. }
  7299. // Get the decls type and save a reference for later, since
  7300. // CheckInitializerTypes may change it.
  7301. QualType DclT = VDecl->getType(), SavT = DclT;
  7302. // Expressions default to 'id' when we're in a debugger
  7303. // and we are assigning it to a variable of Objective-C pointer type.
  7304. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  7305. Init->getType() == Context.UnknownAnyTy) {
  7306. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  7307. if (Result.isInvalid()) {
  7308. VDecl->setInvalidDecl();
  7309. return;
  7310. }
  7311. Init = Result.take();
  7312. }
  7313. // Perform the initialization.
  7314. if (!VDecl->isInvalidDecl()) {
  7315. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  7316. InitializationKind Kind
  7317. = DirectInit ?
  7318. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  7319. Init->getLocStart(),
  7320. Init->getLocEnd())
  7321. : InitializationKind::CreateDirectList(
  7322. VDecl->getLocation())
  7323. : InitializationKind::CreateCopy(VDecl->getLocation(),
  7324. Init->getLocStart());
  7325. MultiExprArg Args = Init;
  7326. if (CXXDirectInit)
  7327. Args = MultiExprArg(CXXDirectInit->getExprs(),
  7328. CXXDirectInit->getNumExprs());
  7329. InitializationSequence InitSeq(*this, Entity, Kind, Args);
  7330. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  7331. if (Result.isInvalid()) {
  7332. VDecl->setInvalidDecl();
  7333. return;
  7334. }
  7335. Init = Result.takeAs<Expr>();
  7336. }
  7337. // Check for self-references within variable initializers.
  7338. // Variables declared within a function/method body (except for references)
  7339. // are handled by a dataflow analysis.
  7340. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  7341. VDecl->getType()->isReferenceType()) {
  7342. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  7343. }
  7344. // If the type changed, it means we had an incomplete type that was
  7345. // completed by the initializer. For example:
  7346. // int ary[] = { 1, 3, 5 };
  7347. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  7348. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  7349. VDecl->setType(DclT);
  7350. if (!VDecl->isInvalidDecl()) {
  7351. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  7352. if (VDecl->hasAttr<BlocksAttr>())
  7353. checkRetainCycles(VDecl, Init);
  7354. // It is safe to assign a weak reference into a strong variable.
  7355. // Although this code can still have problems:
  7356. // id x = self.weakProp;
  7357. // id y = self.weakProp;
  7358. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  7359. // paths through the function. This should be revisited if
  7360. // -Wrepeated-use-of-weak is made flow-sensitive.
  7361. if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
  7362. DiagnosticsEngine::Level Level =
  7363. Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
  7364. Init->getLocStart());
  7365. if (Level != DiagnosticsEngine::Ignored)
  7366. getCurFunction()->markSafeWeakUse(Init);
  7367. }
  7368. }
  7369. // The initialization is usually a full-expression.
  7370. //
  7371. // FIXME: If this is a braced initialization of an aggregate, it is not
  7372. // an expression, and each individual field initializer is a separate
  7373. // full-expression. For instance, in:
  7374. //
  7375. // struct Temp { ~Temp(); };
  7376. // struct S { S(Temp); };
  7377. // struct T { S a, b; } t = { Temp(), Temp() }
  7378. //
  7379. // we should destroy the first Temp before constructing the second.
  7380. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  7381. false,
  7382. VDecl->isConstexpr());
  7383. if (Result.isInvalid()) {
  7384. VDecl->setInvalidDecl();
  7385. return;
  7386. }
  7387. Init = Result.take();
  7388. // Attach the initializer to the decl.
  7389. VDecl->setInit(Init);
  7390. if (VDecl->isLocalVarDecl()) {
  7391. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  7392. // static storage duration shall be constant expressions or string literals.
  7393. // C++ does not have this restriction.
  7394. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
  7395. const Expr *Culprit;
  7396. if (VDecl->getStorageClass() == SC_Static)
  7397. CheckForConstantInitializer(Init, DclT);
  7398. // C89 is stricter than C99 for non-static aggregate types.
  7399. // C89 6.5.7p3: All the expressions [...] in an initializer list
  7400. // for an object that has aggregate or union type shall be
  7401. // constant expressions.
  7402. else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  7403. isa<InitListExpr>(Init) &&
  7404. !Init->isConstantInitializer(Context, false, &Culprit))
  7405. Diag(Culprit->getExprLoc(),
  7406. diag::ext_aggregate_init_not_constant)
  7407. << Culprit->getSourceRange();
  7408. }
  7409. } else if (VDecl->isStaticDataMember() &&
  7410. VDecl->getLexicalDeclContext()->isRecord()) {
  7411. // This is an in-class initialization for a static data member, e.g.,
  7412. //
  7413. // struct S {
  7414. // static const int value = 17;
  7415. // };
  7416. // C++ [class.mem]p4:
  7417. // A member-declarator can contain a constant-initializer only
  7418. // if it declares a static member (9.4) of const integral or
  7419. // const enumeration type, see 9.4.2.
  7420. //
  7421. // C++11 [class.static.data]p3:
  7422. // If a non-volatile const static data member is of integral or
  7423. // enumeration type, its declaration in the class definition can
  7424. // specify a brace-or-equal-initializer in which every initalizer-clause
  7425. // that is an assignment-expression is a constant expression. A static
  7426. // data member of literal type can be declared in the class definition
  7427. // with the constexpr specifier; if so, its declaration shall specify a
  7428. // brace-or-equal-initializer in which every initializer-clause that is
  7429. // an assignment-expression is a constant expression.
  7430. // Do nothing on dependent types.
  7431. if (DclT->isDependentType()) {
  7432. // Allow any 'static constexpr' members, whether or not they are of literal
  7433. // type. We separately check that every constexpr variable is of literal
  7434. // type.
  7435. } else if (VDecl->isConstexpr()) {
  7436. // Require constness.
  7437. } else if (!DclT.isConstQualified()) {
  7438. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  7439. << Init->getSourceRange();
  7440. VDecl->setInvalidDecl();
  7441. // We allow integer constant expressions in all cases.
  7442. } else if (DclT->isIntegralOrEnumerationType()) {
  7443. // Check whether the expression is a constant expression.
  7444. SourceLocation Loc;
  7445. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  7446. // In C++11, a non-constexpr const static data member with an
  7447. // in-class initializer cannot be volatile.
  7448. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  7449. else if (Init->isValueDependent())
  7450. ; // Nothing to check.
  7451. else if (Init->isIntegerConstantExpr(Context, &Loc))
  7452. ; // Ok, it's an ICE!
  7453. else if (Init->isEvaluatable(Context)) {
  7454. // If we can constant fold the initializer through heroics, accept it,
  7455. // but report this as a use of an extension for -pedantic.
  7456. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  7457. << Init->getSourceRange();
  7458. } else {
  7459. // Otherwise, this is some crazy unknown case. Report the issue at the
  7460. // location provided by the isIntegerConstantExpr failed check.
  7461. Diag(Loc, diag::err_in_class_initializer_non_constant)
  7462. << Init->getSourceRange();
  7463. VDecl->setInvalidDecl();
  7464. }
  7465. // We allow foldable floating-point constants as an extension.
  7466. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  7467. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  7468. // it anyway and provide a fixit to add the 'constexpr'.
  7469. if (getLangOpts().CPlusPlus11) {
  7470. Diag(VDecl->getLocation(),
  7471. diag::ext_in_class_initializer_float_type_cxx11)
  7472. << DclT << Init->getSourceRange();
  7473. Diag(VDecl->getLocStart(),
  7474. diag::note_in_class_initializer_float_type_cxx11)
  7475. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  7476. } else {
  7477. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  7478. << DclT << Init->getSourceRange();
  7479. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  7480. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  7481. << Init->getSourceRange();
  7482. VDecl->setInvalidDecl();
  7483. }
  7484. }
  7485. // Suggest adding 'constexpr' in C++11 for literal types.
  7486. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  7487. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  7488. << DclT << Init->getSourceRange()
  7489. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  7490. VDecl->setConstexpr(true);
  7491. } else {
  7492. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  7493. << DclT << Init->getSourceRange();
  7494. VDecl->setInvalidDecl();
  7495. }
  7496. } else if (VDecl->isFileVarDecl()) {
  7497. if (VDecl->getStorageClass() == SC_Extern &&
  7498. (!getLangOpts().CPlusPlus ||
  7499. !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
  7500. VDecl->isExternC())) &&
  7501. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  7502. Diag(VDecl->getLocation(), diag::warn_extern_init);
  7503. // C99 6.7.8p4. All file scoped initializers need to be constant.
  7504. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  7505. CheckForConstantInitializer(Init, DclT);
  7506. }
  7507. // We will represent direct-initialization similarly to copy-initialization:
  7508. // int x(1); -as-> int x = 1;
  7509. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  7510. //
  7511. // Clients that want to distinguish between the two forms, can check for
  7512. // direct initializer using VarDecl::getInitStyle().
  7513. // A major benefit is that clients that don't particularly care about which
  7514. // exactly form was it (like the CodeGen) can handle both cases without
  7515. // special case code.
  7516. // C++ 8.5p11:
  7517. // The form of initialization (using parentheses or '=') is generally
  7518. // insignificant, but does matter when the entity being initialized has a
  7519. // class type.
  7520. if (CXXDirectInit) {
  7521. assert(DirectInit && "Call-style initializer must be direct init.");
  7522. VDecl->setInitStyle(VarDecl::CallInit);
  7523. } else if (DirectInit) {
  7524. // This must be list-initialization. No other way is direct-initialization.
  7525. VDecl->setInitStyle(VarDecl::ListInit);
  7526. }
  7527. CheckCompleteVariableDeclaration(VDecl);
  7528. }
  7529. /// ActOnInitializerError - Given that there was an error parsing an
  7530. /// initializer for the given declaration, try to return to some form
  7531. /// of sanity.
  7532. void Sema::ActOnInitializerError(Decl *D) {
  7533. // Our main concern here is re-establishing invariants like "a
  7534. // variable's type is either dependent or complete".
  7535. if (!D || D->isInvalidDecl()) return;
  7536. VarDecl *VD = dyn_cast<VarDecl>(D);
  7537. if (!VD) return;
  7538. // Auto types are meaningless if we can't make sense of the initializer.
  7539. if (ParsingInitForAutoVars.count(D)) {
  7540. D->setInvalidDecl();
  7541. return;
  7542. }
  7543. QualType Ty = VD->getType();
  7544. if (Ty->isDependentType()) return;
  7545. // Require a complete type.
  7546. if (RequireCompleteType(VD->getLocation(),
  7547. Context.getBaseElementType(Ty),
  7548. diag::err_typecheck_decl_incomplete_type)) {
  7549. VD->setInvalidDecl();
  7550. return;
  7551. }
  7552. // Require a non-abstract type.
  7553. if (RequireNonAbstractType(VD->getLocation(), Ty,
  7554. diag::err_abstract_type_in_decl,
  7555. AbstractVariableType)) {
  7556. VD->setInvalidDecl();
  7557. return;
  7558. }
  7559. // Don't bother complaining about constructors or destructors,
  7560. // though.
  7561. }
  7562. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  7563. bool TypeMayContainAuto) {
  7564. // If there is no declaration, there was an error parsing it. Just ignore it.
  7565. if (RealDecl == 0)
  7566. return;
  7567. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  7568. QualType Type = Var->getType();
  7569. // C++11 [dcl.spec.auto]p3
  7570. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  7571. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  7572. << Var->getDeclName() << Type;
  7573. Var->setInvalidDecl();
  7574. return;
  7575. }
  7576. // C++11 [class.static.data]p3: A static data member can be declared with
  7577. // the constexpr specifier; if so, its declaration shall specify
  7578. // a brace-or-equal-initializer.
  7579. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  7580. // the definition of a variable [...] or the declaration of a static data
  7581. // member.
  7582. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  7583. if (Var->isStaticDataMember())
  7584. Diag(Var->getLocation(),
  7585. diag::err_constexpr_static_mem_var_requires_init)
  7586. << Var->getDeclName();
  7587. else
  7588. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  7589. Var->setInvalidDecl();
  7590. return;
  7591. }
  7592. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  7593. // be initialized.
  7594. if (!Var->isInvalidDecl() &&
  7595. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  7596. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  7597. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  7598. Var->setInvalidDecl();
  7599. return;
  7600. }
  7601. switch (Var->isThisDeclarationADefinition()) {
  7602. case VarDecl::Definition:
  7603. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  7604. break;
  7605. // We have an out-of-line definition of a static data member
  7606. // that has an in-class initializer, so we type-check this like
  7607. // a declaration.
  7608. //
  7609. // Fall through
  7610. case VarDecl::DeclarationOnly:
  7611. // It's only a declaration.
  7612. // Block scope. C99 6.7p7: If an identifier for an object is
  7613. // declared with no linkage (C99 6.2.2p6), the type for the
  7614. // object shall be complete.
  7615. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  7616. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  7617. RequireCompleteType(Var->getLocation(), Type,
  7618. diag::err_typecheck_decl_incomplete_type))
  7619. Var->setInvalidDecl();
  7620. // Make sure that the type is not abstract.
  7621. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  7622. RequireNonAbstractType(Var->getLocation(), Type,
  7623. diag::err_abstract_type_in_decl,
  7624. AbstractVariableType))
  7625. Var->setInvalidDecl();
  7626. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  7627. Var->getStorageClass() == SC_PrivateExtern) {
  7628. Diag(Var->getLocation(), diag::warn_private_extern);
  7629. Diag(Var->getLocation(), diag::note_private_extern);
  7630. }
  7631. return;
  7632. case VarDecl::TentativeDefinition:
  7633. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  7634. // object that has file scope without an initializer, and without a
  7635. // storage-class specifier or with the storage-class specifier "static",
  7636. // constitutes a tentative definition. Note: A tentative definition with
  7637. // external linkage is valid (C99 6.2.2p5).
  7638. if (!Var->isInvalidDecl()) {
  7639. if (const IncompleteArrayType *ArrayT
  7640. = Context.getAsIncompleteArrayType(Type)) {
  7641. if (RequireCompleteType(Var->getLocation(),
  7642. ArrayT->getElementType(),
  7643. diag::err_illegal_decl_array_incomplete_type))
  7644. Var->setInvalidDecl();
  7645. } else if (Var->getStorageClass() == SC_Static) {
  7646. // C99 6.9.2p3: If the declaration of an identifier for an object is
  7647. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  7648. // declared type shall not be an incomplete type.
  7649. // NOTE: code such as the following
  7650. // static struct s;
  7651. // struct s { int a; };
  7652. // is accepted by gcc. Hence here we issue a warning instead of
  7653. // an error and we do not invalidate the static declaration.
  7654. // NOTE: to avoid multiple warnings, only check the first declaration.
  7655. if (Var->isFirstDecl())
  7656. RequireCompleteType(Var->getLocation(), Type,
  7657. diag::ext_typecheck_decl_incomplete_type);
  7658. }
  7659. }
  7660. // Record the tentative definition; we're done.
  7661. if (!Var->isInvalidDecl())
  7662. TentativeDefinitions.push_back(Var);
  7663. return;
  7664. }
  7665. // Provide a specific diagnostic for uninitialized variable
  7666. // definitions with incomplete array type.
  7667. if (Type->isIncompleteArrayType()) {
  7668. Diag(Var->getLocation(),
  7669. diag::err_typecheck_incomplete_array_needs_initializer);
  7670. Var->setInvalidDecl();
  7671. return;
  7672. }
  7673. // Provide a specific diagnostic for uninitialized variable
  7674. // definitions with reference type.
  7675. if (Type->isReferenceType()) {
  7676. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  7677. << Var->getDeclName()
  7678. << SourceRange(Var->getLocation(), Var->getLocation());
  7679. Var->setInvalidDecl();
  7680. return;
  7681. }
  7682. // Do not attempt to type-check the default initializer for a
  7683. // variable with dependent type.
  7684. if (Type->isDependentType())
  7685. return;
  7686. if (Var->isInvalidDecl())
  7687. return;
  7688. if (RequireCompleteType(Var->getLocation(),
  7689. Context.getBaseElementType(Type),
  7690. diag::err_typecheck_decl_incomplete_type)) {
  7691. Var->setInvalidDecl();
  7692. return;
  7693. }
  7694. // The variable can not have an abstract class type.
  7695. if (RequireNonAbstractType(Var->getLocation(), Type,
  7696. diag::err_abstract_type_in_decl,
  7697. AbstractVariableType)) {
  7698. Var->setInvalidDecl();
  7699. return;
  7700. }
  7701. // Check for jumps past the implicit initializer. C++0x
  7702. // clarifies that this applies to a "variable with automatic
  7703. // storage duration", not a "local variable".
  7704. // C++11 [stmt.dcl]p3
  7705. // A program that jumps from a point where a variable with automatic
  7706. // storage duration is not in scope to a point where it is in scope is
  7707. // ill-formed unless the variable has scalar type, class type with a
  7708. // trivial default constructor and a trivial destructor, a cv-qualified
  7709. // version of one of these types, or an array of one of the preceding
  7710. // types and is declared without an initializer.
  7711. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  7712. if (const RecordType *Record
  7713. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  7714. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  7715. // Mark the function for further checking even if the looser rules of
  7716. // C++11 do not require such checks, so that we can diagnose
  7717. // incompatibilities with C++98.
  7718. if (!CXXRecord->isPOD())
  7719. getCurFunction()->setHasBranchProtectedScope();
  7720. }
  7721. }
  7722. // C++03 [dcl.init]p9:
  7723. // If no initializer is specified for an object, and the
  7724. // object is of (possibly cv-qualified) non-POD class type (or
  7725. // array thereof), the object shall be default-initialized; if
  7726. // the object is of const-qualified type, the underlying class
  7727. // type shall have a user-declared default
  7728. // constructor. Otherwise, if no initializer is specified for
  7729. // a non- static object, the object and its subobjects, if
  7730. // any, have an indeterminate initial value); if the object
  7731. // or any of its subobjects are of const-qualified type, the
  7732. // program is ill-formed.
  7733. // C++0x [dcl.init]p11:
  7734. // If no initializer is specified for an object, the object is
  7735. // default-initialized; [...].
  7736. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  7737. InitializationKind Kind
  7738. = InitializationKind::CreateDefault(Var->getLocation());
  7739. InitializationSequence InitSeq(*this, Entity, Kind, None);
  7740. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  7741. if (Init.isInvalid())
  7742. Var->setInvalidDecl();
  7743. else if (Init.get()) {
  7744. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  7745. // This is important for template substitution.
  7746. Var->setInitStyle(VarDecl::CallInit);
  7747. }
  7748. CheckCompleteVariableDeclaration(Var);
  7749. }
  7750. }
  7751. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  7752. VarDecl *VD = dyn_cast<VarDecl>(D);
  7753. if (!VD) {
  7754. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  7755. D->setInvalidDecl();
  7756. return;
  7757. }
  7758. VD->setCXXForRangeDecl(true);
  7759. // for-range-declaration cannot be given a storage class specifier.
  7760. int Error = -1;
  7761. switch (VD->getStorageClass()) {
  7762. case SC_None:
  7763. break;
  7764. case SC_Extern:
  7765. Error = 0;
  7766. break;
  7767. case SC_Static:
  7768. Error = 1;
  7769. break;
  7770. case SC_PrivateExtern:
  7771. Error = 2;
  7772. break;
  7773. case SC_Auto:
  7774. Error = 3;
  7775. break;
  7776. case SC_Register:
  7777. Error = 4;
  7778. break;
  7779. case SC_OpenCLWorkGroupLocal:
  7780. llvm_unreachable("Unexpected storage class");
  7781. }
  7782. if (VD->isConstexpr())
  7783. Error = 5;
  7784. if (Error != -1) {
  7785. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  7786. << VD->getDeclName() << Error;
  7787. D->setInvalidDecl();
  7788. }
  7789. }
  7790. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  7791. if (var->isInvalidDecl()) return;
  7792. // In ARC, don't allow jumps past the implicit initialization of a
  7793. // local retaining variable.
  7794. if (getLangOpts().ObjCAutoRefCount &&
  7795. var->hasLocalStorage()) {
  7796. switch (var->getType().getObjCLifetime()) {
  7797. case Qualifiers::OCL_None:
  7798. case Qualifiers::OCL_ExplicitNone:
  7799. case Qualifiers::OCL_Autoreleasing:
  7800. break;
  7801. case Qualifiers::OCL_Weak:
  7802. case Qualifiers::OCL_Strong:
  7803. getCurFunction()->setHasBranchProtectedScope();
  7804. break;
  7805. }
  7806. }
  7807. // Warn about externally-visible variables being defined without a
  7808. // prior declaration. We only want to do this for global
  7809. // declarations, but we also specifically need to avoid doing it for
  7810. // class members because the linkage of an anonymous class can
  7811. // change if it's later given a typedef name.
  7812. if (var->isThisDeclarationADefinition() &&
  7813. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  7814. var->isExternallyVisible() && var->hasLinkage() &&
  7815. getDiagnostics().getDiagnosticLevel(
  7816. diag::warn_missing_variable_declarations,
  7817. var->getLocation())) {
  7818. // Find a previous declaration that's not a definition.
  7819. VarDecl *prev = var->getPreviousDecl();
  7820. while (prev && prev->isThisDeclarationADefinition())
  7821. prev = prev->getPreviousDecl();
  7822. if (!prev)
  7823. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  7824. }
  7825. if (var->getTLSKind() == VarDecl::TLS_Static) {
  7826. const Expr *Culprit;
  7827. if (var->getType().isDestructedType()) {
  7828. // GNU C++98 edits for __thread, [basic.start.term]p3:
  7829. // The type of an object with thread storage duration shall not
  7830. // have a non-trivial destructor.
  7831. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  7832. if (getLangOpts().CPlusPlus11)
  7833. Diag(var->getLocation(), diag::note_use_thread_local);
  7834. } else if (getLangOpts().CPlusPlus && var->hasInit() &&
  7835. !var->getInit()->isConstantInitializer(
  7836. Context, var->getType()->isReferenceType(), &Culprit)) {
  7837. // GNU C++98 edits for __thread, [basic.start.init]p4:
  7838. // An object of thread storage duration shall not require dynamic
  7839. // initialization.
  7840. // FIXME: Need strict checking here.
  7841. Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
  7842. << Culprit->getSourceRange();
  7843. if (getLangOpts().CPlusPlus11)
  7844. Diag(var->getLocation(), diag::note_use_thread_local);
  7845. }
  7846. }
  7847. if (var->isThisDeclarationADefinition() &&
  7848. ActiveTemplateInstantiations.empty()) {
  7849. PragmaStack<StringLiteral *> *Stack = nullptr;
  7850. int SectionFlags = PSF_Implicit | PSF_Read;
  7851. if (var->getType().isConstQualified())
  7852. Stack = &ConstSegStack;
  7853. else if (!var->getInit()) {
  7854. Stack = &BSSSegStack;
  7855. SectionFlags |= PSF_Write;
  7856. } else {
  7857. Stack = &DataSegStack;
  7858. SectionFlags |= PSF_Write;
  7859. }
  7860. if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue)
  7861. var->addAttr(
  7862. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7863. Stack->CurrentValue->getString(),
  7864. Stack->CurrentPragmaLocation));
  7865. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  7866. if (UnifySection(SA->getName(), SectionFlags, var))
  7867. var->dropAttr<SectionAttr>();
  7868. }
  7869. // All the following checks are C++ only.
  7870. if (!getLangOpts().CPlusPlus) return;
  7871. QualType type = var->getType();
  7872. if (type->isDependentType()) return;
  7873. // __block variables might require us to capture a copy-initializer.
  7874. if (var->hasAttr<BlocksAttr>()) {
  7875. // It's currently invalid to ever have a __block variable with an
  7876. // array type; should we diagnose that here?
  7877. // Regardless, we don't want to ignore array nesting when
  7878. // constructing this copy.
  7879. if (type->isStructureOrClassType()) {
  7880. EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
  7881. SourceLocation poi = var->getLocation();
  7882. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  7883. ExprResult result
  7884. = PerformMoveOrCopyInitialization(
  7885. InitializedEntity::InitializeBlock(poi, type, false),
  7886. var, var->getType(), varRef, /*AllowNRVO=*/true);
  7887. if (!result.isInvalid()) {
  7888. result = MaybeCreateExprWithCleanups(result);
  7889. Expr *init = result.takeAs<Expr>();
  7890. Context.setBlockVarCopyInits(var, init);
  7891. }
  7892. }
  7893. }
  7894. Expr *Init = var->getInit();
  7895. bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
  7896. QualType baseType = Context.getBaseElementType(type);
  7897. if (!var->getDeclContext()->isDependentContext() &&
  7898. Init && !Init->isValueDependent()) {
  7899. if (IsGlobal && !var->isConstexpr() &&
  7900. getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
  7901. var->getLocation())
  7902. != DiagnosticsEngine::Ignored) {
  7903. // Warn about globals which don't have a constant initializer. Don't
  7904. // warn about globals with a non-trivial destructor because we already
  7905. // warned about them.
  7906. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  7907. if (!(RD && !RD->hasTrivialDestructor()) &&
  7908. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  7909. Diag(var->getLocation(), diag::warn_global_constructor)
  7910. << Init->getSourceRange();
  7911. }
  7912. if (var->isConstexpr()) {
  7913. SmallVector<PartialDiagnosticAt, 8> Notes;
  7914. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  7915. SourceLocation DiagLoc = var->getLocation();
  7916. // If the note doesn't add any useful information other than a source
  7917. // location, fold it into the primary diagnostic.
  7918. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  7919. diag::note_invalid_subexpr_in_const_expr) {
  7920. DiagLoc = Notes[0].first;
  7921. Notes.clear();
  7922. }
  7923. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  7924. << var << Init->getSourceRange();
  7925. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  7926. Diag(Notes[I].first, Notes[I].second);
  7927. }
  7928. } else if (var->isUsableInConstantExpressions(Context)) {
  7929. // Check whether the initializer of a const variable of integral or
  7930. // enumeration type is an ICE now, since we can't tell whether it was
  7931. // initialized by a constant expression if we check later.
  7932. var->checkInitIsICE();
  7933. }
  7934. }
  7935. // Require the destructor.
  7936. if (const RecordType *recordType = baseType->getAs<RecordType>())
  7937. FinalizeVarWithDestructor(var, recordType);
  7938. }
  7939. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  7940. /// any semantic actions necessary after any initializer has been attached.
  7941. void
  7942. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  7943. // Note that we are no longer parsing the initializer for this declaration.
  7944. ParsingInitForAutoVars.erase(ThisDecl);
  7945. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  7946. if (!VD)
  7947. return;
  7948. checkAttributesAfterMerging(*this, *VD);
  7949. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  7950. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  7951. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  7952. VD->dropAttr<UsedAttr>();
  7953. }
  7954. }
  7955. if (!VD->isInvalidDecl() &&
  7956. VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
  7957. if (const VarDecl *Def = VD->getDefinition()) {
  7958. if (Def->hasAttr<AliasAttr>()) {
  7959. Diag(VD->getLocation(), diag::err_tentative_after_alias)
  7960. << VD->getDeclName();
  7961. Diag(Def->getLocation(), diag::note_previous_definition);
  7962. VD->setInvalidDecl();
  7963. }
  7964. }
  7965. }
  7966. const DeclContext *DC = VD->getDeclContext();
  7967. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7968. // member, set the visibility of this variable.
  7969. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  7970. AddPushedVisibilityAttribute(VD);
  7971. // FIXME: Warn on unused templates.
  7972. if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
  7973. !isa<VarTemplatePartialSpecializationDecl>(VD))
  7974. MarkUnusedFileScopedDecl(VD);
  7975. // Now we have parsed the initializer and can update the table of magic
  7976. // tag values.
  7977. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  7978. !VD->getType()->isIntegralOrEnumerationType())
  7979. return;
  7980. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  7981. const Expr *MagicValueExpr = VD->getInit();
  7982. if (!MagicValueExpr) {
  7983. continue;
  7984. }
  7985. llvm::APSInt MagicValueInt;
  7986. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  7987. Diag(I->getRange().getBegin(),
  7988. diag::err_type_tag_for_datatype_not_ice)
  7989. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  7990. continue;
  7991. }
  7992. if (MagicValueInt.getActiveBits() > 64) {
  7993. Diag(I->getRange().getBegin(),
  7994. diag::err_type_tag_for_datatype_too_large)
  7995. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  7996. continue;
  7997. }
  7998. uint64_t MagicValue = MagicValueInt.getZExtValue();
  7999. RegisterTypeTagForDatatype(I->getArgumentKind(),
  8000. MagicValue,
  8001. I->getMatchingCType(),
  8002. I->getLayoutCompatible(),
  8003. I->getMustBeNull());
  8004. }
  8005. }
  8006. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  8007. ArrayRef<Decl *> Group) {
  8008. SmallVector<Decl*, 8> Decls;
  8009. if (DS.isTypeSpecOwned())
  8010. Decls.push_back(DS.getRepAsDecl());
  8011. DeclaratorDecl *FirstDeclaratorInGroup = 0;
  8012. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8013. if (Decl *D = Group[i]) {
  8014. if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
  8015. if (!FirstDeclaratorInGroup)
  8016. FirstDeclaratorInGroup = DD;
  8017. Decls.push_back(D);
  8018. }
  8019. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  8020. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  8021. HandleTagNumbering(*this, Tag, S);
  8022. if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
  8023. Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
  8024. }
  8025. }
  8026. return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
  8027. }
  8028. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  8029. /// group, performing any necessary semantic checking.
  8030. Sema::DeclGroupPtrTy
  8031. Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
  8032. bool TypeMayContainAuto) {
  8033. // C++0x [dcl.spec.auto]p7:
  8034. // If the type deduced for the template parameter U is not the same in each
  8035. // deduction, the program is ill-formed.
  8036. // FIXME: When initializer-list support is added, a distinction is needed
  8037. // between the deduced type U and the deduced type which 'auto' stands for.
  8038. // auto a = 0, b = { 1, 2, 3 };
  8039. // is legal because the deduced type U is 'int' in both cases.
  8040. if (TypeMayContainAuto && Group.size() > 1) {
  8041. QualType Deduced;
  8042. CanQualType DeducedCanon;
  8043. VarDecl *DeducedDecl = 0;
  8044. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  8045. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  8046. AutoType *AT = D->getType()->getContainedAutoType();
  8047. // Don't reissue diagnostics when instantiating a template.
  8048. if (AT && D->isInvalidDecl())
  8049. break;
  8050. QualType U = AT ? AT->getDeducedType() : QualType();
  8051. if (!U.isNull()) {
  8052. CanQualType UCanon = Context.getCanonicalType(U);
  8053. if (Deduced.isNull()) {
  8054. Deduced = U;
  8055. DeducedCanon = UCanon;
  8056. DeducedDecl = D;
  8057. } else if (DeducedCanon != UCanon) {
  8058. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  8059. diag::err_auto_different_deductions)
  8060. << (AT->isDecltypeAuto() ? 1 : 0)
  8061. << Deduced << DeducedDecl->getDeclName()
  8062. << U << D->getDeclName()
  8063. << DeducedDecl->getInit()->getSourceRange()
  8064. << D->getInit()->getSourceRange();
  8065. D->setInvalidDecl();
  8066. break;
  8067. }
  8068. }
  8069. }
  8070. }
  8071. }
  8072. ActOnDocumentableDecls(Group);
  8073. return DeclGroupPtrTy::make(
  8074. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  8075. }
  8076. void Sema::ActOnDocumentableDecl(Decl *D) {
  8077. ActOnDocumentableDecls(D);
  8078. }
  8079. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  8080. // Don't parse the comment if Doxygen diagnostics are ignored.
  8081. if (Group.empty() || !Group[0])
  8082. return;
  8083. if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
  8084. Group[0]->getLocation())
  8085. == DiagnosticsEngine::Ignored)
  8086. return;
  8087. if (Group.size() >= 2) {
  8088. // This is a decl group. Normally it will contain only declarations
  8089. // produced from declarator list. But in case we have any definitions or
  8090. // additional declaration references:
  8091. // 'typedef struct S {} S;'
  8092. // 'typedef struct S *S;'
  8093. // 'struct S *pS;'
  8094. // FinalizeDeclaratorGroup adds these as separate declarations.
  8095. Decl *MaybeTagDecl = Group[0];
  8096. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  8097. Group = Group.slice(1);
  8098. }
  8099. }
  8100. // See if there are any new comments that are not attached to a decl.
  8101. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  8102. if (!Comments.empty() &&
  8103. !Comments.back()->isAttached()) {
  8104. // There is at least one comment that not attached to a decl.
  8105. // Maybe it should be attached to one of these decls?
  8106. //
  8107. // Note that this way we pick up not only comments that precede the
  8108. // declaration, but also comments that *follow* the declaration -- thanks to
  8109. // the lookahead in the lexer: we've consumed the semicolon and looked
  8110. // ahead through comments.
  8111. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  8112. Context.getCommentForDecl(Group[i], &PP);
  8113. }
  8114. }
  8115. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  8116. /// to introduce parameters into function prototype scope.
  8117. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  8118. const DeclSpec &DS = D.getDeclSpec();
  8119. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  8120. // C++03 [dcl.stc]p2 also permits 'auto'.
  8121. VarDecl::StorageClass StorageClass = SC_None;
  8122. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  8123. StorageClass = SC_Register;
  8124. } else if (getLangOpts().CPlusPlus &&
  8125. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  8126. StorageClass = SC_Auto;
  8127. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  8128. Diag(DS.getStorageClassSpecLoc(),
  8129. diag::err_invalid_storage_class_in_func_decl);
  8130. D.getMutableDeclSpec().ClearStorageClassSpecs();
  8131. }
  8132. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  8133. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  8134. << DeclSpec::getSpecifierName(TSCS);
  8135. if (DS.isConstexprSpecified())
  8136. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  8137. << 0;
  8138. DiagnoseFunctionSpecifiers(DS);
  8139. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8140. QualType parmDeclType = TInfo->getType();
  8141. if (getLangOpts().CPlusPlus) {
  8142. // Check that there are no default arguments inside the type of this
  8143. // parameter.
  8144. CheckExtraCXXDefaultArguments(D);
  8145. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  8146. if (D.getCXXScopeSpec().isSet()) {
  8147. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  8148. << D.getCXXScopeSpec().getRange();
  8149. D.getCXXScopeSpec().clear();
  8150. }
  8151. }
  8152. // Ensure we have a valid name
  8153. IdentifierInfo *II = 0;
  8154. if (D.hasName()) {
  8155. II = D.getIdentifier();
  8156. if (!II) {
  8157. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  8158. << GetNameForDeclarator(D).getName();
  8159. D.setInvalidType(true);
  8160. }
  8161. }
  8162. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  8163. if (II) {
  8164. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  8165. ForRedeclaration);
  8166. LookupName(R, S);
  8167. if (R.isSingleResult()) {
  8168. NamedDecl *PrevDecl = R.getFoundDecl();
  8169. if (PrevDecl->isTemplateParameter()) {
  8170. // Maybe we will complain about the shadowed template parameter.
  8171. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  8172. // Just pretend that we didn't see the previous declaration.
  8173. PrevDecl = 0;
  8174. } else if (S->isDeclScope(PrevDecl)) {
  8175. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  8176. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8177. // Recover by removing the name
  8178. II = 0;
  8179. D.SetIdentifier(0, D.getIdentifierLoc());
  8180. D.setInvalidType(true);
  8181. }
  8182. }
  8183. }
  8184. // Temporarily put parameter variables in the translation unit, not
  8185. // the enclosing context. This prevents them from accidentally
  8186. // looking like class members in C++.
  8187. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  8188. D.getLocStart(),
  8189. D.getIdentifierLoc(), II,
  8190. parmDeclType, TInfo,
  8191. StorageClass);
  8192. if (D.isInvalidType())
  8193. New->setInvalidDecl();
  8194. assert(S->isFunctionPrototypeScope());
  8195. assert(S->getFunctionPrototypeDepth() >= 1);
  8196. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  8197. S->getNextFunctionPrototypeIndex());
  8198. // Add the parameter declaration into this scope.
  8199. S->AddDecl(New);
  8200. if (II)
  8201. IdResolver.AddDecl(New);
  8202. ProcessDeclAttributes(S, New, D);
  8203. if (D.getDeclSpec().isModulePrivateSpecified())
  8204. Diag(New->getLocation(), diag::err_module_private_local)
  8205. << 1 << New->getDeclName()
  8206. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  8207. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  8208. if (New->hasAttr<BlocksAttr>()) {
  8209. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  8210. }
  8211. return New;
  8212. }
  8213. /// \brief Synthesizes a variable for a parameter arising from a
  8214. /// typedef.
  8215. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  8216. SourceLocation Loc,
  8217. QualType T) {
  8218. /* FIXME: setting StartLoc == Loc.
  8219. Would it be worth to modify callers so as to provide proper source
  8220. location for the unnamed parameters, embedding the parameter's type? */
  8221. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
  8222. T, Context.getTrivialTypeSourceInfo(T, Loc),
  8223. SC_None, 0);
  8224. Param->setImplicit();
  8225. return Param;
  8226. }
  8227. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  8228. ParmVarDecl * const *ParamEnd) {
  8229. // Don't diagnose unused-parameter errors in template instantiations; we
  8230. // will already have done so in the template itself.
  8231. if (!ActiveTemplateInstantiations.empty())
  8232. return;
  8233. for (; Param != ParamEnd; ++Param) {
  8234. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  8235. !(*Param)->hasAttr<UnusedAttr>()) {
  8236. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  8237. << (*Param)->getDeclName();
  8238. }
  8239. }
  8240. }
  8241. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  8242. ParmVarDecl * const *ParamEnd,
  8243. QualType ReturnTy,
  8244. NamedDecl *D) {
  8245. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  8246. return;
  8247. // Warn if the return value is pass-by-value and larger than the specified
  8248. // threshold.
  8249. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  8250. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  8251. if (Size > LangOpts.NumLargeByValueCopy)
  8252. Diag(D->getLocation(), diag::warn_return_value_size)
  8253. << D->getDeclName() << Size;
  8254. }
  8255. // Warn if any parameter is pass-by-value and larger than the specified
  8256. // threshold.
  8257. for (; Param != ParamEnd; ++Param) {
  8258. QualType T = (*Param)->getType();
  8259. if (T->isDependentType() || !T.isPODType(Context))
  8260. continue;
  8261. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  8262. if (Size > LangOpts.NumLargeByValueCopy)
  8263. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  8264. << (*Param)->getDeclName() << Size;
  8265. }
  8266. }
  8267. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  8268. SourceLocation NameLoc, IdentifierInfo *Name,
  8269. QualType T, TypeSourceInfo *TSInfo,
  8270. VarDecl::StorageClass StorageClass) {
  8271. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  8272. if (getLangOpts().ObjCAutoRefCount &&
  8273. T.getObjCLifetime() == Qualifiers::OCL_None &&
  8274. T->isObjCLifetimeType()) {
  8275. Qualifiers::ObjCLifetime lifetime;
  8276. // Special cases for arrays:
  8277. // - if it's const, use __unsafe_unretained
  8278. // - otherwise, it's an error
  8279. if (T->isArrayType()) {
  8280. if (!T.isConstQualified()) {
  8281. DelayedDiagnostics.add(
  8282. sema::DelayedDiagnostic::makeForbiddenType(
  8283. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  8284. }
  8285. lifetime = Qualifiers::OCL_ExplicitNone;
  8286. } else {
  8287. lifetime = T->getObjCARCImplicitLifetime();
  8288. }
  8289. T = Context.getLifetimeQualifiedType(T, lifetime);
  8290. }
  8291. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  8292. Context.getAdjustedParameterType(T),
  8293. TSInfo,
  8294. StorageClass, 0);
  8295. // Parameters can not be abstract class types.
  8296. // For record types, this is done by the AbstractClassUsageDiagnoser once
  8297. // the class has been completely parsed.
  8298. if (!CurContext->isRecord() &&
  8299. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  8300. AbstractParamType))
  8301. New->setInvalidDecl();
  8302. // Parameter declarators cannot be interface types. All ObjC objects are
  8303. // passed by reference.
  8304. if (T->isObjCObjectType()) {
  8305. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  8306. Diag(NameLoc,
  8307. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  8308. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  8309. T = Context.getObjCObjectPointerType(T);
  8310. New->setType(T);
  8311. }
  8312. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  8313. // duration shall not be qualified by an address-space qualifier."
  8314. // Since all parameters have automatic store duration, they can not have
  8315. // an address space.
  8316. if (T.getAddressSpace() != 0) {
  8317. // OpenCL allows function arguments declared to be an array of a type
  8318. // to be qualified with an address space.
  8319. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  8320. Diag(NameLoc, diag::err_arg_with_address_space);
  8321. New->setInvalidDecl();
  8322. }
  8323. }
  8324. return New;
  8325. }
  8326. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  8327. SourceLocation LocAfterDecls) {
  8328. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  8329. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  8330. // for a K&R function.
  8331. if (!FTI.hasPrototype) {
  8332. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  8333. --i;
  8334. if (FTI.Params[i].Param == 0) {
  8335. SmallString<256> Code;
  8336. llvm::raw_svector_ostream(Code)
  8337. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  8338. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  8339. << FTI.Params[i].Ident
  8340. << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
  8341. // Implicitly declare the argument as type 'int' for lack of a better
  8342. // type.
  8343. AttributeFactory attrs;
  8344. DeclSpec DS(attrs);
  8345. const char* PrevSpec; // unused
  8346. unsigned DiagID; // unused
  8347. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  8348. DiagID, Context.getPrintingPolicy());
  8349. // Use the identifier location for the type source range.
  8350. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  8351. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  8352. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  8353. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  8354. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  8355. }
  8356. }
  8357. }
  8358. }
  8359. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  8360. assert(getCurFunctionDecl() == 0 && "Function parsing confused");
  8361. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  8362. Scope *ParentScope = FnBodyScope->getParent();
  8363. D.setFunctionDefinitionKind(FDK_Definition);
  8364. Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
  8365. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  8366. }
  8367. void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
  8368. Consumer.HandleInlineMethodDefinition(D);
  8369. }
  8370. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  8371. const FunctionDecl*& PossibleZeroParamPrototype) {
  8372. // Don't warn about invalid declarations.
  8373. if (FD->isInvalidDecl())
  8374. return false;
  8375. // Or declarations that aren't global.
  8376. if (!FD->isGlobal())
  8377. return false;
  8378. // Don't warn about C++ member functions.
  8379. if (isa<CXXMethodDecl>(FD))
  8380. return false;
  8381. // Don't warn about 'main'.
  8382. if (FD->isMain())
  8383. return false;
  8384. // Don't warn about inline functions.
  8385. if (FD->isInlined())
  8386. return false;
  8387. // Don't warn about function templates.
  8388. if (FD->getDescribedFunctionTemplate())
  8389. return false;
  8390. // Don't warn about function template specializations.
  8391. if (FD->isFunctionTemplateSpecialization())
  8392. return false;
  8393. // Don't warn for OpenCL kernels.
  8394. if (FD->hasAttr<OpenCLKernelAttr>())
  8395. return false;
  8396. bool MissingPrototype = true;
  8397. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  8398. Prev; Prev = Prev->getPreviousDecl()) {
  8399. // Ignore any declarations that occur in function or method
  8400. // scope, because they aren't visible from the header.
  8401. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  8402. continue;
  8403. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  8404. if (FD->getNumParams() == 0)
  8405. PossibleZeroParamPrototype = Prev;
  8406. break;
  8407. }
  8408. return MissingPrototype;
  8409. }
  8410. void
  8411. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  8412. const FunctionDecl *EffectiveDefinition) {
  8413. // Don't complain if we're in GNU89 mode and the previous definition
  8414. // was an extern inline function.
  8415. const FunctionDecl *Definition = EffectiveDefinition;
  8416. if (!Definition)
  8417. if (!FD->isDefined(Definition))
  8418. return;
  8419. if (canRedefineFunction(Definition, getLangOpts()))
  8420. return;
  8421. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  8422. Definition->getStorageClass() == SC_Extern)
  8423. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  8424. << FD->getDeclName() << getLangOpts().CPlusPlus;
  8425. else
  8426. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  8427. Diag(Definition->getLocation(), diag::note_previous_definition);
  8428. FD->setInvalidDecl();
  8429. }
  8430. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  8431. Sema &S) {
  8432. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  8433. LambdaScopeInfo *LSI = S.PushLambdaScope();
  8434. LSI->CallOperator = CallOperator;
  8435. LSI->Lambda = LambdaClass;
  8436. LSI->ReturnType = CallOperator->getReturnType();
  8437. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  8438. if (LCD == LCD_None)
  8439. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  8440. else if (LCD == LCD_ByCopy)
  8441. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  8442. else if (LCD == LCD_ByRef)
  8443. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  8444. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  8445. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  8446. LSI->Mutable = !CallOperator->isConst();
  8447. // Add the captures to the LSI so they can be noted as already
  8448. // captured within tryCaptureVar.
  8449. for (const auto &C : LambdaClass->captures()) {
  8450. if (C.capturesVariable()) {
  8451. VarDecl *VD = C.getCapturedVar();
  8452. if (VD->isInitCapture())
  8453. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  8454. QualType CaptureType = VD->getType();
  8455. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  8456. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  8457. /*RefersToEnclosingLocal*/true, C.getLocation(),
  8458. /*EllipsisLoc*/C.isPackExpansion()
  8459. ? C.getEllipsisLoc() : SourceLocation(),
  8460. CaptureType, /*Expr*/ 0);
  8461. } else if (C.capturesThis()) {
  8462. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  8463. S.getCurrentThisType(), /*Expr*/ 0);
  8464. }
  8465. }
  8466. }
  8467. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  8468. // Clear the last template instantiation error context.
  8469. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  8470. if (!D)
  8471. return D;
  8472. FunctionDecl *FD = 0;
  8473. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  8474. FD = FunTmpl->getTemplatedDecl();
  8475. else
  8476. FD = cast<FunctionDecl>(D);
  8477. // If we are instantiating a generic lambda call operator, push
  8478. // a LambdaScopeInfo onto the function stack. But use the information
  8479. // that's already been calculated (ActOnLambdaExpr) to prime the current
  8480. // LambdaScopeInfo.
  8481. // When the template operator is being specialized, the LambdaScopeInfo,
  8482. // has to be properly restored so that tryCaptureVariable doesn't try
  8483. // and capture any new variables. In addition when calculating potential
  8484. // captures during transformation of nested lambdas, it is necessary to
  8485. // have the LSI properly restored.
  8486. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  8487. assert(ActiveTemplateInstantiations.size() &&
  8488. "There should be an active template instantiation on the stack "
  8489. "when instantiating a generic lambda!");
  8490. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  8491. }
  8492. else
  8493. // Enter a new function scope
  8494. PushFunctionScope();
  8495. // See if this is a redefinition.
  8496. if (!FD->isLateTemplateParsed())
  8497. CheckForFunctionRedefinition(FD);
  8498. // Builtin functions cannot be defined.
  8499. if (unsigned BuiltinID = FD->getBuiltinID()) {
  8500. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  8501. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  8502. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  8503. FD->setInvalidDecl();
  8504. }
  8505. }
  8506. // The return type of a function definition must be complete
  8507. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  8508. QualType ResultType = FD->getReturnType();
  8509. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  8510. !FD->isInvalidDecl() &&
  8511. RequireCompleteType(FD->getLocation(), ResultType,
  8512. diag::err_func_def_incomplete_result))
  8513. FD->setInvalidDecl();
  8514. // GNU warning -Wmissing-prototypes:
  8515. // Warn if a global function is defined without a previous
  8516. // prototype declaration. This warning is issued even if the
  8517. // definition itself provides a prototype. The aim is to detect
  8518. // global functions that fail to be declared in header files.
  8519. const FunctionDecl *PossibleZeroParamPrototype = 0;
  8520. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  8521. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  8522. if (PossibleZeroParamPrototype) {
  8523. // We found a declaration that is not a prototype,
  8524. // but that could be a zero-parameter prototype
  8525. if (TypeSourceInfo *TI =
  8526. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  8527. TypeLoc TL = TI->getTypeLoc();
  8528. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  8529. Diag(PossibleZeroParamPrototype->getLocation(),
  8530. diag::note_declaration_not_a_prototype)
  8531. << PossibleZeroParamPrototype
  8532. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  8533. }
  8534. }
  8535. }
  8536. if (FnBodyScope)
  8537. PushDeclContext(FnBodyScope, FD);
  8538. // Check the validity of our function parameters
  8539. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  8540. /*CheckParameterNames=*/true);
  8541. // Introduce our parameters into the function scope
  8542. for (auto Param : FD->params()) {
  8543. Param->setOwningFunction(FD);
  8544. // If this has an identifier, add it to the scope stack.
  8545. if (Param->getIdentifier() && FnBodyScope) {
  8546. CheckShadow(FnBodyScope, Param);
  8547. PushOnScopeChains(Param, FnBodyScope);
  8548. }
  8549. }
  8550. // If we had any tags defined in the function prototype,
  8551. // introduce them into the function scope.
  8552. if (FnBodyScope) {
  8553. for (ArrayRef<NamedDecl *>::iterator
  8554. I = FD->getDeclsInPrototypeScope().begin(),
  8555. E = FD->getDeclsInPrototypeScope().end();
  8556. I != E; ++I) {
  8557. NamedDecl *D = *I;
  8558. // Some of these decls (like enums) may have been pinned to the translation unit
  8559. // for lack of a real context earlier. If so, remove from the translation unit
  8560. // and reattach to the current context.
  8561. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  8562. // Is the decl actually in the context?
  8563. for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
  8564. if (DI == D) {
  8565. Context.getTranslationUnitDecl()->removeDecl(D);
  8566. break;
  8567. }
  8568. }
  8569. // Either way, reassign the lexical decl context to our FunctionDecl.
  8570. D->setLexicalDeclContext(CurContext);
  8571. }
  8572. // If the decl has a non-null name, make accessible in the current scope.
  8573. if (!D->getName().empty())
  8574. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  8575. // Similarly, dive into enums and fish their constants out, making them
  8576. // accessible in this scope.
  8577. if (auto *ED = dyn_cast<EnumDecl>(D)) {
  8578. for (auto *EI : ED->enumerators())
  8579. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  8580. }
  8581. }
  8582. }
  8583. // Ensure that the function's exception specification is instantiated.
  8584. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  8585. ResolveExceptionSpec(D->getLocation(), FPT);
  8586. // dllimport cannot be applied to non-inline function definitions.
  8587. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  8588. !FD->isTemplateInstantiation()) {
  8589. assert(!FD->hasAttr<DLLExportAttr>());
  8590. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  8591. FD->setInvalidDecl();
  8592. return D;
  8593. }
  8594. // We want to attach documentation to original Decl (which might be
  8595. // a function template).
  8596. ActOnDocumentableDecl(D);
  8597. return D;
  8598. }
  8599. /// \brief Given the set of return statements within a function body,
  8600. /// compute the variables that are subject to the named return value
  8601. /// optimization.
  8602. ///
  8603. /// Each of the variables that is subject to the named return value
  8604. /// optimization will be marked as NRVO variables in the AST, and any
  8605. /// return statement that has a marked NRVO variable as its NRVO candidate can
  8606. /// use the named return value optimization.
  8607. ///
  8608. /// This function applies a very simplistic algorithm for NRVO: if every return
  8609. /// statement in the scope of a variable has the same NRVO candidate, that
  8610. /// candidate is an NRVO variable.
  8611. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  8612. ReturnStmt **Returns = Scope->Returns.data();
  8613. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  8614. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  8615. if (!NRVOCandidate->isNRVOVariable())
  8616. Returns[I]->setNRVOCandidate(nullptr);
  8617. }
  8618. }
  8619. }
  8620. bool Sema::canDelayFunctionBody(const Declarator &D) {
  8621. // We can't delay parsing the body of a constexpr function template (yet).
  8622. if (D.getDeclSpec().isConstexprSpecified())
  8623. return false;
  8624. // We can't delay parsing the body of a function template with a deduced
  8625. // return type (yet).
  8626. if (D.getDeclSpec().containsPlaceholderType()) {
  8627. // If the placeholder introduces a non-deduced trailing return type,
  8628. // we can still delay parsing it.
  8629. if (D.getNumTypeObjects()) {
  8630. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  8631. if (Outer.Kind == DeclaratorChunk::Function &&
  8632. Outer.Fun.hasTrailingReturnType()) {
  8633. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  8634. return Ty.isNull() || !Ty->isUndeducedType();
  8635. }
  8636. }
  8637. return false;
  8638. }
  8639. return true;
  8640. }
  8641. bool Sema::canSkipFunctionBody(Decl *D) {
  8642. // We cannot skip the body of a function (or function template) which is
  8643. // constexpr, since we may need to evaluate its body in order to parse the
  8644. // rest of the file.
  8645. // We cannot skip the body of a function with an undeduced return type,
  8646. // because any callers of that function need to know the type.
  8647. if (const FunctionDecl *FD = D->getAsFunction())
  8648. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  8649. return false;
  8650. return Consumer.shouldSkipFunctionBody(D);
  8651. }
  8652. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  8653. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  8654. FD->setHasSkippedBody();
  8655. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  8656. MD->setHasSkippedBody();
  8657. return ActOnFinishFunctionBody(Decl, 0);
  8658. }
  8659. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  8660. return ActOnFinishFunctionBody(D, BodyArg, false);
  8661. }
  8662. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  8663. bool IsInstantiation) {
  8664. FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0;
  8665. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  8666. sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
  8667. if (FD) {
  8668. FD->setBody(Body);
  8669. if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
  8670. !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
  8671. // If the function has a deduced result type but contains no 'return'
  8672. // statements, the result type as written must be exactly 'auto', and
  8673. // the deduced result type is 'void'.
  8674. if (!FD->getReturnType()->getAs<AutoType>()) {
  8675. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  8676. << FD->getReturnType();
  8677. FD->setInvalidDecl();
  8678. } else {
  8679. // Substitute 'void' for the 'auto' in the type.
  8680. TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
  8681. IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
  8682. Context.adjustDeducedFunctionResultType(
  8683. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  8684. }
  8685. }
  8686. // The only way to be included in UndefinedButUsed is if there is an
  8687. // ODR use before the definition. Avoid the expensive map lookup if this
  8688. // is the first declaration.
  8689. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  8690. if (!FD->isExternallyVisible())
  8691. UndefinedButUsed.erase(FD);
  8692. else if (FD->isInlined() &&
  8693. (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
  8694. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  8695. UndefinedButUsed.erase(FD);
  8696. }
  8697. // If the function implicitly returns zero (like 'main') or is naked,
  8698. // don't complain about missing return statements.
  8699. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  8700. WP.disableCheckFallThrough();
  8701. // MSVC permits the use of pure specifier (=0) on function definition,
  8702. // defined at class scope, warn about this non-standard construct.
  8703. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  8704. Diag(FD->getLocation(), diag::warn_pure_function_definition);
  8705. if (!FD->isInvalidDecl()) {
  8706. // Don't diagnose unused parameters of defaulted or deleted functions.
  8707. if (Body)
  8708. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  8709. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  8710. FD->getReturnType(), FD);
  8711. // If this is a constructor, we need a vtable.
  8712. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  8713. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  8714. // Try to apply the named return value optimization. We have to check
  8715. // if we can do this here because lambdas keep return statements around
  8716. // to deduce an implicit return type.
  8717. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  8718. !FD->isDependentContext())
  8719. computeNRVO(Body, getCurFunction());
  8720. }
  8721. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  8722. "Function parsing confused");
  8723. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  8724. assert(MD == getCurMethodDecl() && "Method parsing confused");
  8725. MD->setBody(Body);
  8726. if (!MD->isInvalidDecl()) {
  8727. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  8728. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  8729. MD->getReturnType(), MD);
  8730. if (Body)
  8731. computeNRVO(Body, getCurFunction());
  8732. }
  8733. if (getCurFunction()->ObjCShouldCallSuper) {
  8734. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  8735. << MD->getSelector().getAsString();
  8736. getCurFunction()->ObjCShouldCallSuper = false;
  8737. }
  8738. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  8739. const ObjCMethodDecl *InitMethod = 0;
  8740. bool isDesignated =
  8741. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  8742. assert(isDesignated && InitMethod);
  8743. (void)isDesignated;
  8744. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  8745. auto IFace = MD->getClassInterface();
  8746. if (!IFace)
  8747. return false;
  8748. auto SuperD = IFace->getSuperClass();
  8749. if (!SuperD)
  8750. return false;
  8751. return SuperD->getIdentifier() ==
  8752. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  8753. };
  8754. // Don't issue this warning for unavailable inits or direct subclasses
  8755. // of NSObject.
  8756. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  8757. Diag(MD->getLocation(),
  8758. diag::warn_objc_designated_init_missing_super_call);
  8759. Diag(InitMethod->getLocation(),
  8760. diag::note_objc_designated_init_marked_here);
  8761. }
  8762. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  8763. }
  8764. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  8765. // Don't issue this warning for unavaialable inits.
  8766. if (!MD->isUnavailable())
  8767. Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
  8768. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  8769. }
  8770. } else {
  8771. return 0;
  8772. }
  8773. assert(!getCurFunction()->ObjCShouldCallSuper &&
  8774. "This should only be set for ObjC methods, which should have been "
  8775. "handled in the block above.");
  8776. // Verify and clean out per-function state.
  8777. if (Body) {
  8778. // C++ constructors that have function-try-blocks can't have return
  8779. // statements in the handlers of that block. (C++ [except.handle]p14)
  8780. // Verify this.
  8781. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  8782. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  8783. // Verify that gotos and switch cases don't jump into scopes illegally.
  8784. if (getCurFunction()->NeedsScopeChecking() &&
  8785. !PP.isCodeCompletionEnabled())
  8786. DiagnoseInvalidJumps(Body);
  8787. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  8788. if (!Destructor->getParent()->isDependentType())
  8789. CheckDestructor(Destructor);
  8790. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  8791. Destructor->getParent());
  8792. }
  8793. // If any errors have occurred, clear out any temporaries that may have
  8794. // been leftover. This ensures that these temporaries won't be picked up for
  8795. // deletion in some later function.
  8796. if (getDiagnostics().hasErrorOccurred() ||
  8797. getDiagnostics().getSuppressAllDiagnostics()) {
  8798. DiscardCleanupsInEvaluationContext();
  8799. }
  8800. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  8801. !isa<FunctionTemplateDecl>(dcl)) {
  8802. // Since the body is valid, issue any analysis-based warnings that are
  8803. // enabled.
  8804. ActivePolicy = &WP;
  8805. }
  8806. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  8807. (!CheckConstexprFunctionDecl(FD) ||
  8808. !CheckConstexprFunctionBody(FD, Body)))
  8809. FD->setInvalidDecl();
  8810. assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
  8811. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  8812. assert(MaybeODRUseExprs.empty() &&
  8813. "Leftover expressions for odr-use checking");
  8814. }
  8815. if (!IsInstantiation)
  8816. PopDeclContext();
  8817. PopFunctionScopeInfo(ActivePolicy, dcl);
  8818. // If any errors have occurred, clear out any temporaries that may have
  8819. // been leftover. This ensures that these temporaries won't be picked up for
  8820. // deletion in some later function.
  8821. if (getDiagnostics().hasErrorOccurred()) {
  8822. DiscardCleanupsInEvaluationContext();
  8823. }
  8824. return dcl;
  8825. }
  8826. /// When we finish delayed parsing of an attribute, we must attach it to the
  8827. /// relevant Decl.
  8828. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  8829. ParsedAttributes &Attrs) {
  8830. // Always attach attributes to the underlying decl.
  8831. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  8832. D = TD->getTemplatedDecl();
  8833. ProcessDeclAttributeList(S, D, Attrs.getList());
  8834. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  8835. if (Method->isStatic())
  8836. checkThisInStaticMemberFunctionAttributes(Method);
  8837. }
  8838. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  8839. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  8840. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  8841. IdentifierInfo &II, Scope *S) {
  8842. // Before we produce a declaration for an implicitly defined
  8843. // function, see whether there was a locally-scoped declaration of
  8844. // this name as a function or variable. If so, use that
  8845. // (non-visible) declaration, and complain about it.
  8846. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  8847. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  8848. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  8849. return ExternCPrev;
  8850. }
  8851. // Extension in C99. Legal in C90, but warn about it.
  8852. unsigned diag_id;
  8853. if (II.getName().startswith("__builtin_"))
  8854. diag_id = diag::warn_builtin_unknown;
  8855. else if (getLangOpts().C99)
  8856. diag_id = diag::ext_implicit_function_decl;
  8857. else
  8858. diag_id = diag::warn_implicit_function_decl;
  8859. Diag(Loc, diag_id) << &II;
  8860. // Because typo correction is expensive, only do it if the implicit
  8861. // function declaration is going to be treated as an error.
  8862. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  8863. TypoCorrection Corrected;
  8864. DeclFilterCCC<FunctionDecl> Validator;
  8865. if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
  8866. LookupOrdinaryName, S, 0, Validator,
  8867. CTK_NonError)))
  8868. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  8869. /*ErrorRecovery*/false);
  8870. }
  8871. // Set a Declarator for the implicit definition: int foo();
  8872. const char *Dummy;
  8873. AttributeFactory attrFactory;
  8874. DeclSpec DS(attrFactory);
  8875. unsigned DiagID;
  8876. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  8877. Context.getPrintingPolicy());
  8878. (void)Error; // Silence warning.
  8879. assert(!Error && "Error setting up implicit decl!");
  8880. SourceLocation NoLoc;
  8881. Declarator D(DS, Declarator::BlockContext);
  8882. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  8883. /*IsAmbiguous=*/false,
  8884. /*LParenLoc=*/NoLoc,
  8885. /*Params=*/0,
  8886. /*NumParams=*/0,
  8887. /*EllipsisLoc=*/NoLoc,
  8888. /*RParenLoc=*/NoLoc,
  8889. /*TypeQuals=*/0,
  8890. /*RefQualifierIsLvalueRef=*/true,
  8891. /*RefQualifierLoc=*/NoLoc,
  8892. /*ConstQualifierLoc=*/NoLoc,
  8893. /*VolatileQualifierLoc=*/NoLoc,
  8894. /*MutableLoc=*/NoLoc,
  8895. EST_None,
  8896. /*ESpecLoc=*/NoLoc,
  8897. /*Exceptions=*/0,
  8898. /*ExceptionRanges=*/0,
  8899. /*NumExceptions=*/0,
  8900. /*NoexceptExpr=*/0,
  8901. Loc, Loc, D),
  8902. DS.getAttributes(),
  8903. SourceLocation());
  8904. D.SetIdentifier(&II, Loc);
  8905. // Insert this function into translation-unit scope.
  8906. DeclContext *PrevDC = CurContext;
  8907. CurContext = Context.getTranslationUnitDecl();
  8908. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  8909. FD->setImplicit();
  8910. CurContext = PrevDC;
  8911. AddKnownFunctionAttributes(FD);
  8912. return FD;
  8913. }
  8914. /// \brief Adds any function attributes that we know a priori based on
  8915. /// the declaration of this function.
  8916. ///
  8917. /// These attributes can apply both to implicitly-declared builtins
  8918. /// (like __builtin___printf_chk) or to library-declared functions
  8919. /// like NSLog or printf.
  8920. ///
  8921. /// We need to check for duplicate attributes both here and where user-written
  8922. /// attributes are applied to declarations.
  8923. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  8924. if (FD->isInvalidDecl())
  8925. return;
  8926. // If this is a built-in function, map its builtin attributes to
  8927. // actual attributes.
  8928. if (unsigned BuiltinID = FD->getBuiltinID()) {
  8929. // Handle printf-formatting attributes.
  8930. unsigned FormatIdx;
  8931. bool HasVAListArg;
  8932. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  8933. if (!FD->hasAttr<FormatAttr>()) {
  8934. const char *fmt = "printf";
  8935. unsigned int NumParams = FD->getNumParams();
  8936. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  8937. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  8938. fmt = "NSString";
  8939. FD->addAttr(FormatAttr::CreateImplicit(Context,
  8940. &Context.Idents.get(fmt),
  8941. FormatIdx+1,
  8942. HasVAListArg ? 0 : FormatIdx+2,
  8943. FD->getLocation()));
  8944. }
  8945. }
  8946. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  8947. HasVAListArg)) {
  8948. if (!FD->hasAttr<FormatAttr>())
  8949. FD->addAttr(FormatAttr::CreateImplicit(Context,
  8950. &Context.Idents.get("scanf"),
  8951. FormatIdx+1,
  8952. HasVAListArg ? 0 : FormatIdx+2,
  8953. FD->getLocation()));
  8954. }
  8955. // Mark const if we don't care about errno and that is the only
  8956. // thing preventing the function from being const. This allows
  8957. // IRgen to use LLVM intrinsics for such functions.
  8958. if (!getLangOpts().MathErrno &&
  8959. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  8960. if (!FD->hasAttr<ConstAttr>())
  8961. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  8962. }
  8963. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  8964. !FD->hasAttr<ReturnsTwiceAttr>())
  8965. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  8966. FD->getLocation()));
  8967. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  8968. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  8969. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  8970. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  8971. }
  8972. IdentifierInfo *Name = FD->getIdentifier();
  8973. if (!Name)
  8974. return;
  8975. if ((!getLangOpts().CPlusPlus &&
  8976. FD->getDeclContext()->isTranslationUnit()) ||
  8977. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  8978. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  8979. LinkageSpecDecl::lang_c)) {
  8980. // Okay: this could be a libc/libm/Objective-C function we know
  8981. // about.
  8982. } else
  8983. return;
  8984. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  8985. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  8986. // target-specific builtins, perhaps?
  8987. if (!FD->hasAttr<FormatAttr>())
  8988. FD->addAttr(FormatAttr::CreateImplicit(Context,
  8989. &Context.Idents.get("printf"), 2,
  8990. Name->isStr("vasprintf") ? 0 : 3,
  8991. FD->getLocation()));
  8992. }
  8993. if (Name->isStr("__CFStringMakeConstantString")) {
  8994. // We already have a __builtin___CFStringMakeConstantString,
  8995. // but builds that use -fno-constant-cfstrings don't go through that.
  8996. if (!FD->hasAttr<FormatArgAttr>())
  8997. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  8998. FD->getLocation()));
  8999. }
  9000. }
  9001. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  9002. TypeSourceInfo *TInfo) {
  9003. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  9004. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  9005. if (!TInfo) {
  9006. assert(D.isInvalidType() && "no declarator info for valid type");
  9007. TInfo = Context.getTrivialTypeSourceInfo(T);
  9008. }
  9009. // Scope manipulation handled by caller.
  9010. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  9011. D.getLocStart(),
  9012. D.getIdentifierLoc(),
  9013. D.getIdentifier(),
  9014. TInfo);
  9015. // Bail out immediately if we have an invalid declaration.
  9016. if (D.isInvalidType()) {
  9017. NewTD->setInvalidDecl();
  9018. return NewTD;
  9019. }
  9020. if (D.getDeclSpec().isModulePrivateSpecified()) {
  9021. if (CurContext->isFunctionOrMethod())
  9022. Diag(NewTD->getLocation(), diag::err_module_private_local)
  9023. << 2 << NewTD->getDeclName()
  9024. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  9025. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  9026. else
  9027. NewTD->setModulePrivate();
  9028. }
  9029. // C++ [dcl.typedef]p8:
  9030. // If the typedef declaration defines an unnamed class (or
  9031. // enum), the first typedef-name declared by the declaration
  9032. // to be that class type (or enum type) is used to denote the
  9033. // class type (or enum type) for linkage purposes only.
  9034. // We need to check whether the type was declared in the declaration.
  9035. switch (D.getDeclSpec().getTypeSpecType()) {
  9036. case TST_enum:
  9037. case TST_struct:
  9038. case TST_interface:
  9039. case TST_union:
  9040. case TST_class: {
  9041. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  9042. // Do nothing if the tag is not anonymous or already has an
  9043. // associated typedef (from an earlier typedef in this decl group).
  9044. if (tagFromDeclSpec->getIdentifier()) break;
  9045. if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
  9046. // A well-formed anonymous tag must always be a TUK_Definition.
  9047. assert(tagFromDeclSpec->isThisDeclarationADefinition());
  9048. // The type must match the tag exactly; no qualifiers allowed.
  9049. if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
  9050. break;
  9051. // If we've already computed linkage for the anonymous tag, then
  9052. // adding a typedef name for the anonymous decl can change that
  9053. // linkage, which might be a serious problem. Diagnose this as
  9054. // unsupported and ignore the typedef name. TODO: we should
  9055. // pursue this as a language defect and establish a formal rule
  9056. // for how to handle it.
  9057. if (tagFromDeclSpec->hasLinkageBeenComputed()) {
  9058. Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage);
  9059. SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
  9060. tagLoc = getLocForEndOfToken(tagLoc);
  9061. llvm::SmallString<40> textToInsert;
  9062. textToInsert += ' ';
  9063. textToInsert += D.getIdentifier()->getName();
  9064. Diag(tagLoc, diag::note_typedef_changes_linkage)
  9065. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  9066. break;
  9067. }
  9068. // Otherwise, set this is the anon-decl typedef for the tag.
  9069. tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  9070. break;
  9071. }
  9072. default:
  9073. break;
  9074. }
  9075. return NewTD;
  9076. }
  9077. /// \brief Check that this is a valid underlying type for an enum declaration.
  9078. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  9079. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  9080. QualType T = TI->getType();
  9081. if (T->isDependentType())
  9082. return false;
  9083. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  9084. if (BT->isInteger())
  9085. return false;
  9086. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  9087. return true;
  9088. }
  9089. /// Check whether this is a valid redeclaration of a previous enumeration.
  9090. /// \return true if the redeclaration was invalid.
  9091. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  9092. QualType EnumUnderlyingTy,
  9093. const EnumDecl *Prev) {
  9094. bool IsFixed = !EnumUnderlyingTy.isNull();
  9095. if (IsScoped != Prev->isScoped()) {
  9096. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  9097. << Prev->isScoped();
  9098. Diag(Prev->getLocation(), diag::note_previous_declaration);
  9099. return true;
  9100. }
  9101. if (IsFixed && Prev->isFixed()) {
  9102. if (!EnumUnderlyingTy->isDependentType() &&
  9103. !Prev->getIntegerType()->isDependentType() &&
  9104. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  9105. Prev->getIntegerType())) {
  9106. // TODO: Highlight the underlying type of the redeclaration.
  9107. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  9108. << EnumUnderlyingTy << Prev->getIntegerType();
  9109. Diag(Prev->getLocation(), diag::note_previous_declaration)
  9110. << Prev->getIntegerTypeRange();
  9111. return true;
  9112. }
  9113. } else if (IsFixed != Prev->isFixed()) {
  9114. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  9115. << Prev->isFixed();
  9116. Diag(Prev->getLocation(), diag::note_previous_declaration);
  9117. return true;
  9118. }
  9119. return false;
  9120. }
  9121. /// \brief Get diagnostic %select index for tag kind for
  9122. /// redeclaration diagnostic message.
  9123. /// WARNING: Indexes apply to particular diagnostics only!
  9124. ///
  9125. /// \returns diagnostic %select index.
  9126. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  9127. switch (Tag) {
  9128. case TTK_Struct: return 0;
  9129. case TTK_Interface: return 1;
  9130. case TTK_Class: return 2;
  9131. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  9132. }
  9133. }
  9134. /// \brief Determine if tag kind is a class-key compatible with
  9135. /// class for redeclaration (class, struct, or __interface).
  9136. ///
  9137. /// \returns true iff the tag kind is compatible.
  9138. static bool isClassCompatTagKind(TagTypeKind Tag)
  9139. {
  9140. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  9141. }
  9142. /// \brief Determine whether a tag with a given kind is acceptable
  9143. /// as a redeclaration of the given tag declaration.
  9144. ///
  9145. /// \returns true if the new tag kind is acceptable, false otherwise.
  9146. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  9147. TagTypeKind NewTag, bool isDefinition,
  9148. SourceLocation NewTagLoc,
  9149. const IdentifierInfo &Name) {
  9150. // C++ [dcl.type.elab]p3:
  9151. // The class-key or enum keyword present in the
  9152. // elaborated-type-specifier shall agree in kind with the
  9153. // declaration to which the name in the elaborated-type-specifier
  9154. // refers. This rule also applies to the form of
  9155. // elaborated-type-specifier that declares a class-name or
  9156. // friend class since it can be construed as referring to the
  9157. // definition of the class. Thus, in any
  9158. // elaborated-type-specifier, the enum keyword shall be used to
  9159. // refer to an enumeration (7.2), the union class-key shall be
  9160. // used to refer to a union (clause 9), and either the class or
  9161. // struct class-key shall be used to refer to a class (clause 9)
  9162. // declared using the class or struct class-key.
  9163. TagTypeKind OldTag = Previous->getTagKind();
  9164. if (!isDefinition || !isClassCompatTagKind(NewTag))
  9165. if (OldTag == NewTag)
  9166. return true;
  9167. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  9168. // Warn about the struct/class tag mismatch.
  9169. bool isTemplate = false;
  9170. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  9171. isTemplate = Record->getDescribedClassTemplate();
  9172. if (!ActiveTemplateInstantiations.empty()) {
  9173. // In a template instantiation, do not offer fix-its for tag mismatches
  9174. // since they usually mess up the template instead of fixing the problem.
  9175. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  9176. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  9177. << getRedeclDiagFromTagKind(OldTag);
  9178. return true;
  9179. }
  9180. if (isDefinition) {
  9181. // On definitions, check previous tags and issue a fix-it for each
  9182. // one that doesn't match the current tag.
  9183. if (Previous->getDefinition()) {
  9184. // Don't suggest fix-its for redefinitions.
  9185. return true;
  9186. }
  9187. bool previousMismatch = false;
  9188. for (auto I : Previous->redecls()) {
  9189. if (I->getTagKind() != NewTag) {
  9190. if (!previousMismatch) {
  9191. previousMismatch = true;
  9192. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  9193. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  9194. << getRedeclDiagFromTagKind(I->getTagKind());
  9195. }
  9196. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  9197. << getRedeclDiagFromTagKind(NewTag)
  9198. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  9199. TypeWithKeyword::getTagTypeKindName(NewTag));
  9200. }
  9201. }
  9202. return true;
  9203. }
  9204. // Check for a previous definition. If current tag and definition
  9205. // are same type, do nothing. If no definition, but disagree with
  9206. // with previous tag type, give a warning, but no fix-it.
  9207. const TagDecl *Redecl = Previous->getDefinition() ?
  9208. Previous->getDefinition() : Previous;
  9209. if (Redecl->getTagKind() == NewTag) {
  9210. return true;
  9211. }
  9212. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  9213. << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
  9214. << getRedeclDiagFromTagKind(OldTag);
  9215. Diag(Redecl->getLocation(), diag::note_previous_use);
  9216. // If there is a previous definition, suggest a fix-it.
  9217. if (Previous->getDefinition()) {
  9218. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  9219. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  9220. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  9221. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  9222. }
  9223. return true;
  9224. }
  9225. return false;
  9226. }
  9227. /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  9228. /// former case, Name will be non-null. In the later case, Name will be null.
  9229. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  9230. /// reference/declaration/definition of a tag.
  9231. ///
  9232. /// IsTypeSpecifier is true if this is a type-specifier (or
  9233. /// trailing-type-specifier) other than one in an alias-declaration.
  9234. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  9235. SourceLocation KWLoc, CXXScopeSpec &SS,
  9236. IdentifierInfo *Name, SourceLocation NameLoc,
  9237. AttributeList *Attr, AccessSpecifier AS,
  9238. SourceLocation ModulePrivateLoc,
  9239. MultiTemplateParamsArg TemplateParameterLists,
  9240. bool &OwnedDecl, bool &IsDependent,
  9241. SourceLocation ScopedEnumKWLoc,
  9242. bool ScopedEnumUsesClassTag,
  9243. TypeResult UnderlyingType,
  9244. bool IsTypeSpecifier) {
  9245. // If this is not a definition, it must have a name.
  9246. IdentifierInfo *OrigName = Name;
  9247. assert((Name != 0 || TUK == TUK_Definition) &&
  9248. "Nameless record must be a definition!");
  9249. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  9250. OwnedDecl = false;
  9251. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  9252. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  9253. // FIXME: Check explicit specializations more carefully.
  9254. bool isExplicitSpecialization = false;
  9255. bool Invalid = false;
  9256. // We only need to do this matching if we have template parameters
  9257. // or a scope specifier, which also conveniently avoids this work
  9258. // for non-C++ cases.
  9259. if (TemplateParameterLists.size() > 0 ||
  9260. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  9261. if (TemplateParameterList *TemplateParams =
  9262. MatchTemplateParametersToScopeSpecifier(
  9263. KWLoc, NameLoc, SS, 0, TemplateParameterLists,
  9264. TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
  9265. if (Kind == TTK_Enum) {
  9266. Diag(KWLoc, diag::err_enum_template);
  9267. return 0;
  9268. }
  9269. if (TemplateParams->size() > 0) {
  9270. // This is a declaration or definition of a class template (which may
  9271. // be a member of another template).
  9272. if (Invalid)
  9273. return 0;
  9274. OwnedDecl = false;
  9275. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  9276. SS, Name, NameLoc, Attr,
  9277. TemplateParams, AS,
  9278. ModulePrivateLoc,
  9279. TemplateParameterLists.size()-1,
  9280. TemplateParameterLists.data());
  9281. return Result.get();
  9282. } else {
  9283. // The "template<>" header is extraneous.
  9284. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  9285. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  9286. isExplicitSpecialization = true;
  9287. }
  9288. }
  9289. }
  9290. // Figure out the underlying type if this a enum declaration. We need to do
  9291. // this early, because it's needed to detect if this is an incompatible
  9292. // redeclaration.
  9293. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  9294. if (Kind == TTK_Enum) {
  9295. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  9296. // No underlying type explicitly specified, or we failed to parse the
  9297. // type, default to int.
  9298. EnumUnderlying = Context.IntTy.getTypePtr();
  9299. else if (UnderlyingType.get()) {
  9300. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  9301. // integral type; any cv-qualification is ignored.
  9302. TypeSourceInfo *TI = 0;
  9303. GetTypeFromParser(UnderlyingType.get(), &TI);
  9304. EnumUnderlying = TI;
  9305. if (CheckEnumUnderlyingType(TI))
  9306. // Recover by falling back to int.
  9307. EnumUnderlying = Context.IntTy.getTypePtr();
  9308. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  9309. UPPC_FixedUnderlyingType))
  9310. EnumUnderlying = Context.IntTy.getTypePtr();
  9311. } else if (getLangOpts().MSVCCompat)
  9312. // Microsoft enums are always of int type.
  9313. EnumUnderlying = Context.IntTy.getTypePtr();
  9314. }
  9315. DeclContext *SearchDC = CurContext;
  9316. DeclContext *DC = CurContext;
  9317. bool isStdBadAlloc = false;
  9318. RedeclarationKind Redecl = ForRedeclaration;
  9319. if (TUK == TUK_Friend || TUK == TUK_Reference)
  9320. Redecl = NotForRedeclaration;
  9321. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  9322. bool FriendSawTagOutsideEnclosingNamespace = false;
  9323. if (Name && SS.isNotEmpty()) {
  9324. // We have a nested-name tag ('struct foo::bar').
  9325. // Check for invalid 'foo::'.
  9326. if (SS.isInvalid()) {
  9327. Name = 0;
  9328. goto CreateNewDecl;
  9329. }
  9330. // If this is a friend or a reference to a class in a dependent
  9331. // context, don't try to make a decl for it.
  9332. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  9333. DC = computeDeclContext(SS, false);
  9334. if (!DC) {
  9335. IsDependent = true;
  9336. return 0;
  9337. }
  9338. } else {
  9339. DC = computeDeclContext(SS, true);
  9340. if (!DC) {
  9341. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  9342. << SS.getRange();
  9343. return 0;
  9344. }
  9345. }
  9346. if (RequireCompleteDeclContext(SS, DC))
  9347. return 0;
  9348. SearchDC = DC;
  9349. // Look-up name inside 'foo::'.
  9350. LookupQualifiedName(Previous, DC);
  9351. if (Previous.isAmbiguous())
  9352. return 0;
  9353. if (Previous.empty()) {
  9354. // Name lookup did not find anything. However, if the
  9355. // nested-name-specifier refers to the current instantiation,
  9356. // and that current instantiation has any dependent base
  9357. // classes, we might find something at instantiation time: treat
  9358. // this as a dependent elaborated-type-specifier.
  9359. // But this only makes any sense for reference-like lookups.
  9360. if (Previous.wasNotFoundInCurrentInstantiation() &&
  9361. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  9362. IsDependent = true;
  9363. return 0;
  9364. }
  9365. // A tag 'foo::bar' must already exist.
  9366. Diag(NameLoc, diag::err_not_tag_in_scope)
  9367. << Kind << Name << DC << SS.getRange();
  9368. Name = 0;
  9369. Invalid = true;
  9370. goto CreateNewDecl;
  9371. }
  9372. } else if (Name) {
  9373. // If this is a named struct, check to see if there was a previous forward
  9374. // declaration or definition.
  9375. // FIXME: We're looking into outer scopes here, even when we
  9376. // shouldn't be. Doing so can result in ambiguities that we
  9377. // shouldn't be diagnosing.
  9378. LookupName(Previous, S);
  9379. // When declaring or defining a tag, ignore ambiguities introduced
  9380. // by types using'ed into this scope.
  9381. if (Previous.isAmbiguous() &&
  9382. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  9383. LookupResult::Filter F = Previous.makeFilter();
  9384. while (F.hasNext()) {
  9385. NamedDecl *ND = F.next();
  9386. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  9387. F.erase();
  9388. }
  9389. F.done();
  9390. }
  9391. // C++11 [namespace.memdef]p3:
  9392. // If the name in a friend declaration is neither qualified nor
  9393. // a template-id and the declaration is a function or an
  9394. // elaborated-type-specifier, the lookup to determine whether
  9395. // the entity has been previously declared shall not consider
  9396. // any scopes outside the innermost enclosing namespace.
  9397. //
  9398. // Does it matter that this should be by scope instead of by
  9399. // semantic context?
  9400. if (!Previous.empty() && TUK == TUK_Friend) {
  9401. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  9402. LookupResult::Filter F = Previous.makeFilter();
  9403. while (F.hasNext()) {
  9404. NamedDecl *ND = F.next();
  9405. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  9406. if (DC->isFileContext() &&
  9407. !EnclosingNS->Encloses(ND->getDeclContext())) {
  9408. F.erase();
  9409. FriendSawTagOutsideEnclosingNamespace = true;
  9410. }
  9411. }
  9412. F.done();
  9413. }
  9414. // Note: there used to be some attempt at recovery here.
  9415. if (Previous.isAmbiguous())
  9416. return 0;
  9417. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  9418. // FIXME: This makes sure that we ignore the contexts associated
  9419. // with C structs, unions, and enums when looking for a matching
  9420. // tag declaration or definition. See the similar lookup tweak
  9421. // in Sema::LookupName; is there a better way to deal with this?
  9422. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  9423. SearchDC = SearchDC->getParent();
  9424. }
  9425. } else if (S->isFunctionPrototypeScope()) {
  9426. // If this is an enum declaration in function prototype scope, set its
  9427. // initial context to the translation unit.
  9428. // FIXME: [citation needed]
  9429. SearchDC = Context.getTranslationUnitDecl();
  9430. }
  9431. if (Previous.isSingleResult() &&
  9432. Previous.getFoundDecl()->isTemplateParameter()) {
  9433. // Maybe we will complain about the shadowed template parameter.
  9434. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  9435. // Just pretend that we didn't see the previous declaration.
  9436. Previous.clear();
  9437. }
  9438. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  9439. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  9440. // This is a declaration of or a reference to "std::bad_alloc".
  9441. isStdBadAlloc = true;
  9442. if (Previous.empty() && StdBadAlloc) {
  9443. // std::bad_alloc has been implicitly declared (but made invisible to
  9444. // name lookup). Fill in this implicit declaration as the previous
  9445. // declaration, so that the declarations get chained appropriately.
  9446. Previous.addDecl(getStdBadAlloc());
  9447. }
  9448. }
  9449. // If we didn't find a previous declaration, and this is a reference
  9450. // (or friend reference), move to the correct scope. In C++, we
  9451. // also need to do a redeclaration lookup there, just in case
  9452. // there's a shadow friend decl.
  9453. if (Name && Previous.empty() &&
  9454. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  9455. if (Invalid) goto CreateNewDecl;
  9456. assert(SS.isEmpty());
  9457. if (TUK == TUK_Reference) {
  9458. // C++ [basic.scope.pdecl]p5:
  9459. // -- for an elaborated-type-specifier of the form
  9460. //
  9461. // class-key identifier
  9462. //
  9463. // if the elaborated-type-specifier is used in the
  9464. // decl-specifier-seq or parameter-declaration-clause of a
  9465. // function defined in namespace scope, the identifier is
  9466. // declared as a class-name in the namespace that contains
  9467. // the declaration; otherwise, except as a friend
  9468. // declaration, the identifier is declared in the smallest
  9469. // non-class, non-function-prototype scope that contains the
  9470. // declaration.
  9471. //
  9472. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  9473. // C structs and unions.
  9474. //
  9475. // It is an error in C++ to declare (rather than define) an enum
  9476. // type, including via an elaborated type specifier. We'll
  9477. // diagnose that later; for now, declare the enum in the same
  9478. // scope as we would have picked for any other tag type.
  9479. //
  9480. // GNU C also supports this behavior as part of its incomplete
  9481. // enum types extension, while GNU C++ does not.
  9482. //
  9483. // Find the context where we'll be declaring the tag.
  9484. // FIXME: We would like to maintain the current DeclContext as the
  9485. // lexical context,
  9486. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  9487. SearchDC = SearchDC->getParent();
  9488. // Find the scope where we'll be declaring the tag.
  9489. while (S->isClassScope() ||
  9490. (getLangOpts().CPlusPlus &&
  9491. S->isFunctionPrototypeScope()) ||
  9492. ((S->getFlags() & Scope::DeclScope) == 0) ||
  9493. (S->getEntity() && S->getEntity()->isTransparentContext()))
  9494. S = S->getParent();
  9495. } else {
  9496. assert(TUK == TUK_Friend);
  9497. // C++ [namespace.memdef]p3:
  9498. // If a friend declaration in a non-local class first declares a
  9499. // class or function, the friend class or function is a member of
  9500. // the innermost enclosing namespace.
  9501. SearchDC = SearchDC->getEnclosingNamespaceContext();
  9502. }
  9503. // In C++, we need to do a redeclaration lookup to properly
  9504. // diagnose some problems.
  9505. if (getLangOpts().CPlusPlus) {
  9506. Previous.setRedeclarationKind(ForRedeclaration);
  9507. LookupQualifiedName(Previous, SearchDC);
  9508. }
  9509. }
  9510. if (!Previous.empty()) {
  9511. NamedDecl *PrevDecl = Previous.getFoundDecl();
  9512. NamedDecl *DirectPrevDecl =
  9513. getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
  9514. // It's okay to have a tag decl in the same scope as a typedef
  9515. // which hides a tag decl in the same scope. Finding this
  9516. // insanity with a redeclaration lookup can only actually happen
  9517. // in C++.
  9518. //
  9519. // This is also okay for elaborated-type-specifiers, which is
  9520. // technically forbidden by the current standard but which is
  9521. // okay according to the likely resolution of an open issue;
  9522. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  9523. if (getLangOpts().CPlusPlus) {
  9524. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  9525. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  9526. TagDecl *Tag = TT->getDecl();
  9527. if (Tag->getDeclName() == Name &&
  9528. Tag->getDeclContext()->getRedeclContext()
  9529. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  9530. PrevDecl = Tag;
  9531. Previous.clear();
  9532. Previous.addDecl(Tag);
  9533. Previous.resolveKind();
  9534. }
  9535. }
  9536. }
  9537. }
  9538. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  9539. // If this is a use of a previous tag, or if the tag is already declared
  9540. // in the same scope (so that the definition/declaration completes or
  9541. // rementions the tag), reuse the decl.
  9542. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  9543. isDeclInScope(DirectPrevDecl, SearchDC, S,
  9544. SS.isNotEmpty() || isExplicitSpecialization)) {
  9545. // Make sure that this wasn't declared as an enum and now used as a
  9546. // struct or something similar.
  9547. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  9548. TUK == TUK_Definition, KWLoc,
  9549. *Name)) {
  9550. bool SafeToContinue
  9551. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  9552. Kind != TTK_Enum);
  9553. if (SafeToContinue)
  9554. Diag(KWLoc, diag::err_use_with_wrong_tag)
  9555. << Name
  9556. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  9557. PrevTagDecl->getKindName());
  9558. else
  9559. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  9560. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  9561. if (SafeToContinue)
  9562. Kind = PrevTagDecl->getTagKind();
  9563. else {
  9564. // Recover by making this an anonymous redefinition.
  9565. Name = 0;
  9566. Previous.clear();
  9567. Invalid = true;
  9568. }
  9569. }
  9570. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  9571. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  9572. // If this is an elaborated-type-specifier for a scoped enumeration,
  9573. // the 'class' keyword is not necessary and not permitted.
  9574. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  9575. if (ScopedEnum)
  9576. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  9577. << PrevEnum->isScoped()
  9578. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  9579. return PrevTagDecl;
  9580. }
  9581. QualType EnumUnderlyingTy;
  9582. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  9583. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  9584. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  9585. EnumUnderlyingTy = QualType(T, 0);
  9586. // All conflicts with previous declarations are recovered by
  9587. // returning the previous declaration, unless this is a definition,
  9588. // in which case we want the caller to bail out.
  9589. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  9590. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  9591. return TUK == TUK_Declaration ? PrevTagDecl : 0;
  9592. }
  9593. // C++11 [class.mem]p1:
  9594. // A member shall not be declared twice in the member-specification,
  9595. // except that a nested class or member class template can be declared
  9596. // and then later defined.
  9597. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  9598. S->isDeclScope(PrevDecl)) {
  9599. Diag(NameLoc, diag::ext_member_redeclared);
  9600. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  9601. }
  9602. if (!Invalid) {
  9603. // If this is a use, just return the declaration we found, unless
  9604. // we have attributes.
  9605. // FIXME: In the future, return a variant or some other clue
  9606. // for the consumer of this Decl to know it doesn't own it.
  9607. // For our current ASTs this shouldn't be a problem, but will
  9608. // need to be changed with DeclGroups.
  9609. if (!Attr &&
  9610. ((TUK == TUK_Reference &&
  9611. (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
  9612. || TUK == TUK_Friend))
  9613. return PrevTagDecl;
  9614. // Diagnose attempts to redefine a tag.
  9615. if (TUK == TUK_Definition) {
  9616. if (TagDecl *Def = PrevTagDecl->getDefinition()) {
  9617. // If we're defining a specialization and the previous definition
  9618. // is from an implicit instantiation, don't emit an error
  9619. // here; we'll catch this in the general case below.
  9620. bool IsExplicitSpecializationAfterInstantiation = false;
  9621. if (isExplicitSpecialization) {
  9622. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  9623. IsExplicitSpecializationAfterInstantiation =
  9624. RD->getTemplateSpecializationKind() !=
  9625. TSK_ExplicitSpecialization;
  9626. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  9627. IsExplicitSpecializationAfterInstantiation =
  9628. ED->getTemplateSpecializationKind() !=
  9629. TSK_ExplicitSpecialization;
  9630. }
  9631. if (!IsExplicitSpecializationAfterInstantiation) {
  9632. // A redeclaration in function prototype scope in C isn't
  9633. // visible elsewhere, so merely issue a warning.
  9634. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  9635. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  9636. else
  9637. Diag(NameLoc, diag::err_redefinition) << Name;
  9638. Diag(Def->getLocation(), diag::note_previous_definition);
  9639. // If this is a redefinition, recover by making this
  9640. // struct be anonymous, which will make any later
  9641. // references get the previous definition.
  9642. Name = 0;
  9643. Previous.clear();
  9644. Invalid = true;
  9645. }
  9646. } else {
  9647. // If the type is currently being defined, complain
  9648. // about a nested redefinition.
  9649. const TagType *Tag
  9650. = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
  9651. if (Tag->isBeingDefined()) {
  9652. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  9653. Diag(PrevTagDecl->getLocation(),
  9654. diag::note_previous_definition);
  9655. Name = 0;
  9656. Previous.clear();
  9657. Invalid = true;
  9658. }
  9659. }
  9660. // Okay, this is definition of a previously declared or referenced
  9661. // tag. We're going to create a new Decl for it.
  9662. }
  9663. // Okay, we're going to make a redeclaration. If this is some kind
  9664. // of reference, make sure we build the redeclaration in the same DC
  9665. // as the original, and ignore the current access specifier.
  9666. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  9667. SearchDC = PrevTagDecl->getDeclContext();
  9668. AS = AS_none;
  9669. }
  9670. }
  9671. // If we get here we have (another) forward declaration or we
  9672. // have a definition. Just create a new decl.
  9673. } else {
  9674. // If we get here, this is a definition of a new tag type in a nested
  9675. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  9676. // new decl/type. We set PrevDecl to NULL so that the entities
  9677. // have distinct types.
  9678. Previous.clear();
  9679. }
  9680. // If we get here, we're going to create a new Decl. If PrevDecl
  9681. // is non-NULL, it's a definition of the tag declared by
  9682. // PrevDecl. If it's NULL, we have a new definition.
  9683. // Otherwise, PrevDecl is not a tag, but was found with tag
  9684. // lookup. This is only actually possible in C++, where a few
  9685. // things like templates still live in the tag namespace.
  9686. } else {
  9687. // Use a better diagnostic if an elaborated-type-specifier
  9688. // found the wrong kind of type on the first
  9689. // (non-redeclaration) lookup.
  9690. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  9691. !Previous.isForRedeclaration()) {
  9692. unsigned Kind = 0;
  9693. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  9694. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  9695. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  9696. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  9697. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  9698. Invalid = true;
  9699. // Otherwise, only diagnose if the declaration is in scope.
  9700. } else if (!isDeclInScope(PrevDecl, SearchDC, S,
  9701. SS.isNotEmpty() || isExplicitSpecialization)) {
  9702. // do nothing
  9703. // Diagnose implicit declarations introduced by elaborated types.
  9704. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  9705. unsigned Kind = 0;
  9706. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  9707. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  9708. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  9709. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  9710. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  9711. Invalid = true;
  9712. // Otherwise it's a declaration. Call out a particularly common
  9713. // case here.
  9714. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  9715. unsigned Kind = 0;
  9716. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  9717. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  9718. << Name << Kind << TND->getUnderlyingType();
  9719. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  9720. Invalid = true;
  9721. // Otherwise, diagnose.
  9722. } else {
  9723. // The tag name clashes with something else in the target scope,
  9724. // issue an error and recover by making this tag be anonymous.
  9725. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  9726. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9727. Name = 0;
  9728. Invalid = true;
  9729. }
  9730. // The existing declaration isn't relevant to us; we're in a
  9731. // new scope, so clear out the previous declaration.
  9732. Previous.clear();
  9733. }
  9734. }
  9735. CreateNewDecl:
  9736. TagDecl *PrevDecl = 0;
  9737. if (Previous.isSingleResult())
  9738. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  9739. // If there is an identifier, use the location of the identifier as the
  9740. // location of the decl, otherwise use the location of the struct/union
  9741. // keyword.
  9742. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  9743. // Otherwise, create a new declaration. If there is a previous
  9744. // declaration of the same entity, the two will be linked via
  9745. // PrevDecl.
  9746. TagDecl *New;
  9747. bool IsForwardReference = false;
  9748. if (Kind == TTK_Enum) {
  9749. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  9750. // enum X { A, B, C } D; D should chain to X.
  9751. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  9752. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  9753. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  9754. // If this is an undefined enum, warn.
  9755. if (TUK != TUK_Definition && !Invalid) {
  9756. TagDecl *Def;
  9757. if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  9758. cast<EnumDecl>(New)->isFixed()) {
  9759. // C++0x: 7.2p2: opaque-enum-declaration.
  9760. // Conflicts are diagnosed above. Do nothing.
  9761. }
  9762. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  9763. Diag(Loc, diag::ext_forward_ref_enum_def)
  9764. << New;
  9765. Diag(Def->getLocation(), diag::note_previous_definition);
  9766. } else {
  9767. unsigned DiagID = diag::ext_forward_ref_enum;
  9768. if (getLangOpts().MSVCCompat)
  9769. DiagID = diag::ext_ms_forward_ref_enum;
  9770. else if (getLangOpts().CPlusPlus)
  9771. DiagID = diag::err_forward_ref_enum;
  9772. Diag(Loc, DiagID);
  9773. // If this is a forward-declared reference to an enumeration, make a
  9774. // note of it; we won't actually be introducing the declaration into
  9775. // the declaration context.
  9776. if (TUK == TUK_Reference)
  9777. IsForwardReference = true;
  9778. }
  9779. }
  9780. if (EnumUnderlying) {
  9781. EnumDecl *ED = cast<EnumDecl>(New);
  9782. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  9783. ED->setIntegerTypeSourceInfo(TI);
  9784. else
  9785. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  9786. ED->setPromotionType(ED->getIntegerType());
  9787. }
  9788. } else {
  9789. // struct/union/class
  9790. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  9791. // struct X { int A; } D; D should chain to X.
  9792. if (getLangOpts().CPlusPlus) {
  9793. // FIXME: Look for a way to use RecordDecl for simple structs.
  9794. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  9795. cast_or_null<CXXRecordDecl>(PrevDecl));
  9796. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  9797. StdBadAlloc = cast<CXXRecordDecl>(New);
  9798. } else
  9799. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  9800. cast_or_null<RecordDecl>(PrevDecl));
  9801. }
  9802. // C++11 [dcl.type]p3:
  9803. // A type-specifier-seq shall not define a class or enumeration [...].
  9804. if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
  9805. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  9806. << Context.getTagDeclType(New);
  9807. Invalid = true;
  9808. }
  9809. // Maybe add qualifier info.
  9810. if (SS.isNotEmpty()) {
  9811. if (SS.isSet()) {
  9812. // If this is either a declaration or a definition, check the
  9813. // nested-name-specifier against the current context. We don't do this
  9814. // for explicit specializations, because they have similar checking
  9815. // (with more specific diagnostics) in the call to
  9816. // CheckMemberSpecialization, below.
  9817. if (!isExplicitSpecialization &&
  9818. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  9819. diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
  9820. Invalid = true;
  9821. New->setQualifierInfo(SS.getWithLocInContext(Context));
  9822. if (TemplateParameterLists.size() > 0) {
  9823. New->setTemplateParameterListsInfo(Context,
  9824. TemplateParameterLists.size(),
  9825. TemplateParameterLists.data());
  9826. }
  9827. }
  9828. else
  9829. Invalid = true;
  9830. }
  9831. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  9832. // Add alignment attributes if necessary; these attributes are checked when
  9833. // the ASTContext lays out the structure.
  9834. //
  9835. // It is important for implementing the correct semantics that this
  9836. // happen here (in act on tag decl). The #pragma pack stack is
  9837. // maintained as a result of parser callbacks which can occur at
  9838. // many points during the parsing of a struct declaration (because
  9839. // the #pragma tokens are effectively skipped over during the
  9840. // parsing of the struct).
  9841. if (TUK == TUK_Definition) {
  9842. AddAlignmentAttributesForRecord(RD);
  9843. AddMsStructLayoutForRecord(RD);
  9844. }
  9845. }
  9846. if (ModulePrivateLoc.isValid()) {
  9847. if (isExplicitSpecialization)
  9848. Diag(New->getLocation(), diag::err_module_private_specialization)
  9849. << 2
  9850. << FixItHint::CreateRemoval(ModulePrivateLoc);
  9851. // __module_private__ does not apply to local classes. However, we only
  9852. // diagnose this as an error when the declaration specifiers are
  9853. // freestanding. Here, we just ignore the __module_private__.
  9854. else if (!SearchDC->isFunctionOrMethod())
  9855. New->setModulePrivate();
  9856. }
  9857. // If this is a specialization of a member class (of a class template),
  9858. // check the specialization.
  9859. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  9860. Invalid = true;
  9861. if (Invalid)
  9862. New->setInvalidDecl();
  9863. if (Attr)
  9864. ProcessDeclAttributeList(S, New, Attr);
  9865. // If we're declaring or defining a tag in function prototype scope in C,
  9866. // note that this type can only be used within the function and add it to
  9867. // the list of decls to inject into the function definition scope.
  9868. if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) &&
  9869. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  9870. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  9871. DeclsInPrototypeScope.push_back(New);
  9872. }
  9873. // Set the lexical context. If the tag has a C++ scope specifier, the
  9874. // lexical context will be different from the semantic context.
  9875. New->setLexicalDeclContext(CurContext);
  9876. // Mark this as a friend decl if applicable.
  9877. // In Microsoft mode, a friend declaration also acts as a forward
  9878. // declaration so we always pass true to setObjectOfFriendDecl to make
  9879. // the tag name visible.
  9880. if (TUK == TUK_Friend)
  9881. New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
  9882. getLangOpts().MicrosoftExt);
  9883. // Set the access specifier.
  9884. if (!Invalid && SearchDC->isRecord())
  9885. SetMemberAccessSpecifier(New, PrevDecl, AS);
  9886. if (TUK == TUK_Definition)
  9887. New->startDefinition();
  9888. // If this has an identifier, add it to the scope stack.
  9889. if (TUK == TUK_Friend) {
  9890. // We might be replacing an existing declaration in the lookup tables;
  9891. // if so, borrow its access specifier.
  9892. if (PrevDecl)
  9893. New->setAccess(PrevDecl->getAccess());
  9894. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  9895. DC->makeDeclVisibleInContext(New);
  9896. if (Name) // can be null along some error paths
  9897. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  9898. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  9899. } else if (Name) {
  9900. S = getNonFieldDeclScope(S);
  9901. PushOnScopeChains(New, S, !IsForwardReference);
  9902. if (IsForwardReference)
  9903. SearchDC->makeDeclVisibleInContext(New);
  9904. } else {
  9905. CurContext->addDecl(New);
  9906. }
  9907. // If this is the C FILE type, notify the AST context.
  9908. if (IdentifierInfo *II = New->getIdentifier())
  9909. if (!New->isInvalidDecl() &&
  9910. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  9911. II->isStr("FILE"))
  9912. Context.setFILEDecl(New);
  9913. if (PrevDecl)
  9914. mergeDeclAttributes(New, PrevDecl);
  9915. // If there's a #pragma GCC visibility in scope, set the visibility of this
  9916. // record.
  9917. AddPushedVisibilityAttribute(New);
  9918. OwnedDecl = true;
  9919. // In C++, don't return an invalid declaration. We can't recover well from
  9920. // the cases where we make the type anonymous.
  9921. return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
  9922. }
  9923. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  9924. AdjustDeclIfTemplate(TagD);
  9925. TagDecl *Tag = cast<TagDecl>(TagD);
  9926. // Enter the tag context.
  9927. PushDeclContext(S, Tag);
  9928. ActOnDocumentableDecl(TagD);
  9929. // If there's a #pragma GCC visibility in scope, set the visibility of this
  9930. // record.
  9931. AddPushedVisibilityAttribute(Tag);
  9932. }
  9933. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  9934. assert(isa<ObjCContainerDecl>(IDecl) &&
  9935. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  9936. DeclContext *OCD = cast<DeclContext>(IDecl);
  9937. assert(getContainingDC(OCD) == CurContext &&
  9938. "The next DeclContext should be lexically contained in the current one.");
  9939. CurContext = OCD;
  9940. return IDecl;
  9941. }
  9942. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  9943. SourceLocation FinalLoc,
  9944. bool IsFinalSpelledSealed,
  9945. SourceLocation LBraceLoc) {
  9946. AdjustDeclIfTemplate(TagD);
  9947. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  9948. FieldCollector->StartClass();
  9949. if (!Record->getIdentifier())
  9950. return;
  9951. if (FinalLoc.isValid())
  9952. Record->addAttr(new (Context)
  9953. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  9954. // C++ [class]p2:
  9955. // [...] The class-name is also inserted into the scope of the
  9956. // class itself; this is known as the injected-class-name. For
  9957. // purposes of access checking, the injected-class-name is treated
  9958. // as if it were a public member name.
  9959. CXXRecordDecl *InjectedClassName
  9960. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  9961. Record->getLocStart(), Record->getLocation(),
  9962. Record->getIdentifier(),
  9963. /*PrevDecl=*/0,
  9964. /*DelayTypeCreation=*/true);
  9965. Context.getTypeDeclType(InjectedClassName, Record);
  9966. InjectedClassName->setImplicit();
  9967. InjectedClassName->setAccess(AS_public);
  9968. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  9969. InjectedClassName->setDescribedClassTemplate(Template);
  9970. PushOnScopeChains(InjectedClassName, S);
  9971. assert(InjectedClassName->isInjectedClassName() &&
  9972. "Broken injected-class-name");
  9973. }
  9974. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  9975. SourceLocation RBraceLoc) {
  9976. AdjustDeclIfTemplate(TagD);
  9977. TagDecl *Tag = cast<TagDecl>(TagD);
  9978. Tag->setRBraceLoc(RBraceLoc);
  9979. // Make sure we "complete" the definition even it is invalid.
  9980. if (Tag->isBeingDefined()) {
  9981. assert(Tag->isInvalidDecl() && "We should already have completed it");
  9982. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  9983. RD->completeDefinition();
  9984. }
  9985. if (isa<CXXRecordDecl>(Tag))
  9986. FieldCollector->FinishClass();
  9987. // Exit this scope of this tag's definition.
  9988. PopDeclContext();
  9989. if (getCurLexicalContext()->isObjCContainer() &&
  9990. Tag->getDeclContext()->isFileContext())
  9991. Tag->setTopLevelDeclInObjCContainer();
  9992. // Notify the consumer that we've defined a tag.
  9993. if (!Tag->isInvalidDecl())
  9994. Consumer.HandleTagDeclDefinition(Tag);
  9995. }
  9996. void Sema::ActOnObjCContainerFinishDefinition() {
  9997. // Exit this scope of this interface definition.
  9998. PopDeclContext();
  9999. }
  10000. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  10001. assert(DC == CurContext && "Mismatch of container contexts");
  10002. OriginalLexicalContext = DC;
  10003. ActOnObjCContainerFinishDefinition();
  10004. }
  10005. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  10006. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  10007. OriginalLexicalContext = 0;
  10008. }
  10009. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  10010. AdjustDeclIfTemplate(TagD);
  10011. TagDecl *Tag = cast<TagDecl>(TagD);
  10012. Tag->setInvalidDecl();
  10013. // Make sure we "complete" the definition even it is invalid.
  10014. if (Tag->isBeingDefined()) {
  10015. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  10016. RD->completeDefinition();
  10017. }
  10018. // We're undoing ActOnTagStartDefinition here, not
  10019. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  10020. // the FieldCollector.
  10021. PopDeclContext();
  10022. }
  10023. // Note that FieldName may be null for anonymous bitfields.
  10024. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  10025. IdentifierInfo *FieldName,
  10026. QualType FieldTy, bool IsMsStruct,
  10027. Expr *BitWidth, bool *ZeroWidth) {
  10028. // Default to true; that shouldn't confuse checks for emptiness
  10029. if (ZeroWidth)
  10030. *ZeroWidth = true;
  10031. // C99 6.7.2.1p4 - verify the field type.
  10032. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  10033. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  10034. // Handle incomplete types with specific error.
  10035. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  10036. return ExprError();
  10037. if (FieldName)
  10038. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  10039. << FieldName << FieldTy << BitWidth->getSourceRange();
  10040. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  10041. << FieldTy << BitWidth->getSourceRange();
  10042. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  10043. UPPC_BitFieldWidth))
  10044. return ExprError();
  10045. // If the bit-width is type- or value-dependent, don't try to check
  10046. // it now.
  10047. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  10048. return Owned(BitWidth);
  10049. llvm::APSInt Value;
  10050. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  10051. if (ICE.isInvalid())
  10052. return ICE;
  10053. BitWidth = ICE.take();
  10054. if (Value != 0 && ZeroWidth)
  10055. *ZeroWidth = false;
  10056. // Zero-width bitfield is ok for anonymous field.
  10057. if (Value == 0 && FieldName)
  10058. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  10059. if (Value.isSigned() && Value.isNegative()) {
  10060. if (FieldName)
  10061. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  10062. << FieldName << Value.toString(10);
  10063. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  10064. << Value.toString(10);
  10065. }
  10066. if (!FieldTy->isDependentType()) {
  10067. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  10068. if (Value.getZExtValue() > TypeSize) {
  10069. if (!getLangOpts().CPlusPlus || IsMsStruct ||
  10070. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  10071. if (FieldName)
  10072. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  10073. << FieldName << (unsigned)Value.getZExtValue()
  10074. << (unsigned)TypeSize;
  10075. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  10076. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  10077. }
  10078. if (FieldName)
  10079. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  10080. << FieldName << (unsigned)Value.getZExtValue()
  10081. << (unsigned)TypeSize;
  10082. else
  10083. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  10084. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  10085. }
  10086. }
  10087. return Owned(BitWidth);
  10088. }
  10089. /// ActOnField - Each field of a C struct/union is passed into this in order
  10090. /// to create a FieldDecl object for it.
  10091. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  10092. Declarator &D, Expr *BitfieldWidth) {
  10093. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  10094. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  10095. /*InitStyle=*/ICIS_NoInit, AS_public);
  10096. return Res;
  10097. }
  10098. /// HandleField - Analyze a field of a C struct or a C++ data member.
  10099. ///
  10100. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  10101. SourceLocation DeclStart,
  10102. Declarator &D, Expr *BitWidth,
  10103. InClassInitStyle InitStyle,
  10104. AccessSpecifier AS) {
  10105. IdentifierInfo *II = D.getIdentifier();
  10106. SourceLocation Loc = DeclStart;
  10107. if (II) Loc = D.getIdentifierLoc();
  10108. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10109. QualType T = TInfo->getType();
  10110. if (getLangOpts().CPlusPlus) {
  10111. CheckExtraCXXDefaultArguments(D);
  10112. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  10113. UPPC_DataMemberType)) {
  10114. D.setInvalidType();
  10115. T = Context.IntTy;
  10116. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  10117. }
  10118. }
  10119. // TR 18037 does not allow fields to be declared with address spaces.
  10120. if (T.getQualifiers().hasAddressSpace()) {
  10121. Diag(Loc, diag::err_field_with_address_space);
  10122. D.setInvalidType();
  10123. }
  10124. // OpenCL 1.2 spec, s6.9 r:
  10125. // The event type cannot be used to declare a structure or union field.
  10126. if (LangOpts.OpenCL && T->isEventT()) {
  10127. Diag(Loc, diag::err_event_t_struct_field);
  10128. D.setInvalidType();
  10129. }
  10130. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  10131. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  10132. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  10133. diag::err_invalid_thread)
  10134. << DeclSpec::getSpecifierName(TSCS);
  10135. // Check to see if this name was declared as a member previously
  10136. NamedDecl *PrevDecl = 0;
  10137. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  10138. LookupName(Previous, S);
  10139. switch (Previous.getResultKind()) {
  10140. case LookupResult::Found:
  10141. case LookupResult::FoundUnresolvedValue:
  10142. PrevDecl = Previous.getAsSingle<NamedDecl>();
  10143. break;
  10144. case LookupResult::FoundOverloaded:
  10145. PrevDecl = Previous.getRepresentativeDecl();
  10146. break;
  10147. case LookupResult::NotFound:
  10148. case LookupResult::NotFoundInCurrentInstantiation:
  10149. case LookupResult::Ambiguous:
  10150. break;
  10151. }
  10152. Previous.suppressDiagnostics();
  10153. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  10154. // Maybe we will complain about the shadowed template parameter.
  10155. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10156. // Just pretend that we didn't see the previous declaration.
  10157. PrevDecl = 0;
  10158. }
  10159. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  10160. PrevDecl = 0;
  10161. bool Mutable
  10162. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  10163. SourceLocation TSSL = D.getLocStart();
  10164. FieldDecl *NewFD
  10165. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  10166. TSSL, AS, PrevDecl, &D);
  10167. if (NewFD->isInvalidDecl())
  10168. Record->setInvalidDecl();
  10169. if (D.getDeclSpec().isModulePrivateSpecified())
  10170. NewFD->setModulePrivate();
  10171. if (NewFD->isInvalidDecl() && PrevDecl) {
  10172. // Don't introduce NewFD into scope; there's already something
  10173. // with the same name in the same scope.
  10174. } else if (II) {
  10175. PushOnScopeChains(NewFD, S);
  10176. } else
  10177. Record->addDecl(NewFD);
  10178. return NewFD;
  10179. }
  10180. /// \brief Build a new FieldDecl and check its well-formedness.
  10181. ///
  10182. /// This routine builds a new FieldDecl given the fields name, type,
  10183. /// record, etc. \p PrevDecl should refer to any previous declaration
  10184. /// with the same name and in the same scope as the field to be
  10185. /// created.
  10186. ///
  10187. /// \returns a new FieldDecl.
  10188. ///
  10189. /// \todo The Declarator argument is a hack. It will be removed once
  10190. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  10191. TypeSourceInfo *TInfo,
  10192. RecordDecl *Record, SourceLocation Loc,
  10193. bool Mutable, Expr *BitWidth,
  10194. InClassInitStyle InitStyle,
  10195. SourceLocation TSSL,
  10196. AccessSpecifier AS, NamedDecl *PrevDecl,
  10197. Declarator *D) {
  10198. IdentifierInfo *II = Name.getAsIdentifierInfo();
  10199. bool InvalidDecl = false;
  10200. if (D) InvalidDecl = D->isInvalidType();
  10201. // If we receive a broken type, recover by assuming 'int' and
  10202. // marking this declaration as invalid.
  10203. if (T.isNull()) {
  10204. InvalidDecl = true;
  10205. T = Context.IntTy;
  10206. }
  10207. QualType EltTy = Context.getBaseElementType(T);
  10208. if (!EltTy->isDependentType()) {
  10209. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  10210. // Fields of incomplete type force their record to be invalid.
  10211. Record->setInvalidDecl();
  10212. InvalidDecl = true;
  10213. } else {
  10214. NamedDecl *Def;
  10215. EltTy->isIncompleteType(&Def);
  10216. if (Def && Def->isInvalidDecl()) {
  10217. Record->setInvalidDecl();
  10218. InvalidDecl = true;
  10219. }
  10220. }
  10221. }
  10222. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  10223. if (BitWidth && getLangOpts().OpenCL) {
  10224. Diag(Loc, diag::err_opencl_bitfields);
  10225. InvalidDecl = true;
  10226. }
  10227. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  10228. // than a variably modified type.
  10229. if (!InvalidDecl && T->isVariablyModifiedType()) {
  10230. bool SizeIsNegative;
  10231. llvm::APSInt Oversized;
  10232. TypeSourceInfo *FixedTInfo =
  10233. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  10234. SizeIsNegative,
  10235. Oversized);
  10236. if (FixedTInfo) {
  10237. Diag(Loc, diag::warn_illegal_constant_array_size);
  10238. TInfo = FixedTInfo;
  10239. T = FixedTInfo->getType();
  10240. } else {
  10241. if (SizeIsNegative)
  10242. Diag(Loc, diag::err_typecheck_negative_array_size);
  10243. else if (Oversized.getBoolValue())
  10244. Diag(Loc, diag::err_array_too_large)
  10245. << Oversized.toString(10);
  10246. else
  10247. Diag(Loc, diag::err_typecheck_field_variable_size);
  10248. InvalidDecl = true;
  10249. }
  10250. }
  10251. // Fields can not have abstract class types
  10252. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  10253. diag::err_abstract_type_in_decl,
  10254. AbstractFieldType))
  10255. InvalidDecl = true;
  10256. bool ZeroWidth = false;
  10257. // If this is declared as a bit-field, check the bit-field.
  10258. if (!InvalidDecl && BitWidth) {
  10259. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  10260. &ZeroWidth).take();
  10261. if (!BitWidth) {
  10262. InvalidDecl = true;
  10263. BitWidth = 0;
  10264. ZeroWidth = false;
  10265. }
  10266. }
  10267. // Check that 'mutable' is consistent with the type of the declaration.
  10268. if (!InvalidDecl && Mutable) {
  10269. unsigned DiagID = 0;
  10270. if (T->isReferenceType())
  10271. DiagID = diag::err_mutable_reference;
  10272. else if (T.isConstQualified())
  10273. DiagID = diag::err_mutable_const;
  10274. if (DiagID) {
  10275. SourceLocation ErrLoc = Loc;
  10276. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  10277. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  10278. Diag(ErrLoc, DiagID);
  10279. Mutable = false;
  10280. InvalidDecl = true;
  10281. }
  10282. }
  10283. // C++11 [class.union]p8 (DR1460):
  10284. // At most one variant member of a union may have a
  10285. // brace-or-equal-initializer.
  10286. if (InitStyle != ICIS_NoInit)
  10287. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  10288. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  10289. BitWidth, Mutable, InitStyle);
  10290. if (InvalidDecl)
  10291. NewFD->setInvalidDecl();
  10292. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  10293. Diag(Loc, diag::err_duplicate_member) << II;
  10294. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10295. NewFD->setInvalidDecl();
  10296. }
  10297. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  10298. if (Record->isUnion()) {
  10299. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  10300. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  10301. if (RDecl->getDefinition()) {
  10302. // C++ [class.union]p1: An object of a class with a non-trivial
  10303. // constructor, a non-trivial copy constructor, a non-trivial
  10304. // destructor, or a non-trivial copy assignment operator
  10305. // cannot be a member of a union, nor can an array of such
  10306. // objects.
  10307. if (CheckNontrivialField(NewFD))
  10308. NewFD->setInvalidDecl();
  10309. }
  10310. }
  10311. // C++ [class.union]p1: If a union contains a member of reference type,
  10312. // the program is ill-formed, except when compiling with MSVC extensions
  10313. // enabled.
  10314. if (EltTy->isReferenceType()) {
  10315. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  10316. diag::ext_union_member_of_reference_type :
  10317. diag::err_union_member_of_reference_type)
  10318. << NewFD->getDeclName() << EltTy;
  10319. if (!getLangOpts().MicrosoftExt)
  10320. NewFD->setInvalidDecl();
  10321. }
  10322. }
  10323. }
  10324. // FIXME: We need to pass in the attributes given an AST
  10325. // representation, not a parser representation.
  10326. if (D) {
  10327. // FIXME: The current scope is almost... but not entirely... correct here.
  10328. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  10329. if (NewFD->hasAttrs())
  10330. CheckAlignasUnderalignment(NewFD);
  10331. }
  10332. // In auto-retain/release, infer strong retension for fields of
  10333. // retainable type.
  10334. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  10335. NewFD->setInvalidDecl();
  10336. if (T.isObjCGCWeak())
  10337. Diag(Loc, diag::warn_attribute_weak_on_field);
  10338. NewFD->setAccess(AS);
  10339. return NewFD;
  10340. }
  10341. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  10342. assert(FD);
  10343. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  10344. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  10345. return false;
  10346. QualType EltTy = Context.getBaseElementType(FD->getType());
  10347. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  10348. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  10349. if (RDecl->getDefinition()) {
  10350. // We check for copy constructors before constructors
  10351. // because otherwise we'll never get complaints about
  10352. // copy constructors.
  10353. CXXSpecialMember member = CXXInvalid;
  10354. // We're required to check for any non-trivial constructors. Since the
  10355. // implicit default constructor is suppressed if there are any
  10356. // user-declared constructors, we just need to check that there is a
  10357. // trivial default constructor and a trivial copy constructor. (We don't
  10358. // worry about move constructors here, since this is a C++98 check.)
  10359. if (RDecl->hasNonTrivialCopyConstructor())
  10360. member = CXXCopyConstructor;
  10361. else if (!RDecl->hasTrivialDefaultConstructor())
  10362. member = CXXDefaultConstructor;
  10363. else if (RDecl->hasNonTrivialCopyAssignment())
  10364. member = CXXCopyAssignment;
  10365. else if (RDecl->hasNonTrivialDestructor())
  10366. member = CXXDestructor;
  10367. if (member != CXXInvalid) {
  10368. if (!getLangOpts().CPlusPlus11 &&
  10369. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  10370. // Objective-C++ ARC: it is an error to have a non-trivial field of
  10371. // a union. However, system headers in Objective-C programs
  10372. // occasionally have Objective-C lifetime objects within unions,
  10373. // and rather than cause the program to fail, we make those
  10374. // members unavailable.
  10375. SourceLocation Loc = FD->getLocation();
  10376. if (getSourceManager().isInSystemHeader(Loc)) {
  10377. if (!FD->hasAttr<UnavailableAttr>())
  10378. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  10379. "this system field has retaining ownership",
  10380. Loc));
  10381. return false;
  10382. }
  10383. }
  10384. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  10385. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  10386. diag::err_illegal_union_or_anon_struct_member)
  10387. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  10388. DiagnoseNontrivial(RDecl, member);
  10389. return !getLangOpts().CPlusPlus11;
  10390. }
  10391. }
  10392. }
  10393. return false;
  10394. }
  10395. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  10396. /// AST enum value.
  10397. static ObjCIvarDecl::AccessControl
  10398. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  10399. switch (ivarVisibility) {
  10400. default: llvm_unreachable("Unknown visitibility kind");
  10401. case tok::objc_private: return ObjCIvarDecl::Private;
  10402. case tok::objc_public: return ObjCIvarDecl::Public;
  10403. case tok::objc_protected: return ObjCIvarDecl::Protected;
  10404. case tok::objc_package: return ObjCIvarDecl::Package;
  10405. }
  10406. }
  10407. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  10408. /// in order to create an IvarDecl object for it.
  10409. Decl *Sema::ActOnIvar(Scope *S,
  10410. SourceLocation DeclStart,
  10411. Declarator &D, Expr *BitfieldWidth,
  10412. tok::ObjCKeywordKind Visibility) {
  10413. IdentifierInfo *II = D.getIdentifier();
  10414. Expr *BitWidth = (Expr*)BitfieldWidth;
  10415. SourceLocation Loc = DeclStart;
  10416. if (II) Loc = D.getIdentifierLoc();
  10417. // FIXME: Unnamed fields can be handled in various different ways, for
  10418. // example, unnamed unions inject all members into the struct namespace!
  10419. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10420. QualType T = TInfo->getType();
  10421. if (BitWidth) {
  10422. // 6.7.2.1p3, 6.7.2.1p4
  10423. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
  10424. if (!BitWidth)
  10425. D.setInvalidType();
  10426. } else {
  10427. // Not a bitfield.
  10428. // validate II.
  10429. }
  10430. if (T->isReferenceType()) {
  10431. Diag(Loc, diag::err_ivar_reference_type);
  10432. D.setInvalidType();
  10433. }
  10434. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  10435. // than a variably modified type.
  10436. else if (T->isVariablyModifiedType()) {
  10437. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  10438. D.setInvalidType();
  10439. }
  10440. // Get the visibility (access control) for this ivar.
  10441. ObjCIvarDecl::AccessControl ac =
  10442. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  10443. : ObjCIvarDecl::None;
  10444. // Must set ivar's DeclContext to its enclosing interface.
  10445. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  10446. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  10447. return 0;
  10448. ObjCContainerDecl *EnclosingContext;
  10449. if (ObjCImplementationDecl *IMPDecl =
  10450. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  10451. if (LangOpts.ObjCRuntime.isFragile()) {
  10452. // Case of ivar declared in an implementation. Context is that of its class.
  10453. EnclosingContext = IMPDecl->getClassInterface();
  10454. assert(EnclosingContext && "Implementation has no class interface!");
  10455. }
  10456. else
  10457. EnclosingContext = EnclosingDecl;
  10458. } else {
  10459. if (ObjCCategoryDecl *CDecl =
  10460. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  10461. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  10462. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  10463. return 0;
  10464. }
  10465. }
  10466. EnclosingContext = EnclosingDecl;
  10467. }
  10468. // Construct the decl.
  10469. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  10470. DeclStart, Loc, II, T,
  10471. TInfo, ac, (Expr *)BitfieldWidth);
  10472. if (II) {
  10473. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  10474. ForRedeclaration);
  10475. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  10476. && !isa<TagDecl>(PrevDecl)) {
  10477. Diag(Loc, diag::err_duplicate_member) << II;
  10478. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10479. NewID->setInvalidDecl();
  10480. }
  10481. }
  10482. // Process attributes attached to the ivar.
  10483. ProcessDeclAttributes(S, NewID, D);
  10484. if (D.isInvalidType())
  10485. NewID->setInvalidDecl();
  10486. // In ARC, infer 'retaining' for ivars of retainable type.
  10487. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  10488. NewID->setInvalidDecl();
  10489. if (D.getDeclSpec().isModulePrivateSpecified())
  10490. NewID->setModulePrivate();
  10491. if (II) {
  10492. // FIXME: When interfaces are DeclContexts, we'll need to add
  10493. // these to the interface.
  10494. S->AddDecl(NewID);
  10495. IdResolver.AddDecl(NewID);
  10496. }
  10497. if (LangOpts.ObjCRuntime.isNonFragile() &&
  10498. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  10499. Diag(Loc, diag::warn_ivars_in_interface);
  10500. return NewID;
  10501. }
  10502. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  10503. /// class and class extensions. For every class \@interface and class
  10504. /// extension \@interface, if the last ivar is a bitfield of any type,
  10505. /// then add an implicit `char :0` ivar to the end of that interface.
  10506. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  10507. SmallVectorImpl<Decl *> &AllIvarDecls) {
  10508. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  10509. return;
  10510. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  10511. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  10512. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  10513. return;
  10514. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  10515. if (!ID) {
  10516. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  10517. if (!CD->IsClassExtension())
  10518. return;
  10519. }
  10520. // No need to add this to end of @implementation.
  10521. else
  10522. return;
  10523. }
  10524. // All conditions are met. Add a new bitfield to the tail end of ivars.
  10525. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  10526. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  10527. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  10528. DeclLoc, DeclLoc, 0,
  10529. Context.CharTy,
  10530. Context.getTrivialTypeSourceInfo(Context.CharTy,
  10531. DeclLoc),
  10532. ObjCIvarDecl::Private, BW,
  10533. true);
  10534. AllIvarDecls.push_back(Ivar);
  10535. }
  10536. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  10537. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  10538. SourceLocation RBrac, AttributeList *Attr) {
  10539. assert(EnclosingDecl && "missing record or interface decl");
  10540. // If this is an Objective-C @implementation or category and we have
  10541. // new fields here we should reset the layout of the interface since
  10542. // it will now change.
  10543. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  10544. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  10545. switch (DC->getKind()) {
  10546. default: break;
  10547. case Decl::ObjCCategory:
  10548. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  10549. break;
  10550. case Decl::ObjCImplementation:
  10551. Context.
  10552. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  10553. break;
  10554. }
  10555. }
  10556. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  10557. // Start counting up the number of named members; make sure to include
  10558. // members of anonymous structs and unions in the total.
  10559. unsigned NumNamedMembers = 0;
  10560. if (Record) {
  10561. for (const auto *I : Record->decls()) {
  10562. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  10563. if (IFD->getDeclName())
  10564. ++NumNamedMembers;
  10565. }
  10566. }
  10567. // Verify that all the fields are okay.
  10568. SmallVector<FieldDecl*, 32> RecFields;
  10569. bool ARCErrReported = false;
  10570. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  10571. i != end; ++i) {
  10572. FieldDecl *FD = cast<FieldDecl>(*i);
  10573. // Get the type for the field.
  10574. const Type *FDTy = FD->getType().getTypePtr();
  10575. if (!FD->isAnonymousStructOrUnion()) {
  10576. // Remember all fields written by the user.
  10577. RecFields.push_back(FD);
  10578. }
  10579. // If the field is already invalid for some reason, don't emit more
  10580. // diagnostics about it.
  10581. if (FD->isInvalidDecl()) {
  10582. EnclosingDecl->setInvalidDecl();
  10583. continue;
  10584. }
  10585. // C99 6.7.2.1p2:
  10586. // A structure or union shall not contain a member with
  10587. // incomplete or function type (hence, a structure shall not
  10588. // contain an instance of itself, but may contain a pointer to
  10589. // an instance of itself), except that the last member of a
  10590. // structure with more than one named member may have incomplete
  10591. // array type; such a structure (and any union containing,
  10592. // possibly recursively, a member that is such a structure)
  10593. // shall not be a member of a structure or an element of an
  10594. // array.
  10595. if (FDTy->isFunctionType()) {
  10596. // Field declared as a function.
  10597. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  10598. << FD->getDeclName();
  10599. FD->setInvalidDecl();
  10600. EnclosingDecl->setInvalidDecl();
  10601. continue;
  10602. } else if (FDTy->isIncompleteArrayType() && Record &&
  10603. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  10604. ((getLangOpts().MicrosoftExt ||
  10605. getLangOpts().CPlusPlus) &&
  10606. (i + 1 == Fields.end() || Record->isUnion())))) {
  10607. // Flexible array member.
  10608. // Microsoft and g++ is more permissive regarding flexible array.
  10609. // It will accept flexible array in union and also
  10610. // as the sole element of a struct/class.
  10611. unsigned DiagID = 0;
  10612. if (Record->isUnion())
  10613. DiagID = getLangOpts().MicrosoftExt
  10614. ? diag::ext_flexible_array_union_ms
  10615. : getLangOpts().CPlusPlus
  10616. ? diag::ext_flexible_array_union_gnu
  10617. : diag::err_flexible_array_union;
  10618. else if (Fields.size() == 1)
  10619. DiagID = getLangOpts().MicrosoftExt
  10620. ? diag::ext_flexible_array_empty_aggregate_ms
  10621. : getLangOpts().CPlusPlus
  10622. ? diag::ext_flexible_array_empty_aggregate_gnu
  10623. : NumNamedMembers < 1
  10624. ? diag::err_flexible_array_empty_aggregate
  10625. : 0;
  10626. if (DiagID)
  10627. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  10628. << Record->getTagKind();
  10629. // While the layout of types that contain virtual bases is not specified
  10630. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  10631. // virtual bases after the derived members. This would make a flexible
  10632. // array member declared at the end of an object not adjacent to the end
  10633. // of the type.
  10634. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  10635. if (RD->getNumVBases() != 0)
  10636. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  10637. << FD->getDeclName() << Record->getTagKind();
  10638. if (!getLangOpts().C99)
  10639. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  10640. << FD->getDeclName() << Record->getTagKind();
  10641. // If the element type has a non-trivial destructor, we would not
  10642. // implicitly destroy the elements, so disallow it for now.
  10643. //
  10644. // FIXME: GCC allows this. We should probably either implicitly delete
  10645. // the destructor of the containing class, or just allow this.
  10646. QualType BaseElem = Context.getBaseElementType(FD->getType());
  10647. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  10648. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  10649. << FD->getDeclName() << FD->getType();
  10650. FD->setInvalidDecl();
  10651. EnclosingDecl->setInvalidDecl();
  10652. continue;
  10653. }
  10654. // Okay, we have a legal flexible array member at the end of the struct.
  10655. if (Record)
  10656. Record->setHasFlexibleArrayMember(true);
  10657. } else if (!FDTy->isDependentType() &&
  10658. RequireCompleteType(FD->getLocation(), FD->getType(),
  10659. diag::err_field_incomplete)) {
  10660. // Incomplete type
  10661. FD->setInvalidDecl();
  10662. EnclosingDecl->setInvalidDecl();
  10663. continue;
  10664. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  10665. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  10666. // If this is a member of a union, then entire union becomes "flexible".
  10667. if (Record && Record->isUnion()) {
  10668. Record->setHasFlexibleArrayMember(true);
  10669. } else {
  10670. // If this is a struct/class and this is not the last element, reject
  10671. // it. Note that GCC supports variable sized arrays in the middle of
  10672. // structures.
  10673. if (i + 1 != Fields.end())
  10674. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  10675. << FD->getDeclName() << FD->getType();
  10676. else {
  10677. // We support flexible arrays at the end of structs in
  10678. // other structs as an extension.
  10679. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  10680. << FD->getDeclName();
  10681. if (Record)
  10682. Record->setHasFlexibleArrayMember(true);
  10683. }
  10684. }
  10685. }
  10686. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  10687. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  10688. diag::err_abstract_type_in_decl,
  10689. AbstractIvarType)) {
  10690. // Ivars can not have abstract class types
  10691. FD->setInvalidDecl();
  10692. }
  10693. if (Record && FDTTy->getDecl()->hasObjectMember())
  10694. Record->setHasObjectMember(true);
  10695. if (Record && FDTTy->getDecl()->hasVolatileMember())
  10696. Record->setHasVolatileMember(true);
  10697. } else if (FDTy->isObjCObjectType()) {
  10698. /// A field cannot be an Objective-c object
  10699. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  10700. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  10701. QualType T = Context.getObjCObjectPointerType(FD->getType());
  10702. FD->setType(T);
  10703. } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
  10704. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  10705. // It's an error in ARC if a field has lifetime.
  10706. // We don't want to report this in a system header, though,
  10707. // so we just make the field unavailable.
  10708. // FIXME: that's really not sufficient; we need to make the type
  10709. // itself invalid to, say, initialize or copy.
  10710. QualType T = FD->getType();
  10711. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  10712. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  10713. SourceLocation loc = FD->getLocation();
  10714. if (getSourceManager().isInSystemHeader(loc)) {
  10715. if (!FD->hasAttr<UnavailableAttr>()) {
  10716. FD->addAttr(UnavailableAttr::CreateImplicit(Context,
  10717. "this system field has retaining ownership",
  10718. loc));
  10719. }
  10720. } else {
  10721. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  10722. << T->isBlockPointerType() << Record->getTagKind();
  10723. }
  10724. ARCErrReported = true;
  10725. }
  10726. } else if (getLangOpts().ObjC1 &&
  10727. getLangOpts().getGC() != LangOptions::NonGC &&
  10728. Record && !Record->hasObjectMember()) {
  10729. if (FD->getType()->isObjCObjectPointerType() ||
  10730. FD->getType().isObjCGCStrong())
  10731. Record->setHasObjectMember(true);
  10732. else if (Context.getAsArrayType(FD->getType())) {
  10733. QualType BaseType = Context.getBaseElementType(FD->getType());
  10734. if (BaseType->isRecordType() &&
  10735. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  10736. Record->setHasObjectMember(true);
  10737. else if (BaseType->isObjCObjectPointerType() ||
  10738. BaseType.isObjCGCStrong())
  10739. Record->setHasObjectMember(true);
  10740. }
  10741. }
  10742. if (Record && FD->getType().isVolatileQualified())
  10743. Record->setHasVolatileMember(true);
  10744. // Keep track of the number of named members.
  10745. if (FD->getIdentifier())
  10746. ++NumNamedMembers;
  10747. }
  10748. // Okay, we successfully defined 'Record'.
  10749. if (Record) {
  10750. bool Completed = false;
  10751. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  10752. if (!CXXRecord->isInvalidDecl()) {
  10753. // Set access bits correctly on the directly-declared conversions.
  10754. for (CXXRecordDecl::conversion_iterator
  10755. I = CXXRecord->conversion_begin(),
  10756. E = CXXRecord->conversion_end(); I != E; ++I)
  10757. I.setAccess((*I)->getAccess());
  10758. if (!CXXRecord->isDependentType()) {
  10759. if (CXXRecord->hasUserDeclaredDestructor()) {
  10760. // Adjust user-defined destructor exception spec.
  10761. if (getLangOpts().CPlusPlus11)
  10762. AdjustDestructorExceptionSpec(CXXRecord,
  10763. CXXRecord->getDestructor());
  10764. }
  10765. // Add any implicitly-declared members to this class.
  10766. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  10767. // If we have virtual base classes, we may end up finding multiple
  10768. // final overriders for a given virtual function. Check for this
  10769. // problem now.
  10770. if (CXXRecord->getNumVBases()) {
  10771. CXXFinalOverriderMap FinalOverriders;
  10772. CXXRecord->getFinalOverriders(FinalOverriders);
  10773. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  10774. MEnd = FinalOverriders.end();
  10775. M != MEnd; ++M) {
  10776. for (OverridingMethods::iterator SO = M->second.begin(),
  10777. SOEnd = M->second.end();
  10778. SO != SOEnd; ++SO) {
  10779. assert(SO->second.size() > 0 &&
  10780. "Virtual function without overridding functions?");
  10781. if (SO->second.size() == 1)
  10782. continue;
  10783. // C++ [class.virtual]p2:
  10784. // In a derived class, if a virtual member function of a base
  10785. // class subobject has more than one final overrider the
  10786. // program is ill-formed.
  10787. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  10788. << (const NamedDecl *)M->first << Record;
  10789. Diag(M->first->getLocation(),
  10790. diag::note_overridden_virtual_function);
  10791. for (OverridingMethods::overriding_iterator
  10792. OM = SO->second.begin(),
  10793. OMEnd = SO->second.end();
  10794. OM != OMEnd; ++OM)
  10795. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  10796. << (const NamedDecl *)M->first << OM->Method->getParent();
  10797. Record->setInvalidDecl();
  10798. }
  10799. }
  10800. CXXRecord->completeDefinition(&FinalOverriders);
  10801. Completed = true;
  10802. }
  10803. }
  10804. }
  10805. }
  10806. if (!Completed)
  10807. Record->completeDefinition();
  10808. if (Record->hasAttrs()) {
  10809. CheckAlignasUnderalignment(Record);
  10810. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  10811. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  10812. IA->getRange(), IA->getBestCase(),
  10813. IA->getSemanticSpelling());
  10814. }
  10815. // Check if the structure/union declaration is a type that can have zero
  10816. // size in C. For C this is a language extension, for C++ it may cause
  10817. // compatibility problems.
  10818. bool CheckForZeroSize;
  10819. if (!getLangOpts().CPlusPlus) {
  10820. CheckForZeroSize = true;
  10821. } else {
  10822. // For C++ filter out types that cannot be referenced in C code.
  10823. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  10824. CheckForZeroSize =
  10825. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  10826. !CXXRecord->isDependentType() &&
  10827. CXXRecord->isCLike();
  10828. }
  10829. if (CheckForZeroSize) {
  10830. bool ZeroSize = true;
  10831. bool IsEmpty = true;
  10832. unsigned NonBitFields = 0;
  10833. for (RecordDecl::field_iterator I = Record->field_begin(),
  10834. E = Record->field_end();
  10835. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  10836. IsEmpty = false;
  10837. if (I->isUnnamedBitfield()) {
  10838. if (I->getBitWidthValue(Context) > 0)
  10839. ZeroSize = false;
  10840. } else {
  10841. ++NonBitFields;
  10842. QualType FieldType = I->getType();
  10843. if (FieldType->isIncompleteType() ||
  10844. !Context.getTypeSizeInChars(FieldType).isZero())
  10845. ZeroSize = false;
  10846. }
  10847. }
  10848. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  10849. // allowed in C++, but warn if its declaration is inside
  10850. // extern "C" block.
  10851. if (ZeroSize) {
  10852. Diag(RecLoc, getLangOpts().CPlusPlus ?
  10853. diag::warn_zero_size_struct_union_in_extern_c :
  10854. diag::warn_zero_size_struct_union_compat)
  10855. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  10856. }
  10857. // Structs without named members are extension in C (C99 6.7.2.1p7),
  10858. // but are accepted by GCC.
  10859. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  10860. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  10861. diag::ext_no_named_members_in_struct_union)
  10862. << Record->isUnion();
  10863. }
  10864. }
  10865. } else {
  10866. ObjCIvarDecl **ClsFields =
  10867. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  10868. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  10869. ID->setEndOfDefinitionLoc(RBrac);
  10870. // Add ivar's to class's DeclContext.
  10871. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  10872. ClsFields[i]->setLexicalDeclContext(ID);
  10873. ID->addDecl(ClsFields[i]);
  10874. }
  10875. // Must enforce the rule that ivars in the base classes may not be
  10876. // duplicates.
  10877. if (ID->getSuperClass())
  10878. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  10879. } else if (ObjCImplementationDecl *IMPDecl =
  10880. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  10881. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  10882. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  10883. // Ivar declared in @implementation never belongs to the implementation.
  10884. // Only it is in implementation's lexical context.
  10885. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  10886. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  10887. IMPDecl->setIvarLBraceLoc(LBrac);
  10888. IMPDecl->setIvarRBraceLoc(RBrac);
  10889. } else if (ObjCCategoryDecl *CDecl =
  10890. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  10891. // case of ivars in class extension; all other cases have been
  10892. // reported as errors elsewhere.
  10893. // FIXME. Class extension does not have a LocEnd field.
  10894. // CDecl->setLocEnd(RBrac);
  10895. // Add ivar's to class extension's DeclContext.
  10896. // Diagnose redeclaration of private ivars.
  10897. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  10898. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  10899. if (IDecl) {
  10900. if (const ObjCIvarDecl *ClsIvar =
  10901. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  10902. Diag(ClsFields[i]->getLocation(),
  10903. diag::err_duplicate_ivar_declaration);
  10904. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  10905. continue;
  10906. }
  10907. for (const auto *Ext : IDecl->known_extensions()) {
  10908. if (const ObjCIvarDecl *ClsExtIvar
  10909. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  10910. Diag(ClsFields[i]->getLocation(),
  10911. diag::err_duplicate_ivar_declaration);
  10912. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  10913. continue;
  10914. }
  10915. }
  10916. }
  10917. ClsFields[i]->setLexicalDeclContext(CDecl);
  10918. CDecl->addDecl(ClsFields[i]);
  10919. }
  10920. CDecl->setIvarLBraceLoc(LBrac);
  10921. CDecl->setIvarRBraceLoc(RBrac);
  10922. }
  10923. }
  10924. if (Attr)
  10925. ProcessDeclAttributeList(S, Record, Attr);
  10926. }
  10927. /// \brief Determine whether the given integral value is representable within
  10928. /// the given type T.
  10929. static bool isRepresentableIntegerValue(ASTContext &Context,
  10930. llvm::APSInt &Value,
  10931. QualType T) {
  10932. assert(T->isIntegralType(Context) && "Integral type required!");
  10933. unsigned BitWidth = Context.getIntWidth(T);
  10934. if (Value.isUnsigned() || Value.isNonNegative()) {
  10935. if (T->isSignedIntegerOrEnumerationType())
  10936. --BitWidth;
  10937. return Value.getActiveBits() <= BitWidth;
  10938. }
  10939. return Value.getMinSignedBits() <= BitWidth;
  10940. }
  10941. // \brief Given an integral type, return the next larger integral type
  10942. // (or a NULL type of no such type exists).
  10943. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  10944. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  10945. // enum checking below.
  10946. assert(T->isIntegralType(Context) && "Integral type required!");
  10947. const unsigned NumTypes = 4;
  10948. QualType SignedIntegralTypes[NumTypes] = {
  10949. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  10950. };
  10951. QualType UnsignedIntegralTypes[NumTypes] = {
  10952. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  10953. Context.UnsignedLongLongTy
  10954. };
  10955. unsigned BitWidth = Context.getTypeSize(T);
  10956. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  10957. : UnsignedIntegralTypes;
  10958. for (unsigned I = 0; I != NumTypes; ++I)
  10959. if (Context.getTypeSize(Types[I]) > BitWidth)
  10960. return Types[I];
  10961. return QualType();
  10962. }
  10963. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  10964. EnumConstantDecl *LastEnumConst,
  10965. SourceLocation IdLoc,
  10966. IdentifierInfo *Id,
  10967. Expr *Val) {
  10968. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  10969. llvm::APSInt EnumVal(IntWidth);
  10970. QualType EltTy;
  10971. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  10972. Val = 0;
  10973. if (Val)
  10974. Val = DefaultLvalueConversion(Val).take();
  10975. if (Val) {
  10976. if (Enum->isDependentType() || Val->isTypeDependent())
  10977. EltTy = Context.DependentTy;
  10978. else {
  10979. SourceLocation ExpLoc;
  10980. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  10981. !getLangOpts().MSVCCompat) {
  10982. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  10983. // constant-expression in the enumerator-definition shall be a converted
  10984. // constant expression of the underlying type.
  10985. EltTy = Enum->getIntegerType();
  10986. ExprResult Converted =
  10987. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  10988. CCEK_Enumerator);
  10989. if (Converted.isInvalid())
  10990. Val = 0;
  10991. else
  10992. Val = Converted.take();
  10993. } else if (!Val->isValueDependent() &&
  10994. !(Val = VerifyIntegerConstantExpression(Val,
  10995. &EnumVal).take())) {
  10996. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  10997. } else {
  10998. if (Enum->isFixed()) {
  10999. EltTy = Enum->getIntegerType();
  11000. // In Obj-C and Microsoft mode, require the enumeration value to be
  11001. // representable in the underlying type of the enumeration. In C++11,
  11002. // we perform a non-narrowing conversion as part of converted constant
  11003. // expression checking.
  11004. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  11005. if (getLangOpts().MSVCCompat) {
  11006. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  11007. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  11008. } else
  11009. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  11010. } else
  11011. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  11012. } else if (getLangOpts().CPlusPlus) {
  11013. // C++11 [dcl.enum]p5:
  11014. // If the underlying type is not fixed, the type of each enumerator
  11015. // is the type of its initializing value:
  11016. // - If an initializer is specified for an enumerator, the
  11017. // initializing value has the same type as the expression.
  11018. EltTy = Val->getType();
  11019. } else {
  11020. // C99 6.7.2.2p2:
  11021. // The expression that defines the value of an enumeration constant
  11022. // shall be an integer constant expression that has a value
  11023. // representable as an int.
  11024. // Complain if the value is not representable in an int.
  11025. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  11026. Diag(IdLoc, diag::ext_enum_value_not_int)
  11027. << EnumVal.toString(10) << Val->getSourceRange()
  11028. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  11029. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  11030. // Force the type of the expression to 'int'.
  11031. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
  11032. }
  11033. EltTy = Val->getType();
  11034. }
  11035. }
  11036. }
  11037. }
  11038. if (!Val) {
  11039. if (Enum->isDependentType())
  11040. EltTy = Context.DependentTy;
  11041. else if (!LastEnumConst) {
  11042. // C++0x [dcl.enum]p5:
  11043. // If the underlying type is not fixed, the type of each enumerator
  11044. // is the type of its initializing value:
  11045. // - If no initializer is specified for the first enumerator, the
  11046. // initializing value has an unspecified integral type.
  11047. //
  11048. // GCC uses 'int' for its unspecified integral type, as does
  11049. // C99 6.7.2.2p3.
  11050. if (Enum->isFixed()) {
  11051. EltTy = Enum->getIntegerType();
  11052. }
  11053. else {
  11054. EltTy = Context.IntTy;
  11055. }
  11056. } else {
  11057. // Assign the last value + 1.
  11058. EnumVal = LastEnumConst->getInitVal();
  11059. ++EnumVal;
  11060. EltTy = LastEnumConst->getType();
  11061. // Check for overflow on increment.
  11062. if (EnumVal < LastEnumConst->getInitVal()) {
  11063. // C++0x [dcl.enum]p5:
  11064. // If the underlying type is not fixed, the type of each enumerator
  11065. // is the type of its initializing value:
  11066. //
  11067. // - Otherwise the type of the initializing value is the same as
  11068. // the type of the initializing value of the preceding enumerator
  11069. // unless the incremented value is not representable in that type,
  11070. // in which case the type is an unspecified integral type
  11071. // sufficient to contain the incremented value. If no such type
  11072. // exists, the program is ill-formed.
  11073. QualType T = getNextLargerIntegralType(Context, EltTy);
  11074. if (T.isNull() || Enum->isFixed()) {
  11075. // There is no integral type larger enough to represent this
  11076. // value. Complain, then allow the value to wrap around.
  11077. EnumVal = LastEnumConst->getInitVal();
  11078. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  11079. ++EnumVal;
  11080. if (Enum->isFixed())
  11081. // When the underlying type is fixed, this is ill-formed.
  11082. Diag(IdLoc, diag::err_enumerator_wrapped)
  11083. << EnumVal.toString(10)
  11084. << EltTy;
  11085. else
  11086. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  11087. << EnumVal.toString(10);
  11088. } else {
  11089. EltTy = T;
  11090. }
  11091. // Retrieve the last enumerator's value, extent that type to the
  11092. // type that is supposed to be large enough to represent the incremented
  11093. // value, then increment.
  11094. EnumVal = LastEnumConst->getInitVal();
  11095. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  11096. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  11097. ++EnumVal;
  11098. // If we're not in C++, diagnose the overflow of enumerator values,
  11099. // which in C99 means that the enumerator value is not representable in
  11100. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  11101. // permits enumerator values that are representable in some larger
  11102. // integral type.
  11103. if (!getLangOpts().CPlusPlus && !T.isNull())
  11104. Diag(IdLoc, diag::warn_enum_value_overflow);
  11105. } else if (!getLangOpts().CPlusPlus &&
  11106. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  11107. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  11108. Diag(IdLoc, diag::ext_enum_value_not_int)
  11109. << EnumVal.toString(10) << 1;
  11110. }
  11111. }
  11112. }
  11113. if (!EltTy->isDependentType()) {
  11114. // Make the enumerator value match the signedness and size of the
  11115. // enumerator's type.
  11116. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  11117. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  11118. }
  11119. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  11120. Val, EnumVal);
  11121. }
  11122. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  11123. SourceLocation IdLoc, IdentifierInfo *Id,
  11124. AttributeList *Attr,
  11125. SourceLocation EqualLoc, Expr *Val) {
  11126. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  11127. EnumConstantDecl *LastEnumConst =
  11128. cast_or_null<EnumConstantDecl>(lastEnumConst);
  11129. // The scope passed in may not be a decl scope. Zip up the scope tree until
  11130. // we find one that is.
  11131. S = getNonFieldDeclScope(S);
  11132. // Verify that there isn't already something declared with this name in this
  11133. // scope.
  11134. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  11135. ForRedeclaration);
  11136. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  11137. // Maybe we will complain about the shadowed template parameter.
  11138. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  11139. // Just pretend that we didn't see the previous declaration.
  11140. PrevDecl = 0;
  11141. }
  11142. if (PrevDecl) {
  11143. // When in C++, we may get a TagDecl with the same name; in this case the
  11144. // enum constant will 'hide' the tag.
  11145. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  11146. "Received TagDecl when not in C++!");
  11147. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  11148. if (isa<EnumConstantDecl>(PrevDecl))
  11149. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  11150. else
  11151. Diag(IdLoc, diag::err_redefinition) << Id;
  11152. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  11153. return 0;
  11154. }
  11155. }
  11156. // C++ [class.mem]p15:
  11157. // If T is the name of a class, then each of the following shall have a name
  11158. // different from T:
  11159. // - every enumerator of every member of class T that is an unscoped
  11160. // enumerated type
  11161. if (CXXRecordDecl *Record
  11162. = dyn_cast<CXXRecordDecl>(
  11163. TheEnumDecl->getDeclContext()->getRedeclContext()))
  11164. if (!TheEnumDecl->isScoped() &&
  11165. Record->getIdentifier() && Record->getIdentifier() == Id)
  11166. Diag(IdLoc, diag::err_member_name_of_class) << Id;
  11167. EnumConstantDecl *New =
  11168. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  11169. if (New) {
  11170. // Process attributes.
  11171. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  11172. // Register this decl in the current scope stack.
  11173. New->setAccess(TheEnumDecl->getAccess());
  11174. PushOnScopeChains(New, S);
  11175. }
  11176. ActOnDocumentableDecl(New);
  11177. return New;
  11178. }
  11179. // Returns true when the enum initial expression does not trigger the
  11180. // duplicate enum warning. A few common cases are exempted as follows:
  11181. // Element2 = Element1
  11182. // Element2 = Element1 + 1
  11183. // Element2 = Element1 - 1
  11184. // Where Element2 and Element1 are from the same enum.
  11185. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  11186. Expr *InitExpr = ECD->getInitExpr();
  11187. if (!InitExpr)
  11188. return true;
  11189. InitExpr = InitExpr->IgnoreImpCasts();
  11190. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  11191. if (!BO->isAdditiveOp())
  11192. return true;
  11193. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  11194. if (!IL)
  11195. return true;
  11196. if (IL->getValue() != 1)
  11197. return true;
  11198. InitExpr = BO->getLHS();
  11199. }
  11200. // This checks if the elements are from the same enum.
  11201. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  11202. if (!DRE)
  11203. return true;
  11204. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  11205. if (!EnumConstant)
  11206. return true;
  11207. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  11208. Enum)
  11209. return true;
  11210. return false;
  11211. }
  11212. struct DupKey {
  11213. int64_t val;
  11214. bool isTombstoneOrEmptyKey;
  11215. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  11216. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  11217. };
  11218. static DupKey GetDupKey(const llvm::APSInt& Val) {
  11219. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  11220. false);
  11221. }
  11222. struct DenseMapInfoDupKey {
  11223. static DupKey getEmptyKey() { return DupKey(0, true); }
  11224. static DupKey getTombstoneKey() { return DupKey(1, true); }
  11225. static unsigned getHashValue(const DupKey Key) {
  11226. return (unsigned)(Key.val * 37);
  11227. }
  11228. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  11229. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  11230. LHS.val == RHS.val;
  11231. }
  11232. };
  11233. // Emits a warning when an element is implicitly set a value that
  11234. // a previous element has already been set to.
  11235. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  11236. EnumDecl *Enum,
  11237. QualType EnumType) {
  11238. if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
  11239. Enum->getLocation()) ==
  11240. DiagnosticsEngine::Ignored)
  11241. return;
  11242. // Avoid anonymous enums
  11243. if (!Enum->getIdentifier())
  11244. return;
  11245. // Only check for small enums.
  11246. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  11247. return;
  11248. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  11249. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  11250. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  11251. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  11252. ValueToVectorMap;
  11253. DuplicatesVector DupVector;
  11254. ValueToVectorMap EnumMap;
  11255. // Populate the EnumMap with all values represented by enum constants without
  11256. // an initialier.
  11257. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  11258. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  11259. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  11260. // this constant. Skip this enum since it may be ill-formed.
  11261. if (!ECD) {
  11262. return;
  11263. }
  11264. if (ECD->getInitExpr())
  11265. continue;
  11266. DupKey Key = GetDupKey(ECD->getInitVal());
  11267. DeclOrVector &Entry = EnumMap[Key];
  11268. // First time encountering this value.
  11269. if (Entry.isNull())
  11270. Entry = ECD;
  11271. }
  11272. // Create vectors for any values that has duplicates.
  11273. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  11274. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  11275. if (!ValidDuplicateEnum(ECD, Enum))
  11276. continue;
  11277. DupKey Key = GetDupKey(ECD->getInitVal());
  11278. DeclOrVector& Entry = EnumMap[Key];
  11279. if (Entry.isNull())
  11280. continue;
  11281. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  11282. // Ensure constants are different.
  11283. if (D == ECD)
  11284. continue;
  11285. // Create new vector and push values onto it.
  11286. ECDVector *Vec = new ECDVector();
  11287. Vec->push_back(D);
  11288. Vec->push_back(ECD);
  11289. // Update entry to point to the duplicates vector.
  11290. Entry = Vec;
  11291. // Store the vector somewhere we can consult later for quick emission of
  11292. // diagnostics.
  11293. DupVector.push_back(Vec);
  11294. continue;
  11295. }
  11296. ECDVector *Vec = Entry.get<ECDVector*>();
  11297. // Make sure constants are not added more than once.
  11298. if (*Vec->begin() == ECD)
  11299. continue;
  11300. Vec->push_back(ECD);
  11301. }
  11302. // Emit diagnostics.
  11303. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  11304. DupVectorEnd = DupVector.end();
  11305. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  11306. ECDVector *Vec = *DupVectorIter;
  11307. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  11308. // Emit warning for one enum constant.
  11309. ECDVector::iterator I = Vec->begin();
  11310. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  11311. << (*I)->getName() << (*I)->getInitVal().toString(10)
  11312. << (*I)->getSourceRange();
  11313. ++I;
  11314. // Emit one note for each of the remaining enum constants with
  11315. // the same value.
  11316. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  11317. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  11318. << (*I)->getName() << (*I)->getInitVal().toString(10)
  11319. << (*I)->getSourceRange();
  11320. delete Vec;
  11321. }
  11322. }
  11323. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  11324. SourceLocation RBraceLoc, Decl *EnumDeclX,
  11325. ArrayRef<Decl *> Elements,
  11326. Scope *S, AttributeList *Attr) {
  11327. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  11328. QualType EnumType = Context.getTypeDeclType(Enum);
  11329. if (Attr)
  11330. ProcessDeclAttributeList(S, Enum, Attr);
  11331. if (Enum->isDependentType()) {
  11332. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  11333. EnumConstantDecl *ECD =
  11334. cast_or_null<EnumConstantDecl>(Elements[i]);
  11335. if (!ECD) continue;
  11336. ECD->setType(EnumType);
  11337. }
  11338. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  11339. return;
  11340. }
  11341. // TODO: If the result value doesn't fit in an int, it must be a long or long
  11342. // long value. ISO C does not support this, but GCC does as an extension,
  11343. // emit a warning.
  11344. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  11345. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  11346. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  11347. // Verify that all the values are okay, compute the size of the values, and
  11348. // reverse the list.
  11349. unsigned NumNegativeBits = 0;
  11350. unsigned NumPositiveBits = 0;
  11351. // Keep track of whether all elements have type int.
  11352. bool AllElementsInt = true;
  11353. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  11354. EnumConstantDecl *ECD =
  11355. cast_or_null<EnumConstantDecl>(Elements[i]);
  11356. if (!ECD) continue; // Already issued a diagnostic.
  11357. const llvm::APSInt &InitVal = ECD->getInitVal();
  11358. // Keep track of the size of positive and negative values.
  11359. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  11360. NumPositiveBits = std::max(NumPositiveBits,
  11361. (unsigned)InitVal.getActiveBits());
  11362. else
  11363. NumNegativeBits = std::max(NumNegativeBits,
  11364. (unsigned)InitVal.getMinSignedBits());
  11365. // Keep track of whether every enum element has type int (very commmon).
  11366. if (AllElementsInt)
  11367. AllElementsInt = ECD->getType() == Context.IntTy;
  11368. }
  11369. // Figure out the type that should be used for this enum.
  11370. QualType BestType;
  11371. unsigned BestWidth;
  11372. // C++0x N3000 [conv.prom]p3:
  11373. // An rvalue of an unscoped enumeration type whose underlying
  11374. // type is not fixed can be converted to an rvalue of the first
  11375. // of the following types that can represent all the values of
  11376. // the enumeration: int, unsigned int, long int, unsigned long
  11377. // int, long long int, or unsigned long long int.
  11378. // C99 6.4.4.3p2:
  11379. // An identifier declared as an enumeration constant has type int.
  11380. // The C99 rule is modified by a gcc extension
  11381. QualType BestPromotionType;
  11382. bool Packed = Enum->hasAttr<PackedAttr>();
  11383. // -fshort-enums is the equivalent to specifying the packed attribute on all
  11384. // enum definitions.
  11385. if (LangOpts.ShortEnums)
  11386. Packed = true;
  11387. if (Enum->isFixed()) {
  11388. BestType = Enum->getIntegerType();
  11389. if (BestType->isPromotableIntegerType())
  11390. BestPromotionType = Context.getPromotedIntegerType(BestType);
  11391. else
  11392. BestPromotionType = BestType;
  11393. // We don't need to set BestWidth, because BestType is going to be the type
  11394. // of the enumerators, but we do anyway because otherwise some compilers
  11395. // warn that it might be used uninitialized.
  11396. BestWidth = CharWidth;
  11397. }
  11398. else if (NumNegativeBits) {
  11399. // If there is a negative value, figure out the smallest integer type (of
  11400. // int/long/longlong) that fits.
  11401. // If it's packed, check also if it fits a char or a short.
  11402. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  11403. BestType = Context.SignedCharTy;
  11404. BestWidth = CharWidth;
  11405. } else if (Packed && NumNegativeBits <= ShortWidth &&
  11406. NumPositiveBits < ShortWidth) {
  11407. BestType = Context.ShortTy;
  11408. BestWidth = ShortWidth;
  11409. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  11410. BestType = Context.IntTy;
  11411. BestWidth = IntWidth;
  11412. } else {
  11413. BestWidth = Context.getTargetInfo().getLongWidth();
  11414. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  11415. BestType = Context.LongTy;
  11416. } else {
  11417. BestWidth = Context.getTargetInfo().getLongLongWidth();
  11418. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  11419. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  11420. BestType = Context.LongLongTy;
  11421. }
  11422. }
  11423. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  11424. } else {
  11425. // If there is no negative value, figure out the smallest type that fits
  11426. // all of the enumerator values.
  11427. // If it's packed, check also if it fits a char or a short.
  11428. if (Packed && NumPositiveBits <= CharWidth) {
  11429. BestType = Context.UnsignedCharTy;
  11430. BestPromotionType = Context.IntTy;
  11431. BestWidth = CharWidth;
  11432. } else if (Packed && NumPositiveBits <= ShortWidth) {
  11433. BestType = Context.UnsignedShortTy;
  11434. BestPromotionType = Context.IntTy;
  11435. BestWidth = ShortWidth;
  11436. } else if (NumPositiveBits <= IntWidth) {
  11437. BestType = Context.UnsignedIntTy;
  11438. BestWidth = IntWidth;
  11439. BestPromotionType
  11440. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  11441. ? Context.UnsignedIntTy : Context.IntTy;
  11442. } else if (NumPositiveBits <=
  11443. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  11444. BestType = Context.UnsignedLongTy;
  11445. BestPromotionType
  11446. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  11447. ? Context.UnsignedLongTy : Context.LongTy;
  11448. } else {
  11449. BestWidth = Context.getTargetInfo().getLongLongWidth();
  11450. assert(NumPositiveBits <= BestWidth &&
  11451. "How could an initializer get larger than ULL?");
  11452. BestType = Context.UnsignedLongLongTy;
  11453. BestPromotionType
  11454. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  11455. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  11456. }
  11457. }
  11458. // Loop over all of the enumerator constants, changing their types to match
  11459. // the type of the enum if needed.
  11460. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  11461. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  11462. if (!ECD) continue; // Already issued a diagnostic.
  11463. // Standard C says the enumerators have int type, but we allow, as an
  11464. // extension, the enumerators to be larger than int size. If each
  11465. // enumerator value fits in an int, type it as an int, otherwise type it the
  11466. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  11467. // that X has type 'int', not 'unsigned'.
  11468. // Determine whether the value fits into an int.
  11469. llvm::APSInt InitVal = ECD->getInitVal();
  11470. // If it fits into an integer type, force it. Otherwise force it to match
  11471. // the enum decl type.
  11472. QualType NewTy;
  11473. unsigned NewWidth;
  11474. bool NewSign;
  11475. if (!getLangOpts().CPlusPlus &&
  11476. !Enum->isFixed() &&
  11477. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  11478. NewTy = Context.IntTy;
  11479. NewWidth = IntWidth;
  11480. NewSign = true;
  11481. } else if (ECD->getType() == BestType) {
  11482. // Already the right type!
  11483. if (getLangOpts().CPlusPlus)
  11484. // C++ [dcl.enum]p4: Following the closing brace of an
  11485. // enum-specifier, each enumerator has the type of its
  11486. // enumeration.
  11487. ECD->setType(EnumType);
  11488. continue;
  11489. } else {
  11490. NewTy = BestType;
  11491. NewWidth = BestWidth;
  11492. NewSign = BestType->isSignedIntegerOrEnumerationType();
  11493. }
  11494. // Adjust the APSInt value.
  11495. InitVal = InitVal.extOrTrunc(NewWidth);
  11496. InitVal.setIsSigned(NewSign);
  11497. ECD->setInitVal(InitVal);
  11498. // Adjust the Expr initializer and type.
  11499. if (ECD->getInitExpr() &&
  11500. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  11501. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  11502. CK_IntegralCast,
  11503. ECD->getInitExpr(),
  11504. /*base paths*/ 0,
  11505. VK_RValue));
  11506. if (getLangOpts().CPlusPlus)
  11507. // C++ [dcl.enum]p4: Following the closing brace of an
  11508. // enum-specifier, each enumerator has the type of its
  11509. // enumeration.
  11510. ECD->setType(EnumType);
  11511. else
  11512. ECD->setType(NewTy);
  11513. }
  11514. Enum->completeDefinition(BestType, BestPromotionType,
  11515. NumPositiveBits, NumNegativeBits);
  11516. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  11517. // Now that the enum type is defined, ensure it's not been underaligned.
  11518. if (Enum->hasAttrs())
  11519. CheckAlignasUnderalignment(Enum);
  11520. }
  11521. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  11522. SourceLocation StartLoc,
  11523. SourceLocation EndLoc) {
  11524. StringLiteral *AsmString = cast<StringLiteral>(expr);
  11525. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  11526. AsmString, StartLoc,
  11527. EndLoc);
  11528. CurContext->addDecl(New);
  11529. return New;
  11530. }
  11531. static void checkModuleImportContext(Sema &S, Module *M,
  11532. SourceLocation ImportLoc,
  11533. DeclContext *DC) {
  11534. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  11535. switch (LSD->getLanguage()) {
  11536. case LinkageSpecDecl::lang_c:
  11537. if (!M->IsExternC) {
  11538. S.Diag(ImportLoc, diag::err_module_import_in_extern_c)
  11539. << M->getFullModuleName();
  11540. S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c);
  11541. return;
  11542. }
  11543. break;
  11544. case LinkageSpecDecl::lang_cxx:
  11545. break;
  11546. }
  11547. DC = LSD->getParent();
  11548. }
  11549. while (isa<LinkageSpecDecl>(DC))
  11550. DC = DC->getParent();
  11551. if (!isa<TranslationUnitDecl>(DC)) {
  11552. S.Diag(ImportLoc, diag::err_module_import_not_at_top_level)
  11553. << M->getFullModuleName() << DC;
  11554. S.Diag(cast<Decl>(DC)->getLocStart(),
  11555. diag::note_module_import_not_at_top_level)
  11556. << DC;
  11557. }
  11558. }
  11559. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  11560. SourceLocation ImportLoc,
  11561. ModuleIdPath Path) {
  11562. Module *Mod =
  11563. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  11564. /*IsIncludeDirective=*/false);
  11565. if (!Mod)
  11566. return true;
  11567. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  11568. // FIXME: we should support importing a submodule within a different submodule
  11569. // of the same top-level module. Until we do, make it an error rather than
  11570. // silently ignoring the import.
  11571. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
  11572. Diag(ImportLoc, diag::err_module_self_import)
  11573. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  11574. SmallVector<SourceLocation, 2> IdentifierLocs;
  11575. Module *ModCheck = Mod;
  11576. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  11577. // If we've run out of module parents, just drop the remaining identifiers.
  11578. // We need the length to be consistent.
  11579. if (!ModCheck)
  11580. break;
  11581. ModCheck = ModCheck->Parent;
  11582. IdentifierLocs.push_back(Path[I].second);
  11583. }
  11584. ImportDecl *Import = ImportDecl::Create(Context,
  11585. Context.getTranslationUnitDecl(),
  11586. AtLoc.isValid()? AtLoc : ImportLoc,
  11587. Mod, IdentifierLocs);
  11588. Context.getTranslationUnitDecl()->addDecl(Import);
  11589. return Import;
  11590. }
  11591. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  11592. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
  11593. // FIXME: Should we synthesize an ImportDecl here?
  11594. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
  11595. /*Complain=*/true);
  11596. }
  11597. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  11598. Module *Mod) {
  11599. // Bail if we're not allowed to implicitly import a module here.
  11600. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
  11601. return;
  11602. // Create the implicit import declaration.
  11603. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  11604. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  11605. Loc, Mod, Loc);
  11606. TU->addDecl(ImportD);
  11607. Consumer.HandleImplicitImportDecl(ImportD);
  11608. // Make the module visible.
  11609. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
  11610. /*Complain=*/false);
  11611. }
  11612. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  11613. IdentifierInfo* AliasName,
  11614. SourceLocation PragmaLoc,
  11615. SourceLocation NameLoc,
  11616. SourceLocation AliasNameLoc) {
  11617. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  11618. LookupOrdinaryName);
  11619. AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
  11620. AliasName->getName(), 0);
  11621. if (PrevDecl)
  11622. PrevDecl->addAttr(Attr);
  11623. else
  11624. (void)ExtnameUndeclaredIdentifiers.insert(
  11625. std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
  11626. }
  11627. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  11628. SourceLocation PragmaLoc,
  11629. SourceLocation NameLoc) {
  11630. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  11631. if (PrevDecl) {
  11632. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  11633. } else {
  11634. (void)WeakUndeclaredIdentifiers.insert(
  11635. std::pair<IdentifierInfo*,WeakInfo>
  11636. (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
  11637. }
  11638. }
  11639. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  11640. IdentifierInfo* AliasName,
  11641. SourceLocation PragmaLoc,
  11642. SourceLocation NameLoc,
  11643. SourceLocation AliasNameLoc) {
  11644. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  11645. LookupOrdinaryName);
  11646. WeakInfo W = WeakInfo(Name, NameLoc);
  11647. if (PrevDecl) {
  11648. if (!PrevDecl->hasAttr<AliasAttr>())
  11649. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  11650. DeclApplyPragmaWeak(TUScope, ND, W);
  11651. } else {
  11652. (void)WeakUndeclaredIdentifiers.insert(
  11653. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  11654. }
  11655. }
  11656. Decl *Sema::getObjCDeclContext() const {
  11657. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  11658. }
  11659. AvailabilityResult Sema::getCurContextAvailability() const {
  11660. const Decl *D = cast<Decl>(getCurObjCLexicalContext());
  11661. // If we are within an Objective-C method, we should consult
  11662. // both the availability of the method as well as the
  11663. // enclosing class. If the class is (say) deprecated,
  11664. // the entire method is considered deprecated from the
  11665. // purpose of checking if the current context is deprecated.
  11666. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  11667. AvailabilityResult R = MD->getAvailability();
  11668. if (R != AR_Available)
  11669. return R;
  11670. D = MD->getClassInterface();
  11671. }
  11672. // If we are within an Objective-c @implementation, it
  11673. // gets the same availability context as the @interface.
  11674. else if (const ObjCImplementationDecl *ID =
  11675. dyn_cast<ObjCImplementationDecl>(D)) {
  11676. D = ID->getClassInterface();
  11677. }
  11678. return D->getAvailability();
  11679. }