SemaDecl.cpp 417 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859
  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 "clang/Sema/Initialization.h"
  15. #include "clang/Sema/Lookup.h"
  16. #include "clang/Sema/CXXFieldCollector.h"
  17. #include "clang/Sema/Scope.h"
  18. #include "clang/Sema/ScopeInfo.h"
  19. #include "TypeLocBuilder.h"
  20. #include "clang/AST/ASTConsumer.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CXXInheritance.h"
  23. #include "clang/AST/CommentDiagnostic.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/EvaluatedExprVisitor.h"
  28. #include "clang/AST/ExprCXX.h"
  29. #include "clang/AST/StmtCXX.h"
  30. #include "clang/AST/CharUnits.h"
  31. #include "clang/Sema/DeclSpec.h"
  32. #include "clang/Sema/ParsedTemplate.h"
  33. #include "clang/Parse/ParseDiagnostic.h"
  34. #include "clang/Basic/PartialDiagnostic.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Basic/SourceManager.h"
  37. #include "clang/Basic/TargetInfo.h"
  38. // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
  39. #include "clang/Lex/Preprocessor.h"
  40. #include "clang/Lex/HeaderSearch.h"
  41. #include "clang/Lex/ModuleLoader.h"
  42. #include "llvm/ADT/SmallString.h"
  43. #include "llvm/ADT/Triple.h"
  44. #include <algorithm>
  45. #include <cstring>
  46. #include <functional>
  47. using namespace clang;
  48. using namespace sema;
  49. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  50. if (OwnedType) {
  51. Decl *Group[2] = { OwnedType, Ptr };
  52. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  53. }
  54. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  55. }
  56. namespace {
  57. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  58. public:
  59. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
  60. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
  61. WantExpressionKeywords = false;
  62. WantCXXNamedCasts = false;
  63. WantRemainingKeywords = false;
  64. }
  65. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  66. if (NamedDecl *ND = candidate.getCorrectionDecl())
  67. return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
  68. (AllowInvalidDecl || !ND->isInvalidDecl());
  69. else
  70. return !WantClassName && candidate.isKeyword();
  71. }
  72. private:
  73. bool AllowInvalidDecl;
  74. bool WantClassName;
  75. };
  76. }
  77. /// \brief Determine whether the token kind starts a simple-type-specifier.
  78. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  79. switch (Kind) {
  80. // FIXME: Take into account the current language when deciding whether a
  81. // token kind is a valid type specifier
  82. case tok::kw_short:
  83. case tok::kw_long:
  84. case tok::kw___int64:
  85. case tok::kw___int128:
  86. case tok::kw_signed:
  87. case tok::kw_unsigned:
  88. case tok::kw_void:
  89. case tok::kw_char:
  90. case tok::kw_int:
  91. case tok::kw_half:
  92. case tok::kw_float:
  93. case tok::kw_double:
  94. case tok::kw_wchar_t:
  95. case tok::kw_bool:
  96. case tok::kw___underlying_type:
  97. return true;
  98. case tok::annot_typename:
  99. case tok::kw_char16_t:
  100. case tok::kw_char32_t:
  101. case tok::kw_typeof:
  102. case tok::kw_decltype:
  103. return getLangOpts().CPlusPlus;
  104. default:
  105. break;
  106. }
  107. return false;
  108. }
  109. /// \brief If the identifier refers to a type name within this scope,
  110. /// return the declaration of that type.
  111. ///
  112. /// This routine performs ordinary name lookup of the identifier II
  113. /// within the given scope, with optional C++ scope specifier SS, to
  114. /// determine whether the name refers to a type. If so, returns an
  115. /// opaque pointer (actually a QualType) corresponding to that
  116. /// type. Otherwise, returns NULL.
  117. ///
  118. /// If name lookup results in an ambiguity, this routine will complain
  119. /// and then return NULL.
  120. ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
  121. Scope *S, CXXScopeSpec *SS,
  122. bool isClassName, bool HasTrailingDot,
  123. ParsedType ObjectTypePtr,
  124. bool IsCtorOrDtorName,
  125. bool WantNontrivialTypeSourceInfo,
  126. IdentifierInfo **CorrectedII) {
  127. // Determine where we will perform name lookup.
  128. DeclContext *LookupCtx = 0;
  129. if (ObjectTypePtr) {
  130. QualType ObjectType = ObjectTypePtr.get();
  131. if (ObjectType->isRecordType())
  132. LookupCtx = computeDeclContext(ObjectType);
  133. } else if (SS && SS->isNotEmpty()) {
  134. LookupCtx = computeDeclContext(*SS, false);
  135. if (!LookupCtx) {
  136. if (isDependentScopeSpecifier(*SS)) {
  137. // C++ [temp.res]p3:
  138. // A qualified-id that refers to a type and in which the
  139. // nested-name-specifier depends on a template-parameter (14.6.2)
  140. // shall be prefixed by the keyword typename to indicate that the
  141. // qualified-id denotes a type, forming an
  142. // elaborated-type-specifier (7.1.5.3).
  143. //
  144. // We therefore do not perform any name lookup if the result would
  145. // refer to a member of an unknown specialization.
  146. if (!isClassName && !IsCtorOrDtorName)
  147. return ParsedType();
  148. // We know from the grammar that this name refers to a type,
  149. // so build a dependent node to describe the type.
  150. if (WantNontrivialTypeSourceInfo)
  151. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  152. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  153. QualType T =
  154. CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  155. II, NameLoc);
  156. return ParsedType::make(T);
  157. }
  158. return ParsedType();
  159. }
  160. if (!LookupCtx->isDependentContext() &&
  161. RequireCompleteDeclContext(*SS, LookupCtx))
  162. return ParsedType();
  163. }
  164. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  165. // lookup for class-names.
  166. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  167. LookupOrdinaryName;
  168. LookupResult Result(*this, &II, NameLoc, Kind);
  169. if (LookupCtx) {
  170. // Perform "qualified" name lookup into the declaration context we
  171. // computed, which is either the type of the base of a member access
  172. // expression or the declaration context associated with a prior
  173. // nested-name-specifier.
  174. LookupQualifiedName(Result, LookupCtx);
  175. if (ObjectTypePtr && Result.empty()) {
  176. // C++ [basic.lookup.classref]p3:
  177. // If the unqualified-id is ~type-name, the type-name is looked up
  178. // in the context of the entire postfix-expression. If the type T of
  179. // the object expression is of a class type C, the type-name is also
  180. // looked up in the scope of class C. At least one of the lookups shall
  181. // find a name that refers to (possibly cv-qualified) T.
  182. LookupName(Result, S);
  183. }
  184. } else {
  185. // Perform unqualified name lookup.
  186. LookupName(Result, S);
  187. }
  188. NamedDecl *IIDecl = 0;
  189. switch (Result.getResultKind()) {
  190. case LookupResult::NotFound:
  191. case LookupResult::NotFoundInCurrentInstantiation:
  192. if (CorrectedII) {
  193. TypeNameValidatorCCC Validator(true, isClassName);
  194. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
  195. Kind, S, SS, Validator);
  196. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  197. TemplateTy Template;
  198. bool MemberOfUnknownSpecialization;
  199. UnqualifiedId TemplateName;
  200. TemplateName.setIdentifier(NewII, NameLoc);
  201. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  202. CXXScopeSpec NewSS, *NewSSPtr = SS;
  203. if (SS && NNS) {
  204. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  205. NewSSPtr = &NewSS;
  206. }
  207. if (Correction && (NNS || NewII != &II) &&
  208. // Ignore a correction to a template type as the to-be-corrected
  209. // identifier is not a template (typo correction for template names
  210. // is handled elsewhere).
  211. !(getLangOpts().CPlusPlus && NewSSPtr &&
  212. isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
  213. false, Template, MemberOfUnknownSpecialization))) {
  214. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  215. isClassName, HasTrailingDot, ObjectTypePtr,
  216. IsCtorOrDtorName,
  217. WantNontrivialTypeSourceInfo);
  218. if (Ty) {
  219. std::string CorrectedStr(Correction.getAsString(getLangOpts()));
  220. std::string CorrectedQuotedStr(
  221. Correction.getQuoted(getLangOpts()));
  222. Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest)
  223. << Result.getLookupName() << CorrectedQuotedStr << isClassName
  224. << FixItHint::CreateReplacement(SourceRange(NameLoc),
  225. CorrectedStr);
  226. if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
  227. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  228. << CorrectedQuotedStr;
  229. if (SS && NNS)
  230. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  231. *CorrectedII = NewII;
  232. return Ty;
  233. }
  234. }
  235. }
  236. // If typo correction failed or was not performed, fall through
  237. case LookupResult::FoundOverloaded:
  238. case LookupResult::FoundUnresolvedValue:
  239. Result.suppressDiagnostics();
  240. return ParsedType();
  241. case LookupResult::Ambiguous:
  242. // Recover from type-hiding ambiguities by hiding the type. We'll
  243. // do the lookup again when looking for an object, and we can
  244. // diagnose the error then. If we don't do this, then the error
  245. // about hiding the type will be immediately followed by an error
  246. // that only makes sense if the identifier was treated like a type.
  247. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  248. Result.suppressDiagnostics();
  249. return ParsedType();
  250. }
  251. // Look to see if we have a type anywhere in the list of results.
  252. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  253. Res != ResEnd; ++Res) {
  254. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
  255. if (!IIDecl ||
  256. (*Res)->getLocation().getRawEncoding() <
  257. IIDecl->getLocation().getRawEncoding())
  258. IIDecl = *Res;
  259. }
  260. }
  261. if (!IIDecl) {
  262. // None of the entities we found is a type, so there is no way
  263. // to even assume that the result is a type. In this case, don't
  264. // complain about the ambiguity. The parser will either try to
  265. // perform this lookup again (e.g., as an object name), which
  266. // will produce the ambiguity, or will complain that it expected
  267. // a type name.
  268. Result.suppressDiagnostics();
  269. return ParsedType();
  270. }
  271. // We found a type within the ambiguous lookup; diagnose the
  272. // ambiguity and then return that type. This might be the right
  273. // answer, or it might not be, but it suppresses any attempt to
  274. // perform the name lookup again.
  275. break;
  276. case LookupResult::Found:
  277. IIDecl = Result.getFoundDecl();
  278. break;
  279. }
  280. assert(IIDecl && "Didn't find decl");
  281. QualType T;
  282. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  283. DiagnoseUseOfDecl(IIDecl, NameLoc);
  284. if (T.isNull())
  285. T = Context.getTypeDeclType(TD);
  286. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  287. // constructor or destructor name (in such a case, the scope specifier
  288. // will be attached to the enclosing Expr or Decl node).
  289. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
  290. if (WantNontrivialTypeSourceInfo) {
  291. // Construct a type with type-source information.
  292. TypeLocBuilder Builder;
  293. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  294. T = getElaboratedType(ETK_None, *SS, T);
  295. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  296. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  297. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  298. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  299. } else {
  300. T = getElaboratedType(ETK_None, *SS, T);
  301. }
  302. }
  303. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  304. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  305. if (!HasTrailingDot)
  306. T = Context.getObjCInterfaceType(IDecl);
  307. }
  308. if (T.isNull()) {
  309. // If it's not plausibly a type, suppress diagnostics.
  310. Result.suppressDiagnostics();
  311. return ParsedType();
  312. }
  313. return ParsedType::make(T);
  314. }
  315. /// isTagName() - This method is called *for error recovery purposes only*
  316. /// to determine if the specified name is a valid tag name ("struct foo"). If
  317. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  318. /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
  319. /// where the user forgot to specify the tag.
  320. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  321. // Do a tag name lookup in this scope.
  322. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  323. LookupName(R, S, false);
  324. R.suppressDiagnostics();
  325. if (R.getResultKind() == LookupResult::Found)
  326. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  327. switch (TD->getTagKind()) {
  328. case TTK_Struct: return DeclSpec::TST_struct;
  329. case TTK_Union: return DeclSpec::TST_union;
  330. case TTK_Class: return DeclSpec::TST_class;
  331. case TTK_Enum: return DeclSpec::TST_enum;
  332. }
  333. }
  334. return DeclSpec::TST_unspecified;
  335. }
  336. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  337. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  338. /// then downgrade the missing typename error to a warning.
  339. /// This is needed for MSVC compatibility; Example:
  340. /// @code
  341. /// template<class T> class A {
  342. /// public:
  343. /// typedef int TYPE;
  344. /// };
  345. /// template<class T> class B : public A<T> {
  346. /// public:
  347. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  348. /// };
  349. /// @endcode
  350. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  351. if (CurContext->isRecord()) {
  352. const Type *Ty = SS->getScopeRep()->getAsType();
  353. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  354. for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
  355. BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
  356. if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
  357. return true;
  358. return S->isFunctionPrototypeScope();
  359. }
  360. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  361. }
  362. bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  363. SourceLocation IILoc,
  364. Scope *S,
  365. CXXScopeSpec *SS,
  366. ParsedType &SuggestedType) {
  367. // We don't have anything to suggest (yet).
  368. SuggestedType = ParsedType();
  369. // There may have been a typo in the name of the type. Look up typo
  370. // results, in case we have something that we can suggest.
  371. TypeNameValidatorCCC Validator(false);
  372. if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
  373. LookupOrdinaryName, S, SS,
  374. Validator)) {
  375. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  376. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  377. if (Corrected.isKeyword()) {
  378. // We corrected to a keyword.
  379. IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo();
  380. if (!isSimpleTypeSpecifier(NewII->getTokenID()))
  381. CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr;
  382. Diag(IILoc, diag::err_unknown_typename_suggest)
  383. << II << CorrectedQuotedStr
  384. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  385. II = NewII;
  386. } else {
  387. NamedDecl *Result = Corrected.getCorrectionDecl();
  388. // We found a similarly-named type or interface; suggest that.
  389. if (!SS || !SS->isSet())
  390. Diag(IILoc, diag::err_unknown_typename_suggest)
  391. << II << CorrectedQuotedStr
  392. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  393. else if (DeclContext *DC = computeDeclContext(*SS, false))
  394. Diag(IILoc, diag::err_unknown_nested_typename_suggest)
  395. << II << DC << CorrectedQuotedStr << SS->getRange()
  396. << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
  397. else
  398. llvm_unreachable("could not have corrected a typo here");
  399. Diag(Result->getLocation(), diag::note_previous_decl)
  400. << CorrectedQuotedStr;
  401. SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
  402. false, false, ParsedType(),
  403. /*IsCtorOrDtorName=*/false,
  404. /*NonTrivialTypeSourceInfo=*/true);
  405. }
  406. return true;
  407. }
  408. if (getLangOpts().CPlusPlus) {
  409. // See if II is a class template that the user forgot to pass arguments to.
  410. UnqualifiedId Name;
  411. Name.setIdentifier(II, IILoc);
  412. CXXScopeSpec EmptySS;
  413. TemplateTy TemplateResult;
  414. bool MemberOfUnknownSpecialization;
  415. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  416. Name, ParsedType(), true, TemplateResult,
  417. MemberOfUnknownSpecialization) == TNK_Type_template) {
  418. TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
  419. Diag(IILoc, diag::err_template_missing_args) << TplName;
  420. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  421. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  422. << TplDecl->getTemplateParameters()->getSourceRange();
  423. }
  424. return true;
  425. }
  426. }
  427. // FIXME: Should we move the logic that tries to recover from a missing tag
  428. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  429. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  430. Diag(IILoc, diag::err_unknown_typename) << II;
  431. else if (DeclContext *DC = computeDeclContext(*SS, false))
  432. Diag(IILoc, diag::err_typename_nested_not_found)
  433. << II << DC << SS->getRange();
  434. else if (isDependentScopeSpecifier(*SS)) {
  435. unsigned DiagID = diag::err_typename_missing;
  436. if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
  437. DiagID = diag::warn_typename_missing;
  438. Diag(SS->getRange().getBegin(), DiagID)
  439. << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
  440. << SourceRange(SS->getRange().getBegin(), IILoc)
  441. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  442. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  443. *SS, *II, IILoc).get();
  444. } else {
  445. assert(SS && SS->isInvalid() &&
  446. "Invalid scope specifier has already been diagnosed");
  447. }
  448. return true;
  449. }
  450. /// \brief Determine whether the given result set contains either a type name
  451. /// or
  452. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  453. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  454. NextToken.is(tok::less);
  455. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  456. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  457. return true;
  458. if (CheckTemplate && isa<TemplateDecl>(*I))
  459. return true;
  460. }
  461. return false;
  462. }
  463. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  464. Scope *S, CXXScopeSpec &SS,
  465. IdentifierInfo *&Name,
  466. SourceLocation NameLoc) {
  467. Result.clear(Sema::LookupTagName);
  468. SemaRef.LookupParsedName(Result, S, &SS);
  469. if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
  470. const char *TagName = 0;
  471. const char *FixItTagName = 0;
  472. switch (Tag->getTagKind()) {
  473. case TTK_Class:
  474. TagName = "class";
  475. FixItTagName = "class ";
  476. break;
  477. case TTK_Enum:
  478. TagName = "enum";
  479. FixItTagName = "enum ";
  480. break;
  481. case TTK_Struct:
  482. TagName = "struct";
  483. FixItTagName = "struct ";
  484. break;
  485. case TTK_Union:
  486. TagName = "union";
  487. FixItTagName = "union ";
  488. break;
  489. }
  490. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  491. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  492. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  493. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName);
  494. if (SemaRef.LookupParsedName(R, S, &SS)) {
  495. for (LookupResult::iterator I = R.begin(), IEnd = R.end();
  496. I != IEnd; ++I)
  497. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  498. << Name << TagName;
  499. }
  500. return true;
  501. }
  502. Result.clear(Sema::LookupOrdinaryName);
  503. return false;
  504. }
  505. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  506. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  507. QualType T, SourceLocation NameLoc) {
  508. ASTContext &Context = S.Context;
  509. TypeLocBuilder Builder;
  510. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  511. T = S.getElaboratedType(ETK_None, SS, T);
  512. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  513. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  514. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  515. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  516. }
  517. Sema::NameClassification Sema::ClassifyName(Scope *S,
  518. CXXScopeSpec &SS,
  519. IdentifierInfo *&Name,
  520. SourceLocation NameLoc,
  521. const Token &NextToken,
  522. bool IsAddressOfOperand,
  523. CorrectionCandidateCallback *CCC) {
  524. DeclarationNameInfo NameInfo(Name, NameLoc);
  525. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  526. if (NextToken.is(tok::coloncolon)) {
  527. BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
  528. QualType(), false, SS, 0, false);
  529. }
  530. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  531. LookupParsedName(Result, S, &SS, !CurMethod);
  532. // Perform lookup for Objective-C instance variables (including automatically
  533. // synthesized instance variables), if we're in an Objective-C method.
  534. // FIXME: This lookup really, really needs to be folded in to the normal
  535. // unqualified lookup mechanism.
  536. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  537. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  538. if (E.get() || E.isInvalid())
  539. return E;
  540. }
  541. bool SecondTry = false;
  542. bool IsFilteredTemplateName = false;
  543. Corrected:
  544. switch (Result.getResultKind()) {
  545. case LookupResult::NotFound:
  546. // If an unqualified-id is followed by a '(', then we have a function
  547. // call.
  548. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  549. // In C++, this is an ADL-only call.
  550. // FIXME: Reference?
  551. if (getLangOpts().CPlusPlus)
  552. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  553. // C90 6.3.2.2:
  554. // If the expression that precedes the parenthesized argument list in a
  555. // function call consists solely of an identifier, and if no
  556. // declaration is visible for this identifier, the identifier is
  557. // implicitly declared exactly as if, in the innermost block containing
  558. // the function call, the declaration
  559. //
  560. // extern int identifier ();
  561. //
  562. // appeared.
  563. //
  564. // We also allow this in C99 as an extension.
  565. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  566. Result.addDecl(D);
  567. Result.resolveKind();
  568. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  569. }
  570. }
  571. // In C, we first see whether there is a tag type by the same name, in
  572. // which case it's likely that the user just forget to write "enum",
  573. // "struct", or "union".
  574. if (!getLangOpts().CPlusPlus && !SecondTry &&
  575. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  576. break;
  577. }
  578. // Perform typo correction to determine if there is another name that is
  579. // close to this name.
  580. if (!SecondTry && CCC) {
  581. SecondTry = true;
  582. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  583. Result.getLookupKind(), S,
  584. &SS, *CCC)) {
  585. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  586. unsigned QualifiedDiag = diag::err_no_member_suggest;
  587. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  588. std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
  589. NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
  590. NamedDecl *UnderlyingFirstDecl
  591. = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
  592. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  593. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  594. UnqualifiedDiag = diag::err_no_template_suggest;
  595. QualifiedDiag = diag::err_no_member_template_suggest;
  596. } else if (UnderlyingFirstDecl &&
  597. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  598. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  599. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  600. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  601. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  602. }
  603. if (SS.isEmpty())
  604. Diag(NameLoc, UnqualifiedDiag)
  605. << Name << CorrectedQuotedStr
  606. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  607. else
  608. Diag(NameLoc, QualifiedDiag)
  609. << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
  610. << SS.getRange()
  611. << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
  612. // Update the name, so that the caller has the new name.
  613. Name = Corrected.getCorrectionAsIdentifierInfo();
  614. // Typo correction corrected to a keyword.
  615. if (Corrected.isKeyword())
  616. return Corrected.getCorrectionAsIdentifierInfo();
  617. // Also update the LookupResult...
  618. // FIXME: This should probably go away at some point
  619. Result.clear();
  620. Result.setLookupName(Corrected.getCorrection());
  621. if (FirstDecl) {
  622. Result.addDecl(FirstDecl);
  623. Diag(FirstDecl->getLocation(), diag::note_previous_decl)
  624. << CorrectedQuotedStr;
  625. }
  626. // If we found an Objective-C instance variable, let
  627. // LookupInObjCMethod build the appropriate expression to
  628. // reference the ivar.
  629. // FIXME: This is a gross hack.
  630. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  631. Result.clear();
  632. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  633. return E;
  634. }
  635. goto Corrected;
  636. }
  637. }
  638. // We failed to correct; just fall through and let the parser deal with it.
  639. Result.suppressDiagnostics();
  640. return NameClassification::Unknown();
  641. case LookupResult::NotFoundInCurrentInstantiation: {
  642. // We performed name lookup into the current instantiation, and there were
  643. // dependent bases, so we treat this result the same way as any other
  644. // dependent nested-name-specifier.
  645. // C++ [temp.res]p2:
  646. // A name used in a template declaration or definition and that is
  647. // dependent on a template-parameter is assumed not to name a type
  648. // unless the applicable name lookup finds a type name or the name is
  649. // qualified by the keyword typename.
  650. //
  651. // FIXME: If the next token is '<', we might want to ask the parser to
  652. // perform some heroics to see if we actually have a
  653. // template-argument-list, which would indicate a missing 'template'
  654. // keyword here.
  655. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  656. NameInfo, IsAddressOfOperand,
  657. /*TemplateArgs=*/0);
  658. }
  659. case LookupResult::Found:
  660. case LookupResult::FoundOverloaded:
  661. case LookupResult::FoundUnresolvedValue:
  662. break;
  663. case LookupResult::Ambiguous:
  664. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  665. hasAnyAcceptableTemplateNames(Result)) {
  666. // C++ [temp.local]p3:
  667. // A lookup that finds an injected-class-name (10.2) can result in an
  668. // ambiguity in certain cases (for example, if it is found in more than
  669. // one base class). If all of the injected-class-names that are found
  670. // refer to specializations of the same class template, and if the name
  671. // is followed by a template-argument-list, the reference refers to the
  672. // class template itself and not a specialization thereof, and is not
  673. // ambiguous.
  674. //
  675. // This filtering can make an ambiguous result into an unambiguous one,
  676. // so try again after filtering out template names.
  677. FilterAcceptableTemplateNames(Result);
  678. if (!Result.isAmbiguous()) {
  679. IsFilteredTemplateName = true;
  680. break;
  681. }
  682. }
  683. // Diagnose the ambiguity and return an error.
  684. return NameClassification::Error();
  685. }
  686. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  687. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  688. // C++ [temp.names]p3:
  689. // After name lookup (3.4) finds that a name is a template-name or that
  690. // an operator-function-id or a literal- operator-id refers to a set of
  691. // overloaded functions any member of which is a function template if
  692. // this is followed by a <, the < is always taken as the delimiter of a
  693. // template-argument-list and never as the less-than operator.
  694. if (!IsFilteredTemplateName)
  695. FilterAcceptableTemplateNames(Result);
  696. if (!Result.empty()) {
  697. bool IsFunctionTemplate;
  698. TemplateName Template;
  699. if (Result.end() - Result.begin() > 1) {
  700. IsFunctionTemplate = true;
  701. Template = Context.getOverloadedTemplateName(Result.begin(),
  702. Result.end());
  703. } else {
  704. TemplateDecl *TD
  705. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  706. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  707. if (SS.isSet() && !SS.isInvalid())
  708. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  709. /*TemplateKeyword=*/false,
  710. TD);
  711. else
  712. Template = TemplateName(TD);
  713. }
  714. if (IsFunctionTemplate) {
  715. // Function templates always go through overload resolution, at which
  716. // point we'll perform the various checks (e.g., accessibility) we need
  717. // to based on which function we selected.
  718. Result.suppressDiagnostics();
  719. return NameClassification::FunctionTemplate(Template);
  720. }
  721. return NameClassification::TypeTemplate(Template);
  722. }
  723. }
  724. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  725. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  726. DiagnoseUseOfDecl(Type, NameLoc);
  727. QualType T = Context.getTypeDeclType(Type);
  728. if (SS.isNotEmpty())
  729. return buildNestedType(*this, SS, T, NameLoc);
  730. return ParsedType::make(T);
  731. }
  732. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  733. if (!Class) {
  734. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  735. if (ObjCCompatibleAliasDecl *Alias
  736. = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  737. Class = Alias->getClassInterface();
  738. }
  739. if (Class) {
  740. DiagnoseUseOfDecl(Class, NameLoc);
  741. if (NextToken.is(tok::period)) {
  742. // Interface. <something> is parsed as a property reference expression.
  743. // Just return "unknown" as a fall-through for now.
  744. Result.suppressDiagnostics();
  745. return NameClassification::Unknown();
  746. }
  747. QualType T = Context.getObjCInterfaceType(Class);
  748. return ParsedType::make(T);
  749. }
  750. // We can have a type template here if we're classifying a template argument.
  751. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
  752. return NameClassification::TypeTemplate(
  753. TemplateName(cast<TemplateDecl>(FirstDecl)));
  754. // Check for a tag type hidden by a non-type decl in a few cases where it
  755. // seems likely a type is wanted instead of the non-type that was found.
  756. if (!getLangOpts().ObjC1) {
  757. bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
  758. if ((NextToken.is(tok::identifier) ||
  759. (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
  760. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  761. FirstDecl = (*Result.begin())->getUnderlyingDecl();
  762. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  763. DiagnoseUseOfDecl(Type, NameLoc);
  764. QualType T = Context.getTypeDeclType(Type);
  765. if (SS.isNotEmpty())
  766. return buildNestedType(*this, SS, T, NameLoc);
  767. return ParsedType::make(T);
  768. }
  769. }
  770. }
  771. if (FirstDecl->isCXXClassMember())
  772. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
  773. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  774. return BuildDeclarationNameExpr(SS, Result, ADL);
  775. }
  776. // Determines the context to return to after temporarily entering a
  777. // context. This depends in an unnecessarily complicated way on the
  778. // exact ordering of callbacks from the parser.
  779. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  780. // Functions defined inline within classes aren't parsed until we've
  781. // finished parsing the top-level class, so the top-level class is
  782. // the context we'll need to return to.
  783. if (isa<FunctionDecl>(DC)) {
  784. DC = DC->getLexicalParent();
  785. // A function not defined within a class will always return to its
  786. // lexical context.
  787. if (!isa<CXXRecordDecl>(DC))
  788. return DC;
  789. // A C++ inline method/friend is parsed *after* the topmost class
  790. // it was declared in is fully parsed ("complete"); the topmost
  791. // class is the context we need to return to.
  792. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  793. DC = RD;
  794. // Return the declaration context of the topmost class the inline method is
  795. // declared in.
  796. return DC;
  797. }
  798. return DC->getLexicalParent();
  799. }
  800. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  801. assert(getContainingDC(DC) == CurContext &&
  802. "The next DeclContext should be lexically contained in the current one.");
  803. CurContext = DC;
  804. S->setEntity(DC);
  805. }
  806. void Sema::PopDeclContext() {
  807. assert(CurContext && "DeclContext imbalance!");
  808. CurContext = getContainingDC(CurContext);
  809. assert(CurContext && "Popped translation unit!");
  810. }
  811. /// EnterDeclaratorContext - Used when we must lookup names in the context
  812. /// of a declarator's nested name specifier.
  813. ///
  814. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  815. // C++0x [basic.lookup.unqual]p13:
  816. // A name used in the definition of a static data member of class
  817. // X (after the qualified-id of the static member) is looked up as
  818. // if the name was used in a member function of X.
  819. // C++0x [basic.lookup.unqual]p14:
  820. // If a variable member of a namespace is defined outside of the
  821. // scope of its namespace then any name used in the definition of
  822. // the variable member (after the declarator-id) is looked up as
  823. // if the definition of the variable member occurred in its
  824. // namespace.
  825. // Both of these imply that we should push a scope whose context
  826. // is the semantic context of the declaration. We can't use
  827. // PushDeclContext here because that context is not necessarily
  828. // lexically contained in the current context. Fortunately,
  829. // the containing scope should have the appropriate information.
  830. assert(!S->getEntity() && "scope already has entity");
  831. #ifndef NDEBUG
  832. Scope *Ancestor = S->getParent();
  833. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  834. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  835. #endif
  836. CurContext = DC;
  837. S->setEntity(DC);
  838. }
  839. void Sema::ExitDeclaratorContext(Scope *S) {
  840. assert(S->getEntity() == CurContext && "Context imbalance!");
  841. // Switch back to the lexical context. The safety of this is
  842. // enforced by an assert in EnterDeclaratorContext.
  843. Scope *Ancestor = S->getParent();
  844. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  845. CurContext = (DeclContext*) Ancestor->getEntity();
  846. // We don't need to do anything with the scope, which is going to
  847. // disappear.
  848. }
  849. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  850. FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  851. if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
  852. // We assume that the caller has already called
  853. // ActOnReenterTemplateScope
  854. FD = TFD->getTemplatedDecl();
  855. }
  856. if (!FD)
  857. return;
  858. // Same implementation as PushDeclContext, but enters the context
  859. // from the lexical parent, rather than the top-level class.
  860. assert(CurContext == FD->getLexicalParent() &&
  861. "The next DeclContext should be lexically contained in the current one.");
  862. CurContext = FD;
  863. S->setEntity(CurContext);
  864. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  865. ParmVarDecl *Param = FD->getParamDecl(P);
  866. // If the parameter has an identifier, then add it to the scope
  867. if (Param->getIdentifier()) {
  868. S->AddDecl(Param);
  869. IdResolver.AddDecl(Param);
  870. }
  871. }
  872. }
  873. void Sema::ActOnExitFunctionContext() {
  874. // Same implementation as PopDeclContext, but returns to the lexical parent,
  875. // rather than the top-level class.
  876. assert(CurContext && "DeclContext imbalance!");
  877. CurContext = CurContext->getLexicalParent();
  878. assert(CurContext && "Popped translation unit!");
  879. }
  880. /// \brief Determine whether we allow overloading of the function
  881. /// PrevDecl with another declaration.
  882. ///
  883. /// This routine determines whether overloading is possible, not
  884. /// whether some new function is actually an overload. It will return
  885. /// true in C++ (where we can always provide overloads) or, as an
  886. /// extension, in C when the previous function is already an
  887. /// overloaded function declaration or has the "overloadable"
  888. /// attribute.
  889. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  890. ASTContext &Context) {
  891. if (Context.getLangOpts().CPlusPlus)
  892. return true;
  893. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  894. return true;
  895. return (Previous.getResultKind() == LookupResult::Found
  896. && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
  897. }
  898. /// Add this decl to the scope shadowed decl chains.
  899. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  900. // Move up the scope chain until we find the nearest enclosing
  901. // non-transparent context. The declaration will be introduced into this
  902. // scope.
  903. while (S->getEntity() &&
  904. ((DeclContext *)S->getEntity())->isTransparentContext())
  905. S = S->getParent();
  906. // Add scoped declarations into their context, so that they can be
  907. // found later. Declarations without a context won't be inserted
  908. // into any context.
  909. if (AddToContext)
  910. CurContext->addDecl(D);
  911. // Out-of-line definitions shouldn't be pushed into scope in C++.
  912. // Out-of-line variable and function definitions shouldn't even in C.
  913. if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
  914. D->isOutOfLine() &&
  915. !D->getDeclContext()->getRedeclContext()->Equals(
  916. D->getLexicalDeclContext()->getRedeclContext()))
  917. return;
  918. // Template instantiations should also not be pushed into scope.
  919. if (isa<FunctionDecl>(D) &&
  920. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  921. return;
  922. // If this replaces anything in the current scope,
  923. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  924. IEnd = IdResolver.end();
  925. for (; I != IEnd; ++I) {
  926. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  927. S->RemoveDecl(*I);
  928. IdResolver.RemoveDecl(*I);
  929. // Should only need to replace one decl.
  930. break;
  931. }
  932. }
  933. S->AddDecl(D);
  934. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  935. // Implicitly-generated labels may end up getting generated in an order that
  936. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  937. // the label at the appropriate place in the identifier chain.
  938. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  939. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  940. if (IDC == CurContext) {
  941. if (!S->isDeclScope(*I))
  942. continue;
  943. } else if (IDC->Encloses(CurContext))
  944. break;
  945. }
  946. IdResolver.InsertDeclAfter(I, D);
  947. } else {
  948. IdResolver.AddDecl(D);
  949. }
  950. }
  951. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  952. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  953. TUScope->AddDecl(D);
  954. }
  955. bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
  956. bool ExplicitInstantiationOrSpecialization) {
  957. return IdResolver.isDeclInScope(D, Ctx, Context, S,
  958. ExplicitInstantiationOrSpecialization);
  959. }
  960. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  961. DeclContext *TargetDC = DC->getPrimaryContext();
  962. do {
  963. if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
  964. if (ScopeDC->getPrimaryContext() == TargetDC)
  965. return S;
  966. } while ((S = S->getParent()));
  967. return 0;
  968. }
  969. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  970. DeclContext*,
  971. ASTContext&);
  972. /// Filters out lookup results that don't fall within the given scope
  973. /// as determined by isDeclInScope.
  974. void Sema::FilterLookupForScope(LookupResult &R,
  975. DeclContext *Ctx, Scope *S,
  976. bool ConsiderLinkage,
  977. bool ExplicitInstantiationOrSpecialization) {
  978. LookupResult::Filter F = R.makeFilter();
  979. while (F.hasNext()) {
  980. NamedDecl *D = F.next();
  981. if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
  982. continue;
  983. if (ConsiderLinkage &&
  984. isOutOfScopePreviousDeclaration(D, Ctx, Context))
  985. continue;
  986. F.erase();
  987. }
  988. F.done();
  989. }
  990. static bool isUsingDecl(NamedDecl *D) {
  991. return isa<UsingShadowDecl>(D) ||
  992. isa<UnresolvedUsingTypenameDecl>(D) ||
  993. isa<UnresolvedUsingValueDecl>(D);
  994. }
  995. /// Removes using shadow declarations from the lookup results.
  996. static void RemoveUsingDecls(LookupResult &R) {
  997. LookupResult::Filter F = R.makeFilter();
  998. while (F.hasNext())
  999. if (isUsingDecl(F.next()))
  1000. F.erase();
  1001. F.done();
  1002. }
  1003. /// \brief Check for this common pattern:
  1004. /// @code
  1005. /// class S {
  1006. /// S(const S&); // DO NOT IMPLEMENT
  1007. /// void operator=(const S&); // DO NOT IMPLEMENT
  1008. /// };
  1009. /// @endcode
  1010. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1011. // FIXME: Should check for private access too but access is set after we get
  1012. // the decl here.
  1013. if (D->doesThisDeclarationHaveABody())
  1014. return false;
  1015. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1016. return CD->isCopyConstructor();
  1017. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1018. return Method->isCopyAssignmentOperator();
  1019. return false;
  1020. }
  1021. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1022. assert(D);
  1023. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1024. return false;
  1025. // Ignore class templates.
  1026. if (D->getDeclContext()->isDependentContext() ||
  1027. D->getLexicalDeclContext()->isDependentContext())
  1028. return false;
  1029. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1030. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1031. return false;
  1032. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1033. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1034. return false;
  1035. } else {
  1036. // 'static inline' functions are used in headers; don't warn.
  1037. if (FD->getStorageClass() == SC_Static &&
  1038. FD->isInlineSpecified())
  1039. return false;
  1040. }
  1041. if (FD->doesThisDeclarationHaveABody() &&
  1042. Context.DeclMustBeEmitted(FD))
  1043. return false;
  1044. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1045. if (!VD->isFileVarDecl() ||
  1046. VD->getType().isConstant(Context) ||
  1047. Context.DeclMustBeEmitted(VD))
  1048. return false;
  1049. if (VD->isStaticDataMember() &&
  1050. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1051. return false;
  1052. } else {
  1053. return false;
  1054. }
  1055. // Only warn for unused decls internal to the translation unit.
  1056. if (D->getLinkage() == ExternalLinkage)
  1057. return false;
  1058. return true;
  1059. }
  1060. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1061. if (!D)
  1062. return;
  1063. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1064. const FunctionDecl *First = FD->getFirstDeclaration();
  1065. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1066. return; // First should already be in the vector.
  1067. }
  1068. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1069. const VarDecl *First = VD->getFirstDeclaration();
  1070. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1071. return; // First should already be in the vector.
  1072. }
  1073. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1074. UnusedFileScopedDecls.push_back(D);
  1075. }
  1076. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1077. if (D->isInvalidDecl())
  1078. return false;
  1079. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1080. return false;
  1081. if (isa<LabelDecl>(D))
  1082. return true;
  1083. // White-list anything that isn't a local variable.
  1084. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
  1085. !D->getDeclContext()->isFunctionOrMethod())
  1086. return false;
  1087. // Types of valid local variables should be complete, so this should succeed.
  1088. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1089. // White-list anything with an __attribute__((unused)) type.
  1090. QualType Ty = VD->getType();
  1091. // Only look at the outermost level of typedef.
  1092. if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
  1093. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1094. return false;
  1095. }
  1096. // If we failed to complete the type for some reason, or if the type is
  1097. // dependent, don't diagnose the variable.
  1098. if (Ty->isIncompleteType() || Ty->isDependentType())
  1099. return false;
  1100. if (const TagType *TT = Ty->getAs<TagType>()) {
  1101. const TagDecl *Tag = TT->getDecl();
  1102. if (Tag->hasAttr<UnusedAttr>())
  1103. return false;
  1104. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1105. if (!RD->hasTrivialDestructor())
  1106. return false;
  1107. if (const Expr *Init = VD->getInit()) {
  1108. const CXXConstructExpr *Construct =
  1109. dyn_cast<CXXConstructExpr>(Init);
  1110. if (Construct && !Construct->isElidable()) {
  1111. CXXConstructorDecl *CD = Construct->getConstructor();
  1112. if (!CD->isTrivial())
  1113. return false;
  1114. }
  1115. }
  1116. }
  1117. }
  1118. // TODO: __attribute__((unused)) templates?
  1119. }
  1120. return true;
  1121. }
  1122. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1123. FixItHint &Hint) {
  1124. if (isa<LabelDecl>(D)) {
  1125. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1126. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1127. if (AfterColon.isInvalid())
  1128. return;
  1129. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1130. getCharRange(D->getLocStart(), AfterColon));
  1131. }
  1132. return;
  1133. }
  1134. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1135. /// unless they are marked attr(unused).
  1136. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1137. FixItHint Hint;
  1138. if (!ShouldDiagnoseUnusedDecl(D))
  1139. return;
  1140. GenerateFixForUnusedDecl(D, Context, Hint);
  1141. unsigned DiagID;
  1142. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1143. DiagID = diag::warn_unused_exception_param;
  1144. else if (isa<LabelDecl>(D))
  1145. DiagID = diag::warn_unused_label;
  1146. else
  1147. DiagID = diag::warn_unused_variable;
  1148. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1149. }
  1150. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1151. // Verify that we have no forward references left. If so, there was a goto
  1152. // or address of a label taken, but no definition of it. Label fwd
  1153. // definitions are indicated with a null substmt.
  1154. if (L->getStmt() == 0)
  1155. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1156. }
  1157. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1158. if (S->decl_empty()) return;
  1159. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1160. "Scope shouldn't contain decls!");
  1161. for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
  1162. I != E; ++I) {
  1163. Decl *TmpD = (*I);
  1164. assert(TmpD && "This decl didn't get pushed??");
  1165. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1166. NamedDecl *D = cast<NamedDecl>(TmpD);
  1167. if (!D->getDeclName()) continue;
  1168. // Diagnose unused variables in this scope.
  1169. if (!S->hasErrorOccurred())
  1170. DiagnoseUnusedDecl(D);
  1171. // If this was a forward reference to a label, verify it was defined.
  1172. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1173. CheckPoppedLabel(LD, *this);
  1174. // Remove this name from our lexical scope.
  1175. IdResolver.RemoveDecl(D);
  1176. }
  1177. }
  1178. void Sema::ActOnStartFunctionDeclarator() {
  1179. ++InFunctionDeclarator;
  1180. }
  1181. void Sema::ActOnEndFunctionDeclarator() {
  1182. assert(InFunctionDeclarator);
  1183. --InFunctionDeclarator;
  1184. }
  1185. /// \brief Look for an Objective-C class in the translation unit.
  1186. ///
  1187. /// \param Id The name of the Objective-C class we're looking for. If
  1188. /// typo-correction fixes this name, the Id will be updated
  1189. /// to the fixed name.
  1190. ///
  1191. /// \param IdLoc The location of the name in the translation unit.
  1192. ///
  1193. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1194. /// if there is no class with the given name.
  1195. ///
  1196. /// \returns The declaration of the named Objective-C class, or NULL if the
  1197. /// class could not be found.
  1198. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1199. SourceLocation IdLoc,
  1200. bool DoTypoCorrection) {
  1201. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1202. // creation from this context.
  1203. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1204. if (!IDecl && DoTypoCorrection) {
  1205. // Perform typo correction at the given location, but only if we
  1206. // find an Objective-C class name.
  1207. DeclFilterCCC<ObjCInterfaceDecl> Validator;
  1208. if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
  1209. LookupOrdinaryName, TUScope, NULL,
  1210. Validator)) {
  1211. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1212. Diag(IdLoc, diag::err_undef_interface_suggest)
  1213. << Id << IDecl->getDeclName()
  1214. << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
  1215. Diag(IDecl->getLocation(), diag::note_previous_decl)
  1216. << IDecl->getDeclName();
  1217. Id = IDecl->getIdentifier();
  1218. }
  1219. }
  1220. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1221. // This routine must always return a class definition, if any.
  1222. if (Def && Def->getDefinition())
  1223. Def = Def->getDefinition();
  1224. return Def;
  1225. }
  1226. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1227. /// from S, where a non-field would be declared. This routine copes
  1228. /// with the difference between C and C++ scoping rules in structs and
  1229. /// unions. For example, the following code is well-formed in C but
  1230. /// ill-formed in C++:
  1231. /// @code
  1232. /// struct S6 {
  1233. /// enum { BAR } e;
  1234. /// };
  1235. ///
  1236. /// void test_S6() {
  1237. /// struct S6 a;
  1238. /// a.e = BAR;
  1239. /// }
  1240. /// @endcode
  1241. /// For the declaration of BAR, this routine will return a different
  1242. /// scope. The scope S will be the scope of the unnamed enumeration
  1243. /// within S6. In C++, this routine will return the scope associated
  1244. /// with S6, because the enumeration's scope is a transparent
  1245. /// context but structures can contain non-field names. In C, this
  1246. /// routine will return the translation unit scope, since the
  1247. /// enumeration's scope is a transparent context and structures cannot
  1248. /// contain non-field names.
  1249. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1250. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1251. (S->getEntity() &&
  1252. ((DeclContext *)S->getEntity())->isTransparentContext()) ||
  1253. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1254. S = S->getParent();
  1255. return S;
  1256. }
  1257. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1258. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1259. /// if we're creating this built-in in anticipation of redeclaring the
  1260. /// built-in.
  1261. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
  1262. Scope *S, bool ForRedeclaration,
  1263. SourceLocation Loc) {
  1264. Builtin::ID BID = (Builtin::ID)bid;
  1265. ASTContext::GetBuiltinTypeError Error;
  1266. QualType R = Context.GetBuiltinType(BID, Error);
  1267. switch (Error) {
  1268. case ASTContext::GE_None:
  1269. // Okay
  1270. break;
  1271. case ASTContext::GE_Missing_stdio:
  1272. if (ForRedeclaration)
  1273. Diag(Loc, diag::warn_implicit_decl_requires_stdio)
  1274. << Context.BuiltinInfo.GetName(BID);
  1275. return 0;
  1276. case ASTContext::GE_Missing_setjmp:
  1277. if (ForRedeclaration)
  1278. Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
  1279. << Context.BuiltinInfo.GetName(BID);
  1280. return 0;
  1281. case ASTContext::GE_Missing_ucontext:
  1282. if (ForRedeclaration)
  1283. Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
  1284. << Context.BuiltinInfo.GetName(BID);
  1285. return 0;
  1286. }
  1287. if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  1288. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1289. << Context.BuiltinInfo.GetName(BID)
  1290. << R;
  1291. if (Context.BuiltinInfo.getHeaderName(BID) &&
  1292. Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
  1293. != DiagnosticsEngine::Ignored)
  1294. Diag(Loc, diag::note_please_include_header)
  1295. << Context.BuiltinInfo.getHeaderName(BID)
  1296. << Context.BuiltinInfo.GetName(BID);
  1297. }
  1298. FunctionDecl *New = FunctionDecl::Create(Context,
  1299. Context.getTranslationUnitDecl(),
  1300. Loc, Loc, II, R, /*TInfo=*/0,
  1301. SC_Extern,
  1302. SC_None, false,
  1303. /*hasPrototype=*/true);
  1304. New->setImplicit();
  1305. // Create Decl objects for each parameter, adding them to the
  1306. // FunctionDecl.
  1307. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1308. SmallVector<ParmVarDecl*, 16> Params;
  1309. for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
  1310. ParmVarDecl *parm =
  1311. ParmVarDecl::Create(Context, New, SourceLocation(),
  1312. SourceLocation(), 0,
  1313. FT->getArgType(i), /*TInfo=*/0,
  1314. SC_None, SC_None, 0);
  1315. parm->setScopeInfo(0, i);
  1316. Params.push_back(parm);
  1317. }
  1318. New->setParams(Params);
  1319. }
  1320. AddKnownFunctionAttributes(New);
  1321. // TUScope is the translation-unit scope to insert this function into.
  1322. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1323. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1324. // entirely, but we're not there yet.
  1325. DeclContext *SavedContext = CurContext;
  1326. CurContext = Context.getTranslationUnitDecl();
  1327. PushOnScopeChains(New, TUScope);
  1328. CurContext = SavedContext;
  1329. return New;
  1330. }
  1331. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1332. QualType OldType;
  1333. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1334. OldType = OldTypedef->getUnderlyingType();
  1335. else
  1336. OldType = Context.getTypeDeclType(Old);
  1337. QualType NewType = New->getUnderlyingType();
  1338. if (NewType->isVariablyModifiedType()) {
  1339. // Must not redefine a typedef with a variably-modified type.
  1340. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1341. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1342. << Kind << NewType;
  1343. if (Old->getLocation().isValid())
  1344. Diag(Old->getLocation(), diag::note_previous_definition);
  1345. New->setInvalidDecl();
  1346. return true;
  1347. }
  1348. if (OldType != NewType &&
  1349. !OldType->isDependentType() &&
  1350. !NewType->isDependentType() &&
  1351. !Context.hasSameType(OldType, NewType)) {
  1352. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1353. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1354. << Kind << NewType << OldType;
  1355. if (Old->getLocation().isValid())
  1356. Diag(Old->getLocation(), diag::note_previous_definition);
  1357. New->setInvalidDecl();
  1358. return true;
  1359. }
  1360. return false;
  1361. }
  1362. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1363. /// same name and scope as a previous declaration 'Old'. Figure out
  1364. /// how to resolve this situation, merging decls or emitting
  1365. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1366. ///
  1367. void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
  1368. // If the new decl is known invalid already, don't bother doing any
  1369. // merging checks.
  1370. if (New->isInvalidDecl()) return;
  1371. // Allow multiple definitions for ObjC built-in typedefs.
  1372. // FIXME: Verify the underlying types are equivalent!
  1373. if (getLangOpts().ObjC1) {
  1374. const IdentifierInfo *TypeID = New->getIdentifier();
  1375. switch (TypeID->getLength()) {
  1376. default: break;
  1377. case 2:
  1378. {
  1379. if (!TypeID->isStr("id"))
  1380. break;
  1381. QualType T = New->getUnderlyingType();
  1382. if (!T->isPointerType())
  1383. break;
  1384. if (!T->isVoidPointerType()) {
  1385. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1386. if (!PT->isStructureType())
  1387. break;
  1388. }
  1389. Context.setObjCIdRedefinitionType(T);
  1390. // Install the built-in type for 'id', ignoring the current definition.
  1391. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1392. return;
  1393. }
  1394. case 5:
  1395. if (!TypeID->isStr("Class"))
  1396. break;
  1397. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1398. // Install the built-in type for 'Class', ignoring the current definition.
  1399. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1400. return;
  1401. case 3:
  1402. if (!TypeID->isStr("SEL"))
  1403. break;
  1404. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1405. // Install the built-in type for 'SEL', ignoring the current definition.
  1406. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1407. return;
  1408. }
  1409. // Fall through - the typedef name was not a builtin type.
  1410. }
  1411. // Verify the old decl was also a type.
  1412. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1413. if (!Old) {
  1414. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1415. << New->getDeclName();
  1416. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1417. if (OldD->getLocation().isValid())
  1418. Diag(OldD->getLocation(), diag::note_previous_definition);
  1419. return New->setInvalidDecl();
  1420. }
  1421. // If the old declaration is invalid, just give up here.
  1422. if (Old->isInvalidDecl())
  1423. return New->setInvalidDecl();
  1424. // If the typedef types are not identical, reject them in all languages and
  1425. // with any extensions enabled.
  1426. if (isIncompatibleTypedef(Old, New))
  1427. return;
  1428. // The types match. Link up the redeclaration chain if the old
  1429. // declaration was a typedef.
  1430. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
  1431. New->setPreviousDeclaration(Typedef);
  1432. if (getLangOpts().MicrosoftExt)
  1433. return;
  1434. if (getLangOpts().CPlusPlus) {
  1435. // C++ [dcl.typedef]p2:
  1436. // In a given non-class scope, a typedef specifier can be used to
  1437. // redefine the name of any type declared in that scope to refer
  1438. // to the type to which it already refers.
  1439. if (!isa<CXXRecordDecl>(CurContext))
  1440. return;
  1441. // C++0x [dcl.typedef]p4:
  1442. // In a given class scope, a typedef specifier can be used to redefine
  1443. // any class-name declared in that scope that is not also a typedef-name
  1444. // to refer to the type to which it already refers.
  1445. //
  1446. // This wording came in via DR424, which was a correction to the
  1447. // wording in DR56, which accidentally banned code like:
  1448. //
  1449. // struct S {
  1450. // typedef struct A { } A;
  1451. // };
  1452. //
  1453. // in the C++03 standard. We implement the C++0x semantics, which
  1454. // allow the above but disallow
  1455. //
  1456. // struct S {
  1457. // typedef int I;
  1458. // typedef int I;
  1459. // };
  1460. //
  1461. // since that was the intent of DR56.
  1462. if (!isa<TypedefNameDecl>(Old))
  1463. return;
  1464. Diag(New->getLocation(), diag::err_redefinition)
  1465. << New->getDeclName();
  1466. Diag(Old->getLocation(), diag::note_previous_definition);
  1467. return New->setInvalidDecl();
  1468. }
  1469. // Modules always permit redefinition of typedefs, as does C11.
  1470. if (getLangOpts().Modules || getLangOpts().C11)
  1471. return;
  1472. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1473. // is normally mapped to an error, but can be controlled with
  1474. // -Wtypedef-redefinition. If either the original or the redefinition is
  1475. // in a system header, don't emit this for compatibility with GCC.
  1476. if (getDiagnostics().getSuppressSystemWarnings() &&
  1477. (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1478. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1479. return;
  1480. Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
  1481. << New->getDeclName();
  1482. Diag(Old->getLocation(), diag::note_previous_definition);
  1483. return;
  1484. }
  1485. /// DeclhasAttr - returns true if decl Declaration already has the target
  1486. /// attribute.
  1487. static bool
  1488. DeclHasAttr(const Decl *D, const Attr *A) {
  1489. // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
  1490. // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
  1491. // responsible for making sure they are consistent.
  1492. const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
  1493. if (AA)
  1494. return false;
  1495. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1496. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1497. for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
  1498. if ((*i)->getKind() == A->getKind()) {
  1499. if (Ann) {
  1500. if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
  1501. return true;
  1502. continue;
  1503. }
  1504. // FIXME: Don't hardcode this check
  1505. if (OA && isa<OwnershipAttr>(*i))
  1506. return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
  1507. return true;
  1508. }
  1509. return false;
  1510. }
  1511. bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) {
  1512. InheritableAttr *NewAttr = NULL;
  1513. if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
  1514. NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  1515. AA->getIntroduced(), AA->getDeprecated(),
  1516. AA->getObsoleted(), AA->getUnavailable(),
  1517. AA->getMessage());
  1518. else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
  1519. NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility());
  1520. else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
  1521. NewAttr = mergeDLLImportAttr(D, ImportA->getRange());
  1522. else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
  1523. NewAttr = mergeDLLExportAttr(D, ExportA->getRange());
  1524. else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
  1525. NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(),
  1526. FA->getFormatIdx(), FA->getFirstArg());
  1527. else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
  1528. NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName());
  1529. else if (!DeclHasAttr(D, Attr))
  1530. NewAttr = cast<InheritableAttr>(Attr->clone(Context));
  1531. if (NewAttr) {
  1532. NewAttr->setInherited(true);
  1533. D->addAttr(NewAttr);
  1534. return true;
  1535. }
  1536. return false;
  1537. }
  1538. static const Decl *getDefinition(const Decl *D) {
  1539. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  1540. return TD->getDefinition();
  1541. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1542. return VD->getDefinition();
  1543. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1544. const FunctionDecl* Def;
  1545. if (FD->hasBody(Def))
  1546. return Def;
  1547. }
  1548. return NULL;
  1549. }
  1550. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  1551. for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
  1552. I != E; ++I) {
  1553. Attr *Attribute = *I;
  1554. if (Attribute->getKind() == Kind)
  1555. return true;
  1556. }
  1557. return false;
  1558. }
  1559. /// checkNewAttributesAfterDef - If we already have a definition, check that
  1560. /// there are no new attributes in this declaration.
  1561. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  1562. if (!New->hasAttrs())
  1563. return;
  1564. const Decl *Def = getDefinition(Old);
  1565. if (!Def || Def == New)
  1566. return;
  1567. AttrVec &NewAttributes = New->getAttrs();
  1568. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  1569. const Attr *NewAttribute = NewAttributes[I];
  1570. if (hasAttribute(Def, NewAttribute->getKind())) {
  1571. ++I;
  1572. continue; // regular attr merging will take care of validating this.
  1573. }
  1574. S.Diag(NewAttribute->getLocation(),
  1575. diag::warn_attribute_precede_definition);
  1576. S.Diag(Def->getLocation(), diag::note_previous_definition);
  1577. NewAttributes.erase(NewAttributes.begin() + I);
  1578. --E;
  1579. }
  1580. }
  1581. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  1582. void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
  1583. bool MergeDeprecation) {
  1584. // attributes declared post-definition are currently ignored
  1585. checkNewAttributesAfterDef(*this, New, Old);
  1586. if (!Old->hasAttrs())
  1587. return;
  1588. bool foundAny = New->hasAttrs();
  1589. // Ensure that any moving of objects within the allocated map is done before
  1590. // we process them.
  1591. if (!foundAny) New->setAttrs(AttrVec());
  1592. for (specific_attr_iterator<InheritableAttr>
  1593. i = Old->specific_attr_begin<InheritableAttr>(),
  1594. e = Old->specific_attr_end<InheritableAttr>();
  1595. i != e; ++i) {
  1596. // Ignore deprecated/unavailable/availability attributes if requested.
  1597. if (!MergeDeprecation &&
  1598. (isa<DeprecatedAttr>(*i) ||
  1599. isa<UnavailableAttr>(*i) ||
  1600. isa<AvailabilityAttr>(*i)))
  1601. continue;
  1602. if (mergeDeclAttribute(New, *i))
  1603. foundAny = true;
  1604. }
  1605. if (!foundAny) New->dropAttrs();
  1606. }
  1607. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  1608. /// to the new one.
  1609. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  1610. const ParmVarDecl *oldDecl,
  1611. ASTContext &C) {
  1612. if (!oldDecl->hasAttrs())
  1613. return;
  1614. bool foundAny = newDecl->hasAttrs();
  1615. // Ensure that any moving of objects within the allocated map is
  1616. // done before we process them.
  1617. if (!foundAny) newDecl->setAttrs(AttrVec());
  1618. for (specific_attr_iterator<InheritableParamAttr>
  1619. i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
  1620. e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
  1621. if (!DeclHasAttr(newDecl, *i)) {
  1622. InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
  1623. newAttr->setInherited(true);
  1624. newDecl->addAttr(newAttr);
  1625. foundAny = true;
  1626. }
  1627. }
  1628. if (!foundAny) newDecl->dropAttrs();
  1629. }
  1630. namespace {
  1631. /// Used in MergeFunctionDecl to keep track of function parameters in
  1632. /// C.
  1633. struct GNUCompatibleParamWarning {
  1634. ParmVarDecl *OldParm;
  1635. ParmVarDecl *NewParm;
  1636. QualType PromotedType;
  1637. };
  1638. }
  1639. /// getSpecialMember - get the special member enum for a method.
  1640. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  1641. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  1642. if (Ctor->isDefaultConstructor())
  1643. return Sema::CXXDefaultConstructor;
  1644. if (Ctor->isCopyConstructor())
  1645. return Sema::CXXCopyConstructor;
  1646. if (Ctor->isMoveConstructor())
  1647. return Sema::CXXMoveConstructor;
  1648. } else if (isa<CXXDestructorDecl>(MD)) {
  1649. return Sema::CXXDestructor;
  1650. } else if (MD->isCopyAssignmentOperator()) {
  1651. return Sema::CXXCopyAssignment;
  1652. } else if (MD->isMoveAssignmentOperator()) {
  1653. return Sema::CXXMoveAssignment;
  1654. }
  1655. return Sema::CXXInvalid;
  1656. }
  1657. /// canRedefineFunction - checks if a function can be redefined. Currently,
  1658. /// only extern inline functions can be redefined, and even then only in
  1659. /// GNU89 mode.
  1660. static bool canRedefineFunction(const FunctionDecl *FD,
  1661. const LangOptions& LangOpts) {
  1662. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  1663. !LangOpts.CPlusPlus &&
  1664. FD->isInlineSpecified() &&
  1665. FD->getStorageClass() == SC_Extern);
  1666. }
  1667. /// MergeFunctionDecl - We just parsed a function 'New' from
  1668. /// declarator D which has the same name and scope as a previous
  1669. /// declaration 'Old'. Figure out how to resolve this situation,
  1670. /// merging decls or emitting diagnostics as appropriate.
  1671. ///
  1672. /// In C++, New and Old must be declarations that are not
  1673. /// overloaded. Use IsOverload to determine whether New and Old are
  1674. /// overloaded, and to select the Old declaration that New should be
  1675. /// merged with.
  1676. ///
  1677. /// Returns true if there was an error, false otherwise.
  1678. bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
  1679. // Verify the old decl was also a function.
  1680. FunctionDecl *Old = 0;
  1681. if (FunctionTemplateDecl *OldFunctionTemplate
  1682. = dyn_cast<FunctionTemplateDecl>(OldD))
  1683. Old = OldFunctionTemplate->getTemplatedDecl();
  1684. else
  1685. Old = dyn_cast<FunctionDecl>(OldD);
  1686. if (!Old) {
  1687. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  1688. Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  1689. Diag(Shadow->getTargetDecl()->getLocation(),
  1690. diag::note_using_decl_target);
  1691. Diag(Shadow->getUsingDecl()->getLocation(),
  1692. diag::note_using_decl) << 0;
  1693. return true;
  1694. }
  1695. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1696. << New->getDeclName();
  1697. Diag(OldD->getLocation(), diag::note_previous_definition);
  1698. return true;
  1699. }
  1700. // Determine whether the previous declaration was a definition,
  1701. // implicit declaration, or a declaration.
  1702. diag::kind PrevDiag;
  1703. if (Old->isThisDeclarationADefinition())
  1704. PrevDiag = diag::note_previous_definition;
  1705. else if (Old->isImplicit())
  1706. PrevDiag = diag::note_previous_implicit_declaration;
  1707. else
  1708. PrevDiag = diag::note_previous_declaration;
  1709. QualType OldQType = Context.getCanonicalType(Old->getType());
  1710. QualType NewQType = Context.getCanonicalType(New->getType());
  1711. // Don't complain about this if we're in GNU89 mode and the old function
  1712. // is an extern inline function.
  1713. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  1714. New->getStorageClass() == SC_Static &&
  1715. Old->getStorageClass() != SC_Static &&
  1716. !canRedefineFunction(Old, getLangOpts())) {
  1717. if (getLangOpts().MicrosoftExt) {
  1718. Diag(New->getLocation(), diag::warn_static_non_static) << New;
  1719. Diag(Old->getLocation(), PrevDiag);
  1720. } else {
  1721. Diag(New->getLocation(), diag::err_static_non_static) << New;
  1722. Diag(Old->getLocation(), PrevDiag);
  1723. return true;
  1724. }
  1725. }
  1726. // If a function is first declared with a calling convention, but is
  1727. // later declared or defined without one, the second decl assumes the
  1728. // calling convention of the first.
  1729. //
  1730. // For the new decl, we have to look at the NON-canonical type to tell the
  1731. // difference between a function that really doesn't have a calling
  1732. // convention and one that is declared cdecl. That's because in
  1733. // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
  1734. // because it is the default calling convention.
  1735. //
  1736. // Note also that we DO NOT return at this point, because we still have
  1737. // other tests to run.
  1738. const FunctionType *OldType = cast<FunctionType>(OldQType);
  1739. const FunctionType *NewType = New->getType()->getAs<FunctionType>();
  1740. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  1741. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  1742. bool RequiresAdjustment = false;
  1743. if (OldTypeInfo.getCC() != CC_Default &&
  1744. NewTypeInfo.getCC() == CC_Default) {
  1745. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  1746. RequiresAdjustment = true;
  1747. } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
  1748. NewTypeInfo.getCC())) {
  1749. // Calling conventions really aren't compatible, so complain.
  1750. Diag(New->getLocation(), diag::err_cconv_change)
  1751. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  1752. << (OldTypeInfo.getCC() == CC_Default)
  1753. << (OldTypeInfo.getCC() == CC_Default ? "" :
  1754. FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
  1755. Diag(Old->getLocation(), diag::note_previous_declaration);
  1756. return true;
  1757. }
  1758. // FIXME: diagnose the other way around?
  1759. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  1760. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  1761. RequiresAdjustment = true;
  1762. }
  1763. // Merge regparm attribute.
  1764. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  1765. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  1766. if (NewTypeInfo.getHasRegParm()) {
  1767. Diag(New->getLocation(), diag::err_regparm_mismatch)
  1768. << NewType->getRegParmType()
  1769. << OldType->getRegParmType();
  1770. Diag(Old->getLocation(), diag::note_previous_declaration);
  1771. return true;
  1772. }
  1773. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  1774. RequiresAdjustment = true;
  1775. }
  1776. // Merge ns_returns_retained attribute.
  1777. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  1778. if (NewTypeInfo.getProducesResult()) {
  1779. Diag(New->getLocation(), diag::err_returns_retained_mismatch);
  1780. Diag(Old->getLocation(), diag::note_previous_declaration);
  1781. return true;
  1782. }
  1783. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  1784. RequiresAdjustment = true;
  1785. }
  1786. if (RequiresAdjustment) {
  1787. NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
  1788. New->setType(QualType(NewType, 0));
  1789. NewQType = Context.getCanonicalType(New->getType());
  1790. }
  1791. if (getLangOpts().CPlusPlus) {
  1792. // (C++98 13.1p2):
  1793. // Certain function declarations cannot be overloaded:
  1794. // -- Function declarations that differ only in the return type
  1795. // cannot be overloaded.
  1796. QualType OldReturnType = OldType->getResultType();
  1797. QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
  1798. QualType ResQT;
  1799. if (OldReturnType != NewReturnType) {
  1800. if (NewReturnType->isObjCObjectPointerType()
  1801. && OldReturnType->isObjCObjectPointerType())
  1802. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  1803. if (ResQT.isNull()) {
  1804. if (New->isCXXClassMember() && New->isOutOfLine())
  1805. Diag(New->getLocation(),
  1806. diag::err_member_def_does_not_match_ret_type) << New;
  1807. else
  1808. Diag(New->getLocation(), diag::err_ovl_diff_return_type);
  1809. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1810. return true;
  1811. }
  1812. else
  1813. NewQType = ResQT;
  1814. }
  1815. const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
  1816. CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
  1817. if (OldMethod && NewMethod) {
  1818. // Preserve triviality.
  1819. NewMethod->setTrivial(OldMethod->isTrivial());
  1820. // MSVC allows explicit template specialization at class scope:
  1821. // 2 CXMethodDecls referring to the same function will be injected.
  1822. // We don't want a redeclartion error.
  1823. bool IsClassScopeExplicitSpecialization =
  1824. OldMethod->isFunctionTemplateSpecialization() &&
  1825. NewMethod->isFunctionTemplateSpecialization();
  1826. bool isFriend = NewMethod->getFriendObjectKind();
  1827. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  1828. !IsClassScopeExplicitSpecialization) {
  1829. // -- Member function declarations with the same name and the
  1830. // same parameter types cannot be overloaded if any of them
  1831. // is a static member function declaration.
  1832. if (OldMethod->isStatic() || NewMethod->isStatic()) {
  1833. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  1834. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1835. return true;
  1836. }
  1837. // C++ [class.mem]p1:
  1838. // [...] A member shall not be declared twice in the
  1839. // member-specification, except that a nested class or member
  1840. // class template can be declared and then later defined.
  1841. if (ActiveTemplateInstantiations.empty()) {
  1842. unsigned NewDiag;
  1843. if (isa<CXXConstructorDecl>(OldMethod))
  1844. NewDiag = diag::err_constructor_redeclared;
  1845. else if (isa<CXXDestructorDecl>(NewMethod))
  1846. NewDiag = diag::err_destructor_redeclared;
  1847. else if (isa<CXXConversionDecl>(NewMethod))
  1848. NewDiag = diag::err_conv_function_redeclared;
  1849. else
  1850. NewDiag = diag::err_member_redeclared;
  1851. Diag(New->getLocation(), NewDiag);
  1852. } else {
  1853. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  1854. << New << New->getType();
  1855. }
  1856. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  1857. // Complain if this is an explicit declaration of a special
  1858. // member that was initially declared implicitly.
  1859. //
  1860. // As an exception, it's okay to befriend such methods in order
  1861. // to permit the implicit constructor/destructor/operator calls.
  1862. } else if (OldMethod->isImplicit()) {
  1863. if (isFriend) {
  1864. NewMethod->setImplicit();
  1865. } else {
  1866. Diag(NewMethod->getLocation(),
  1867. diag::err_definition_of_implicitly_declared_member)
  1868. << New << getSpecialMember(OldMethod);
  1869. return true;
  1870. }
  1871. } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
  1872. Diag(NewMethod->getLocation(),
  1873. diag::err_definition_of_explicitly_defaulted_member)
  1874. << getSpecialMember(OldMethod);
  1875. return true;
  1876. }
  1877. }
  1878. // (C++98 8.3.5p3):
  1879. // All declarations for a function shall agree exactly in both the
  1880. // return type and the parameter-type-list.
  1881. // We also want to respect all the extended bits except noreturn.
  1882. // noreturn should now match unless the old type info didn't have it.
  1883. QualType OldQTypeForComparison = OldQType;
  1884. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  1885. assert(OldQType == QualType(OldType, 0));
  1886. const FunctionType *OldTypeForComparison
  1887. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  1888. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  1889. assert(OldQTypeForComparison.isCanonical());
  1890. }
  1891. if (OldQTypeForComparison == NewQType)
  1892. return MergeCompatibleFunctionDecls(New, Old, S);
  1893. // Fall through for conflicting redeclarations and redefinitions.
  1894. }
  1895. // C: Function types need to be compatible, not identical. This handles
  1896. // duplicate function decls like "void f(int); void f(enum X);" properly.
  1897. if (!getLangOpts().CPlusPlus &&
  1898. Context.typesAreCompatible(OldQType, NewQType)) {
  1899. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  1900. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  1901. const FunctionProtoType *OldProto = 0;
  1902. if (isa<FunctionNoProtoType>(NewFuncType) &&
  1903. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  1904. // The old declaration provided a function prototype, but the
  1905. // new declaration does not. Merge in the prototype.
  1906. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  1907. SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
  1908. OldProto->arg_type_end());
  1909. NewQType = Context.getFunctionType(NewFuncType->getResultType(),
  1910. ParamTypes.data(), ParamTypes.size(),
  1911. OldProto->getExtProtoInfo());
  1912. New->setType(NewQType);
  1913. New->setHasInheritedPrototype();
  1914. // Synthesize a parameter for each argument type.
  1915. SmallVector<ParmVarDecl*, 16> Params;
  1916. for (FunctionProtoType::arg_type_iterator
  1917. ParamType = OldProto->arg_type_begin(),
  1918. ParamEnd = OldProto->arg_type_end();
  1919. ParamType != ParamEnd; ++ParamType) {
  1920. ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
  1921. SourceLocation(),
  1922. SourceLocation(), 0,
  1923. *ParamType, /*TInfo=*/0,
  1924. SC_None, SC_None,
  1925. 0);
  1926. Param->setScopeInfo(0, Params.size());
  1927. Param->setImplicit();
  1928. Params.push_back(Param);
  1929. }
  1930. New->setParams(Params);
  1931. }
  1932. return MergeCompatibleFunctionDecls(New, Old, S);
  1933. }
  1934. // GNU C permits a K&R definition to follow a prototype declaration
  1935. // if the declared types of the parameters in the K&R definition
  1936. // match the types in the prototype declaration, even when the
  1937. // promoted types of the parameters from the K&R definition differ
  1938. // from the types in the prototype. GCC then keeps the types from
  1939. // the prototype.
  1940. //
  1941. // If a variadic prototype is followed by a non-variadic K&R definition,
  1942. // the K&R definition becomes variadic. This is sort of an edge case, but
  1943. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  1944. // C99 6.9.1p8.
  1945. if (!getLangOpts().CPlusPlus &&
  1946. Old->hasPrototype() && !New->hasPrototype() &&
  1947. New->getType()->getAs<FunctionProtoType>() &&
  1948. Old->getNumParams() == New->getNumParams()) {
  1949. SmallVector<QualType, 16> ArgTypes;
  1950. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  1951. const FunctionProtoType *OldProto
  1952. = Old->getType()->getAs<FunctionProtoType>();
  1953. const FunctionProtoType *NewProto
  1954. = New->getType()->getAs<FunctionProtoType>();
  1955. // Determine whether this is the GNU C extension.
  1956. QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
  1957. NewProto->getResultType());
  1958. bool LooseCompatible = !MergedReturn.isNull();
  1959. for (unsigned Idx = 0, End = Old->getNumParams();
  1960. LooseCompatible && Idx != End; ++Idx) {
  1961. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  1962. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  1963. if (Context.typesAreCompatible(OldParm->getType(),
  1964. NewProto->getArgType(Idx))) {
  1965. ArgTypes.push_back(NewParm->getType());
  1966. } else if (Context.typesAreCompatible(OldParm->getType(),
  1967. NewParm->getType(),
  1968. /*CompareUnqualified=*/true)) {
  1969. GNUCompatibleParamWarning Warn
  1970. = { OldParm, NewParm, NewProto->getArgType(Idx) };
  1971. Warnings.push_back(Warn);
  1972. ArgTypes.push_back(NewParm->getType());
  1973. } else
  1974. LooseCompatible = false;
  1975. }
  1976. if (LooseCompatible) {
  1977. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  1978. Diag(Warnings[Warn].NewParm->getLocation(),
  1979. diag::ext_param_promoted_not_compatible_with_prototype)
  1980. << Warnings[Warn].PromotedType
  1981. << Warnings[Warn].OldParm->getType();
  1982. if (Warnings[Warn].OldParm->getLocation().isValid())
  1983. Diag(Warnings[Warn].OldParm->getLocation(),
  1984. diag::note_previous_declaration);
  1985. }
  1986. New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
  1987. ArgTypes.size(),
  1988. OldProto->getExtProtoInfo()));
  1989. return MergeCompatibleFunctionDecls(New, Old, S);
  1990. }
  1991. // Fall through to diagnose conflicting types.
  1992. }
  1993. // A function that has already been declared has been redeclared or defined
  1994. // with a different type- show appropriate diagnostic
  1995. if (unsigned BuiltinID = Old->getBuiltinID()) {
  1996. // The user has declared a builtin function with an incompatible
  1997. // signature.
  1998. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  1999. // The function the user is redeclaring is a library-defined
  2000. // function like 'malloc' or 'printf'. Warn about the
  2001. // redeclaration, then pretend that we don't know about this
  2002. // library built-in.
  2003. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  2004. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2005. << Old << Old->getType();
  2006. New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
  2007. Old->setInvalidDecl();
  2008. return false;
  2009. }
  2010. PrevDiag = diag::note_previous_builtin_declaration;
  2011. }
  2012. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  2013. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  2014. return true;
  2015. }
  2016. /// \brief Completes the merge of two function declarations that are
  2017. /// known to be compatible.
  2018. ///
  2019. /// This routine handles the merging of attributes and other
  2020. /// properties of function declarations form the old declaration to
  2021. /// the new declaration, once we know that New is in fact a
  2022. /// redeclaration of Old.
  2023. ///
  2024. /// \returns false
  2025. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  2026. Scope *S) {
  2027. // Merge the attributes
  2028. mergeDeclAttributes(New, Old);
  2029. // Merge the storage class.
  2030. if (Old->getStorageClass() != SC_Extern &&
  2031. Old->getStorageClass() != SC_None)
  2032. New->setStorageClass(Old->getStorageClass());
  2033. // Merge "pure" flag.
  2034. if (Old->isPure())
  2035. New->setPure();
  2036. // Merge attributes from the parameters. These can mismatch with K&R
  2037. // declarations.
  2038. if (New->getNumParams() == Old->getNumParams())
  2039. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
  2040. mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
  2041. Context);
  2042. if (getLangOpts().CPlusPlus)
  2043. return MergeCXXFunctionDecl(New, Old, S);
  2044. return false;
  2045. }
  2046. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  2047. ObjCMethodDecl *oldMethod) {
  2048. // Merge the attributes, including deprecated/unavailable
  2049. mergeDeclAttributes(newMethod, oldMethod, /* mergeDeprecation */true);
  2050. // Merge attributes from the parameters.
  2051. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  2052. oe = oldMethod->param_end();
  2053. for (ObjCMethodDecl::param_iterator
  2054. ni = newMethod->param_begin(), ne = newMethod->param_end();
  2055. ni != ne && oi != oe; ++ni, ++oi)
  2056. mergeParamDeclAttributes(*ni, *oi, Context);
  2057. CheckObjCMethodOverride(newMethod, oldMethod, true);
  2058. }
  2059. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  2060. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  2061. /// emitting diagnostics as appropriate.
  2062. ///
  2063. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  2064. /// to here in AddInitializerToDecl. We can't check them before the initializer
  2065. /// is attached.
  2066. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
  2067. if (New->isInvalidDecl() || Old->isInvalidDecl())
  2068. return;
  2069. QualType MergedT;
  2070. if (getLangOpts().CPlusPlus) {
  2071. AutoType *AT = New->getType()->getContainedAutoType();
  2072. if (AT && !AT->isDeduced()) {
  2073. // We don't know what the new type is until the initializer is attached.
  2074. return;
  2075. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  2076. // These could still be something that needs exception specs checked.
  2077. return MergeVarDeclExceptionSpecs(New, Old);
  2078. }
  2079. // C++ [basic.link]p10:
  2080. // [...] the types specified by all declarations referring to a given
  2081. // object or function shall be identical, except that declarations for an
  2082. // array object can specify array types that differ by the presence or
  2083. // absence of a major array bound (8.3.4).
  2084. else if (Old->getType()->isIncompleteArrayType() &&
  2085. New->getType()->isArrayType()) {
  2086. CanQual<ArrayType> OldArray
  2087. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  2088. CanQual<ArrayType> NewArray
  2089. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  2090. if (OldArray->getElementType() == NewArray->getElementType())
  2091. MergedT = New->getType();
  2092. } else if (Old->getType()->isArrayType() &&
  2093. New->getType()->isIncompleteArrayType()) {
  2094. CanQual<ArrayType> OldArray
  2095. = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
  2096. CanQual<ArrayType> NewArray
  2097. = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
  2098. if (OldArray->getElementType() == NewArray->getElementType())
  2099. MergedT = Old->getType();
  2100. } else if (New->getType()->isObjCObjectPointerType()
  2101. && Old->getType()->isObjCObjectPointerType()) {
  2102. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  2103. Old->getType());
  2104. }
  2105. } else {
  2106. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  2107. }
  2108. if (MergedT.isNull()) {
  2109. Diag(New->getLocation(), diag::err_redefinition_different_type)
  2110. << New->getDeclName();
  2111. Diag(Old->getLocation(), diag::note_previous_definition);
  2112. return New->setInvalidDecl();
  2113. }
  2114. New->setType(MergedT);
  2115. }
  2116. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  2117. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  2118. /// situation, merging decls or emitting diagnostics as appropriate.
  2119. ///
  2120. /// Tentative definition rules (C99 6.9.2p2) are checked by
  2121. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  2122. /// definitions here, since the initializer hasn't been attached.
  2123. ///
  2124. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  2125. // If the new decl is already invalid, don't do any other checking.
  2126. if (New->isInvalidDecl())
  2127. return;
  2128. // Verify the old decl was also a variable.
  2129. VarDecl *Old = 0;
  2130. if (!Previous.isSingleResult() ||
  2131. !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
  2132. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2133. << New->getDeclName();
  2134. Diag(Previous.getRepresentativeDecl()->getLocation(),
  2135. diag::note_previous_definition);
  2136. return New->setInvalidDecl();
  2137. }
  2138. // C++ [class.mem]p1:
  2139. // A member shall not be declared twice in the member-specification [...]
  2140. //
  2141. // Here, we need only consider static data members.
  2142. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  2143. Diag(New->getLocation(), diag::err_duplicate_member)
  2144. << New->getIdentifier();
  2145. Diag(Old->getLocation(), diag::note_previous_declaration);
  2146. New->setInvalidDecl();
  2147. }
  2148. mergeDeclAttributes(New, Old);
  2149. // Warn if an already-declared variable is made a weak_import in a subsequent
  2150. // declaration
  2151. if (New->getAttr<WeakImportAttr>() &&
  2152. Old->getStorageClass() == SC_None &&
  2153. !Old->getAttr<WeakImportAttr>()) {
  2154. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  2155. Diag(Old->getLocation(), diag::note_previous_definition);
  2156. // Remove weak_import attribute on new declaration.
  2157. New->dropAttr<WeakImportAttr>();
  2158. }
  2159. // Merge the types.
  2160. MergeVarDeclTypes(New, Old);
  2161. if (New->isInvalidDecl())
  2162. return;
  2163. // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
  2164. if (New->getStorageClass() == SC_Static &&
  2165. (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
  2166. Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
  2167. Diag(Old->getLocation(), diag::note_previous_definition);
  2168. return New->setInvalidDecl();
  2169. }
  2170. // C99 6.2.2p4:
  2171. // For an identifier declared with the storage-class specifier
  2172. // extern in a scope in which a prior declaration of that
  2173. // identifier is visible,23) if the prior declaration specifies
  2174. // internal or external linkage, the linkage of the identifier at
  2175. // the later declaration is the same as the linkage specified at
  2176. // the prior declaration. If no prior declaration is visible, or
  2177. // if the prior declaration specifies no linkage, then the
  2178. // identifier has external linkage.
  2179. if (New->hasExternalStorage() && Old->hasLinkage())
  2180. /* Okay */;
  2181. else if (New->getStorageClass() != SC_Static &&
  2182. Old->getStorageClass() == SC_Static) {
  2183. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  2184. Diag(Old->getLocation(), diag::note_previous_definition);
  2185. return New->setInvalidDecl();
  2186. }
  2187. // Check if extern is followed by non-extern and vice-versa.
  2188. if (New->hasExternalStorage() &&
  2189. !Old->hasLinkage() && Old->isLocalVarDecl()) {
  2190. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  2191. Diag(Old->getLocation(), diag::note_previous_definition);
  2192. return New->setInvalidDecl();
  2193. }
  2194. if (Old->hasExternalStorage() &&
  2195. !New->hasLinkage() && New->isLocalVarDecl()) {
  2196. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  2197. Diag(Old->getLocation(), diag::note_previous_definition);
  2198. return New->setInvalidDecl();
  2199. }
  2200. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  2201. // FIXME: The test for external storage here seems wrong? We still
  2202. // need to check for mismatches.
  2203. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  2204. // Don't complain about out-of-line definitions of static members.
  2205. !(Old->getLexicalDeclContext()->isRecord() &&
  2206. !New->getLexicalDeclContext()->isRecord())) {
  2207. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  2208. Diag(Old->getLocation(), diag::note_previous_definition);
  2209. return New->setInvalidDecl();
  2210. }
  2211. if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
  2212. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  2213. Diag(Old->getLocation(), diag::note_previous_definition);
  2214. } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
  2215. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  2216. Diag(Old->getLocation(), diag::note_previous_definition);
  2217. }
  2218. // C++ doesn't have tentative definitions, so go right ahead and check here.
  2219. const VarDecl *Def;
  2220. if (getLangOpts().CPlusPlus &&
  2221. New->isThisDeclarationADefinition() == VarDecl::Definition &&
  2222. (Def = Old->getDefinition())) {
  2223. Diag(New->getLocation(), diag::err_redefinition)
  2224. << New->getDeclName();
  2225. Diag(Def->getLocation(), diag::note_previous_definition);
  2226. New->setInvalidDecl();
  2227. return;
  2228. }
  2229. // c99 6.2.2 P4.
  2230. // For an identifier declared with the storage-class specifier extern in a
  2231. // scope in which a prior declaration of that identifier is visible, if
  2232. // the prior declaration specifies internal or external linkage, the linkage
  2233. // of the identifier at the later declaration is the same as the linkage
  2234. // specified at the prior declaration.
  2235. // FIXME. revisit this code.
  2236. if (New->hasExternalStorage() &&
  2237. Old->getLinkage() == InternalLinkage &&
  2238. New->getDeclContext() == Old->getDeclContext())
  2239. New->setStorageClass(Old->getStorageClass());
  2240. // Keep a chain of previous declarations.
  2241. New->setPreviousDeclaration(Old);
  2242. // Inherit access appropriately.
  2243. New->setAccess(Old->getAccess());
  2244. }
  2245. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2246. /// no declarator (e.g. "struct foo;") is parsed.
  2247. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2248. DeclSpec &DS) {
  2249. return ParsedFreeStandingDeclSpec(S, AS, DS,
  2250. MultiTemplateParamsArg(*this, 0, 0));
  2251. }
  2252. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  2253. /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
  2254. /// parameters to cope with template friend declarations.
  2255. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  2256. DeclSpec &DS,
  2257. MultiTemplateParamsArg TemplateParams) {
  2258. Decl *TagD = 0;
  2259. TagDecl *Tag = 0;
  2260. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  2261. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  2262. DS.getTypeSpecType() == DeclSpec::TST_union ||
  2263. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  2264. TagD = DS.getRepAsDecl();
  2265. if (!TagD) // We probably had an error
  2266. return 0;
  2267. // Note that the above type specs guarantee that the
  2268. // type rep is a Decl, whereas in many of the others
  2269. // it's a Type.
  2270. if (isa<TagDecl>(TagD))
  2271. Tag = cast<TagDecl>(TagD);
  2272. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  2273. Tag = CTD->getTemplatedDecl();
  2274. }
  2275. if (Tag) {
  2276. Tag->setFreeStanding();
  2277. if (Tag->isInvalidDecl())
  2278. return Tag;
  2279. }
  2280. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  2281. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  2282. // or incomplete types shall not be restrict-qualified."
  2283. if (TypeQuals & DeclSpec::TQ_restrict)
  2284. Diag(DS.getRestrictSpecLoc(),
  2285. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  2286. << DS.getSourceRange();
  2287. }
  2288. if (DS.isConstexprSpecified()) {
  2289. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  2290. // and definitions of functions and variables.
  2291. if (Tag)
  2292. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  2293. << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
  2294. DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
  2295. DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
  2296. else
  2297. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  2298. // Don't emit warnings after this error.
  2299. return TagD;
  2300. }
  2301. if (DS.isFriendSpecified()) {
  2302. // If we're dealing with a decl but not a TagDecl, assume that
  2303. // whatever routines created it handled the friendship aspect.
  2304. if (TagD && !Tag)
  2305. return 0;
  2306. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  2307. }
  2308. // Track whether we warned about the fact that there aren't any
  2309. // declarators.
  2310. bool emittedWarning = false;
  2311. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  2312. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  2313. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  2314. if (getLangOpts().CPlusPlus ||
  2315. Record->getDeclContext()->isRecord())
  2316. return BuildAnonymousStructOrUnion(S, DS, AS, Record);
  2317. Diag(DS.getLocStart(), diag::ext_no_declarators)
  2318. << DS.getSourceRange();
  2319. emittedWarning = true;
  2320. }
  2321. }
  2322. // Check for Microsoft C extension: anonymous struct.
  2323. if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
  2324. CurContext->isRecord() &&
  2325. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  2326. // Handle 2 kinds of anonymous struct:
  2327. // struct STRUCT;
  2328. // and
  2329. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  2330. RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
  2331. if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
  2332. (DS.getTypeSpecType() == DeclSpec::TST_typename &&
  2333. DS.getRepAsType().get()->isStructureType())) {
  2334. Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
  2335. << DS.getSourceRange();
  2336. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  2337. }
  2338. }
  2339. if (getLangOpts().CPlusPlus &&
  2340. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  2341. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  2342. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  2343. !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
  2344. Diag(Enum->getLocation(), diag::ext_no_declarators)
  2345. << DS.getSourceRange();
  2346. emittedWarning = true;
  2347. }
  2348. // Skip all the checks below if we have a type error.
  2349. if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
  2350. if (!DS.isMissingDeclaratorOk()) {
  2351. // Warn about typedefs of enums without names, since this is an
  2352. // extension in both Microsoft and GNU.
  2353. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
  2354. Tag && isa<EnumDecl>(Tag)) {
  2355. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  2356. << DS.getSourceRange();
  2357. return Tag;
  2358. }
  2359. Diag(DS.getLocStart(), diag::ext_no_declarators)
  2360. << DS.getSourceRange();
  2361. emittedWarning = true;
  2362. }
  2363. // We're going to complain about a bunch of spurious specifiers;
  2364. // only do this if we're declaring a tag, because otherwise we
  2365. // should be getting diag::ext_no_declarators.
  2366. if (emittedWarning || (TagD && TagD->isInvalidDecl()))
  2367. return TagD;
  2368. // Note that a linkage-specification sets a storage class, but
  2369. // 'extern "C" struct foo;' is actually valid and not theoretically
  2370. // useless.
  2371. if (DeclSpec::SCS scs = DS.getStorageClassSpec())
  2372. if (!DS.isExternInLinkageSpec())
  2373. Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
  2374. << DeclSpec::getSpecifierName(scs);
  2375. if (DS.isThreadSpecified())
  2376. Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
  2377. if (DS.getTypeQualifiers()) {
  2378. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2379. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
  2380. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2381. Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
  2382. // Restrict is covered above.
  2383. }
  2384. if (DS.isInlineSpecified())
  2385. Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
  2386. if (DS.isVirtualSpecified())
  2387. Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
  2388. if (DS.isExplicitSpecified())
  2389. Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
  2390. if (DS.isModulePrivateSpecified() &&
  2391. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  2392. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  2393. << Tag->getTagKind()
  2394. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  2395. // Warn about ignored type attributes, for example:
  2396. // __attribute__((aligned)) struct A;
  2397. // Attributes should be placed after tag to apply to type declaration.
  2398. if (!DS.getAttributes().empty()) {
  2399. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  2400. if (TypeSpecType == DeclSpec::TST_class ||
  2401. TypeSpecType == DeclSpec::TST_struct ||
  2402. TypeSpecType == DeclSpec::TST_union ||
  2403. TypeSpecType == DeclSpec::TST_enum) {
  2404. AttributeList* attrs = DS.getAttributes().getList();
  2405. while (attrs) {
  2406. Diag(attrs->getScopeLoc(),
  2407. diag::warn_declspec_attribute_ignored)
  2408. << attrs->getName()
  2409. << (TypeSpecType == DeclSpec::TST_class ? 0 :
  2410. TypeSpecType == DeclSpec::TST_struct ? 1 :
  2411. TypeSpecType == DeclSpec::TST_union ? 2 : 3);
  2412. attrs = attrs->getNext();
  2413. }
  2414. }
  2415. }
  2416. ActOnDocumentableDecl(TagD);
  2417. return TagD;
  2418. }
  2419. /// We are trying to inject an anonymous member into the given scope;
  2420. /// check if there's an existing declaration that can't be overloaded.
  2421. ///
  2422. /// \return true if this is a forbidden redeclaration
  2423. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  2424. Scope *S,
  2425. DeclContext *Owner,
  2426. DeclarationName Name,
  2427. SourceLocation NameLoc,
  2428. unsigned diagnostic) {
  2429. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  2430. Sema::ForRedeclaration);
  2431. if (!SemaRef.LookupName(R, S)) return false;
  2432. if (R.getAsSingle<TagDecl>())
  2433. return false;
  2434. // Pick a representative declaration.
  2435. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  2436. assert(PrevDecl && "Expected a non-null Decl");
  2437. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  2438. return false;
  2439. SemaRef.Diag(NameLoc, diagnostic) << Name;
  2440. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  2441. return true;
  2442. }
  2443. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  2444. /// anonymous struct or union AnonRecord into the owning context Owner
  2445. /// and scope S. This routine will be invoked just after we realize
  2446. /// that an unnamed union or struct is actually an anonymous union or
  2447. /// struct, e.g.,
  2448. ///
  2449. /// @code
  2450. /// union {
  2451. /// int i;
  2452. /// float f;
  2453. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  2454. /// // f into the surrounding scope.x
  2455. /// @endcode
  2456. ///
  2457. /// This routine is recursive, injecting the names of nested anonymous
  2458. /// structs/unions into the owning context and scope as well.
  2459. static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
  2460. DeclContext *Owner,
  2461. RecordDecl *AnonRecord,
  2462. AccessSpecifier AS,
  2463. SmallVector<NamedDecl*, 2> &Chaining,
  2464. bool MSAnonStruct) {
  2465. unsigned diagKind
  2466. = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
  2467. : diag::err_anonymous_struct_member_redecl;
  2468. bool Invalid = false;
  2469. // Look every FieldDecl and IndirectFieldDecl with a name.
  2470. for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
  2471. DEnd = AnonRecord->decls_end();
  2472. D != DEnd; ++D) {
  2473. if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
  2474. cast<NamedDecl>(*D)->getDeclName()) {
  2475. ValueDecl *VD = cast<ValueDecl>(*D);
  2476. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  2477. VD->getLocation(), diagKind)) {
  2478. // C++ [class.union]p2:
  2479. // The names of the members of an anonymous union shall be
  2480. // distinct from the names of any other entity in the
  2481. // scope in which the anonymous union is declared.
  2482. Invalid = true;
  2483. } else {
  2484. // C++ [class.union]p2:
  2485. // For the purpose of name lookup, after the anonymous union
  2486. // definition, the members of the anonymous union are
  2487. // considered to have been defined in the scope in which the
  2488. // anonymous union is declared.
  2489. unsigned OldChainingSize = Chaining.size();
  2490. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  2491. for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
  2492. PE = IF->chain_end(); PI != PE; ++PI)
  2493. Chaining.push_back(*PI);
  2494. else
  2495. Chaining.push_back(VD);
  2496. assert(Chaining.size() >= 2);
  2497. NamedDecl **NamedChain =
  2498. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  2499. for (unsigned i = 0; i < Chaining.size(); i++)
  2500. NamedChain[i] = Chaining[i];
  2501. IndirectFieldDecl* IndirectField =
  2502. IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
  2503. VD->getIdentifier(), VD->getType(),
  2504. NamedChain, Chaining.size());
  2505. IndirectField->setAccess(AS);
  2506. IndirectField->setImplicit();
  2507. SemaRef.PushOnScopeChains(IndirectField, S);
  2508. // That includes picking up the appropriate access specifier.
  2509. if (AS != AS_none) IndirectField->setAccess(AS);
  2510. Chaining.resize(OldChainingSize);
  2511. }
  2512. }
  2513. }
  2514. return Invalid;
  2515. }
  2516. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  2517. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  2518. /// illegal input values are mapped to SC_None.
  2519. static StorageClass
  2520. StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2521. switch (StorageClassSpec) {
  2522. case DeclSpec::SCS_unspecified: return SC_None;
  2523. case DeclSpec::SCS_extern: return SC_Extern;
  2524. case DeclSpec::SCS_static: return SC_Static;
  2525. case DeclSpec::SCS_auto: return SC_Auto;
  2526. case DeclSpec::SCS_register: return SC_Register;
  2527. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2528. // Illegal SCSs map to None: error reporting is up to the caller.
  2529. case DeclSpec::SCS_mutable: // Fall through.
  2530. case DeclSpec::SCS_typedef: return SC_None;
  2531. }
  2532. llvm_unreachable("unknown storage class specifier");
  2533. }
  2534. /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
  2535. /// a StorageClass. Any error reporting is up to the caller:
  2536. /// illegal input values are mapped to SC_None.
  2537. static StorageClass
  2538. StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
  2539. switch (StorageClassSpec) {
  2540. case DeclSpec::SCS_unspecified: return SC_None;
  2541. case DeclSpec::SCS_extern: return SC_Extern;
  2542. case DeclSpec::SCS_static: return SC_Static;
  2543. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  2544. // Illegal SCSs map to None: error reporting is up to the caller.
  2545. case DeclSpec::SCS_auto: // Fall through.
  2546. case DeclSpec::SCS_mutable: // Fall through.
  2547. case DeclSpec::SCS_register: // Fall through.
  2548. case DeclSpec::SCS_typedef: return SC_None;
  2549. }
  2550. llvm_unreachable("unknown storage class specifier");
  2551. }
  2552. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  2553. /// anonymous structure or union. Anonymous unions are a C++ feature
  2554. /// (C++ [class.union]) and a C11 feature; anonymous structures
  2555. /// are a C11 feature and GNU C++ extension.
  2556. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  2557. AccessSpecifier AS,
  2558. RecordDecl *Record) {
  2559. DeclContext *Owner = Record->getDeclContext();
  2560. // Diagnose whether this anonymous struct/union is an extension.
  2561. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  2562. Diag(Record->getLocation(), diag::ext_anonymous_union);
  2563. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  2564. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  2565. else if (!Record->isUnion() && !getLangOpts().C11)
  2566. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  2567. // C and C++ require different kinds of checks for anonymous
  2568. // structs/unions.
  2569. bool Invalid = false;
  2570. if (getLangOpts().CPlusPlus) {
  2571. const char* PrevSpec = 0;
  2572. unsigned DiagID;
  2573. if (Record->isUnion()) {
  2574. // C++ [class.union]p6:
  2575. // Anonymous unions declared in a named namespace or in the
  2576. // global namespace shall be declared static.
  2577. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  2578. (isa<TranslationUnitDecl>(Owner) ||
  2579. (isa<NamespaceDecl>(Owner) &&
  2580. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  2581. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  2582. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  2583. // Recover by adding 'static'.
  2584. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  2585. PrevSpec, DiagID);
  2586. }
  2587. // C++ [class.union]p6:
  2588. // A storage class is not allowed in a declaration of an
  2589. // anonymous union in a class scope.
  2590. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  2591. isa<RecordDecl>(Owner)) {
  2592. Diag(DS.getStorageClassSpecLoc(),
  2593. diag::err_anonymous_union_with_storage_spec)
  2594. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2595. // Recover by removing the storage specifier.
  2596. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  2597. SourceLocation(),
  2598. PrevSpec, DiagID);
  2599. }
  2600. }
  2601. // Ignore const/volatile/restrict qualifiers.
  2602. if (DS.getTypeQualifiers()) {
  2603. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  2604. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  2605. << Record->isUnion() << 0
  2606. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  2607. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  2608. Diag(DS.getVolatileSpecLoc(),
  2609. diag::ext_anonymous_struct_union_qualified)
  2610. << Record->isUnion() << 1
  2611. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  2612. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  2613. Diag(DS.getRestrictSpecLoc(),
  2614. diag::ext_anonymous_struct_union_qualified)
  2615. << Record->isUnion() << 2
  2616. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  2617. DS.ClearTypeQualifiers();
  2618. }
  2619. // C++ [class.union]p2:
  2620. // The member-specification of an anonymous union shall only
  2621. // define non-static data members. [Note: nested types and
  2622. // functions cannot be declared within an anonymous union. ]
  2623. for (DeclContext::decl_iterator Mem = Record->decls_begin(),
  2624. MemEnd = Record->decls_end();
  2625. Mem != MemEnd; ++Mem) {
  2626. if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
  2627. // C++ [class.union]p3:
  2628. // An anonymous union shall not have private or protected
  2629. // members (clause 11).
  2630. assert(FD->getAccess() != AS_none);
  2631. if (FD->getAccess() != AS_public) {
  2632. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  2633. << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
  2634. Invalid = true;
  2635. }
  2636. // C++ [class.union]p1
  2637. // An object of a class with a non-trivial constructor, a non-trivial
  2638. // copy constructor, a non-trivial destructor, or a non-trivial copy
  2639. // assignment operator cannot be a member of a union, nor can an
  2640. // array of such objects.
  2641. if (CheckNontrivialField(FD))
  2642. Invalid = true;
  2643. } else if ((*Mem)->isImplicit()) {
  2644. // Any implicit members are fine.
  2645. } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
  2646. // This is a type that showed up in an
  2647. // elaborated-type-specifier inside the anonymous struct or
  2648. // union, but which actually declares a type outside of the
  2649. // anonymous struct or union. It's okay.
  2650. } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
  2651. if (!MemRecord->isAnonymousStructOrUnion() &&
  2652. MemRecord->getDeclName()) {
  2653. // Visual C++ allows type definition in anonymous struct or union.
  2654. if (getLangOpts().MicrosoftExt)
  2655. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  2656. << (int)Record->isUnion();
  2657. else {
  2658. // This is a nested type declaration.
  2659. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  2660. << (int)Record->isUnion();
  2661. Invalid = true;
  2662. }
  2663. }
  2664. } else if (isa<AccessSpecDecl>(*Mem)) {
  2665. // Any access specifier is fine.
  2666. } else {
  2667. // We have something that isn't a non-static data
  2668. // member. Complain about it.
  2669. unsigned DK = diag::err_anonymous_record_bad_member;
  2670. if (isa<TypeDecl>(*Mem))
  2671. DK = diag::err_anonymous_record_with_type;
  2672. else if (isa<FunctionDecl>(*Mem))
  2673. DK = diag::err_anonymous_record_with_function;
  2674. else if (isa<VarDecl>(*Mem))
  2675. DK = diag::err_anonymous_record_with_static;
  2676. // Visual C++ allows type definition in anonymous struct or union.
  2677. if (getLangOpts().MicrosoftExt &&
  2678. DK == diag::err_anonymous_record_with_type)
  2679. Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
  2680. << (int)Record->isUnion();
  2681. else {
  2682. Diag((*Mem)->getLocation(), DK)
  2683. << (int)Record->isUnion();
  2684. Invalid = true;
  2685. }
  2686. }
  2687. }
  2688. }
  2689. if (!Record->isUnion() && !Owner->isRecord()) {
  2690. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  2691. << (int)getLangOpts().CPlusPlus;
  2692. Invalid = true;
  2693. }
  2694. // Mock up a declarator.
  2695. Declarator Dc(DS, Declarator::MemberContext);
  2696. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2697. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  2698. // Create a declaration for this anonymous struct/union.
  2699. NamedDecl *Anon = 0;
  2700. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  2701. Anon = FieldDecl::Create(Context, OwningClass,
  2702. DS.getLocStart(),
  2703. Record->getLocation(),
  2704. /*IdentifierInfo=*/0,
  2705. Context.getTypeDeclType(Record),
  2706. TInfo,
  2707. /*BitWidth=*/0, /*Mutable=*/false,
  2708. /*InitStyle=*/ICIS_NoInit);
  2709. Anon->setAccess(AS);
  2710. if (getLangOpts().CPlusPlus)
  2711. FieldCollector->Add(cast<FieldDecl>(Anon));
  2712. } else {
  2713. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  2714. assert(SCSpec != DeclSpec::SCS_typedef &&
  2715. "Parser allowed 'typedef' as storage class VarDecl.");
  2716. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2717. if (SCSpec == DeclSpec::SCS_mutable) {
  2718. // mutable can only appear on non-static class members, so it's always
  2719. // an error here
  2720. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  2721. Invalid = true;
  2722. SC = SC_None;
  2723. }
  2724. SCSpec = DS.getStorageClassSpecAsWritten();
  2725. VarDecl::StorageClass SCAsWritten
  2726. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  2727. Anon = VarDecl::Create(Context, Owner,
  2728. DS.getLocStart(),
  2729. Record->getLocation(), /*IdentifierInfo=*/0,
  2730. Context.getTypeDeclType(Record),
  2731. TInfo, SC, SCAsWritten);
  2732. // Default-initialize the implicit variable. This initialization will be
  2733. // trivial in almost all cases, except if a union member has an in-class
  2734. // initializer:
  2735. // union { int n = 0; };
  2736. ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
  2737. }
  2738. Anon->setImplicit();
  2739. // Add the anonymous struct/union object to the current
  2740. // context. We'll be referencing this object when we refer to one of
  2741. // its members.
  2742. Owner->addDecl(Anon);
  2743. // Inject the members of the anonymous struct/union into the owning
  2744. // context and into the identifier resolver chain for name lookup
  2745. // purposes.
  2746. SmallVector<NamedDecl*, 2> Chain;
  2747. Chain.push_back(Anon);
  2748. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
  2749. Chain, false))
  2750. Invalid = true;
  2751. // Mark this as an anonymous struct/union type. Note that we do not
  2752. // do this until after we have already checked and injected the
  2753. // members of this anonymous struct/union type, because otherwise
  2754. // the members could be injected twice: once by DeclContext when it
  2755. // builds its lookup table, and once by
  2756. // InjectAnonymousStructOrUnionMembers.
  2757. Record->setAnonymousStructOrUnion(true);
  2758. if (Invalid)
  2759. Anon->setInvalidDecl();
  2760. return Anon;
  2761. }
  2762. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  2763. /// Microsoft C anonymous structure.
  2764. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  2765. /// Example:
  2766. ///
  2767. /// struct A { int a; };
  2768. /// struct B { struct A; int b; };
  2769. ///
  2770. /// void foo() {
  2771. /// B var;
  2772. /// var.a = 3;
  2773. /// }
  2774. ///
  2775. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  2776. RecordDecl *Record) {
  2777. // If there is no Record, get the record via the typedef.
  2778. if (!Record)
  2779. Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
  2780. // Mock up a declarator.
  2781. Declarator Dc(DS, Declarator::TypeNameContext);
  2782. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  2783. assert(TInfo && "couldn't build declarator info for anonymous struct");
  2784. // Create a declaration for this anonymous struct.
  2785. NamedDecl* Anon = FieldDecl::Create(Context,
  2786. cast<RecordDecl>(CurContext),
  2787. DS.getLocStart(),
  2788. DS.getLocStart(),
  2789. /*IdentifierInfo=*/0,
  2790. Context.getTypeDeclType(Record),
  2791. TInfo,
  2792. /*BitWidth=*/0, /*Mutable=*/false,
  2793. /*InitStyle=*/ICIS_NoInit);
  2794. Anon->setImplicit();
  2795. // Add the anonymous struct object to the current context.
  2796. CurContext->addDecl(Anon);
  2797. // Inject the members of the anonymous struct into the current
  2798. // context and into the identifier resolver chain for name lookup
  2799. // purposes.
  2800. SmallVector<NamedDecl*, 2> Chain;
  2801. Chain.push_back(Anon);
  2802. RecordDecl *RecordDef = Record->getDefinition();
  2803. if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
  2804. RecordDef, AS_none,
  2805. Chain, true))
  2806. Anon->setInvalidDecl();
  2807. return Anon;
  2808. }
  2809. /// GetNameForDeclarator - Determine the full declaration name for the
  2810. /// given Declarator.
  2811. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  2812. return GetNameFromUnqualifiedId(D.getName());
  2813. }
  2814. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  2815. DeclarationNameInfo
  2816. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  2817. DeclarationNameInfo NameInfo;
  2818. NameInfo.setLoc(Name.StartLocation);
  2819. switch (Name.getKind()) {
  2820. case UnqualifiedId::IK_ImplicitSelfParam:
  2821. case UnqualifiedId::IK_Identifier:
  2822. NameInfo.setName(Name.Identifier);
  2823. NameInfo.setLoc(Name.StartLocation);
  2824. return NameInfo;
  2825. case UnqualifiedId::IK_OperatorFunctionId:
  2826. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  2827. Name.OperatorFunctionId.Operator));
  2828. NameInfo.setLoc(Name.StartLocation);
  2829. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  2830. = Name.OperatorFunctionId.SymbolLocations[0];
  2831. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  2832. = Name.EndLocation.getRawEncoding();
  2833. return NameInfo;
  2834. case UnqualifiedId::IK_LiteralOperatorId:
  2835. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  2836. Name.Identifier));
  2837. NameInfo.setLoc(Name.StartLocation);
  2838. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  2839. return NameInfo;
  2840. case UnqualifiedId::IK_ConversionFunctionId: {
  2841. TypeSourceInfo *TInfo;
  2842. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  2843. if (Ty.isNull())
  2844. return DeclarationNameInfo();
  2845. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  2846. Context.getCanonicalType(Ty)));
  2847. NameInfo.setLoc(Name.StartLocation);
  2848. NameInfo.setNamedTypeInfo(TInfo);
  2849. return NameInfo;
  2850. }
  2851. case UnqualifiedId::IK_ConstructorName: {
  2852. TypeSourceInfo *TInfo;
  2853. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  2854. if (Ty.isNull())
  2855. return DeclarationNameInfo();
  2856. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2857. Context.getCanonicalType(Ty)));
  2858. NameInfo.setLoc(Name.StartLocation);
  2859. NameInfo.setNamedTypeInfo(TInfo);
  2860. return NameInfo;
  2861. }
  2862. case UnqualifiedId::IK_ConstructorTemplateId: {
  2863. // In well-formed code, we can only have a constructor
  2864. // template-id that refers to the current context, so go there
  2865. // to find the actual type being constructed.
  2866. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  2867. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  2868. return DeclarationNameInfo();
  2869. // Determine the type of the class being constructed.
  2870. QualType CurClassType = Context.getTypeDeclType(CurClass);
  2871. // FIXME: Check two things: that the template-id names the same type as
  2872. // CurClassType, and that the template-id does not occur when the name
  2873. // was qualified.
  2874. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  2875. Context.getCanonicalType(CurClassType)));
  2876. NameInfo.setLoc(Name.StartLocation);
  2877. // FIXME: should we retrieve TypeSourceInfo?
  2878. NameInfo.setNamedTypeInfo(0);
  2879. return NameInfo;
  2880. }
  2881. case UnqualifiedId::IK_DestructorName: {
  2882. TypeSourceInfo *TInfo;
  2883. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  2884. if (Ty.isNull())
  2885. return DeclarationNameInfo();
  2886. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  2887. Context.getCanonicalType(Ty)));
  2888. NameInfo.setLoc(Name.StartLocation);
  2889. NameInfo.setNamedTypeInfo(TInfo);
  2890. return NameInfo;
  2891. }
  2892. case UnqualifiedId::IK_TemplateId: {
  2893. TemplateName TName = Name.TemplateId->Template.get();
  2894. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  2895. return Context.getNameForTemplate(TName, TNameLoc);
  2896. }
  2897. } // switch (Name.getKind())
  2898. llvm_unreachable("Unknown name kind");
  2899. }
  2900. static QualType getCoreType(QualType Ty) {
  2901. do {
  2902. if (Ty->isPointerType() || Ty->isReferenceType())
  2903. Ty = Ty->getPointeeType();
  2904. else if (Ty->isArrayType())
  2905. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  2906. else
  2907. return Ty.withoutLocalFastQualifiers();
  2908. } while (true);
  2909. }
  2910. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  2911. /// and Definition have "nearly" matching parameters. This heuristic is
  2912. /// used to improve diagnostics in the case where an out-of-line function
  2913. /// definition doesn't match any declaration within the class or namespace.
  2914. /// Also sets Params to the list of indices to the parameters that differ
  2915. /// between the declaration and the definition. If hasSimilarParameters
  2916. /// returns true and Params is empty, then all of the parameters match.
  2917. static bool hasSimilarParameters(ASTContext &Context,
  2918. FunctionDecl *Declaration,
  2919. FunctionDecl *Definition,
  2920. llvm::SmallVectorImpl<unsigned> &Params) {
  2921. Params.clear();
  2922. if (Declaration->param_size() != Definition->param_size())
  2923. return false;
  2924. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  2925. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  2926. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  2927. // The parameter types are identical
  2928. if (Context.hasSameType(DefParamTy, DeclParamTy))
  2929. continue;
  2930. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  2931. QualType DefParamBaseTy = getCoreType(DefParamTy);
  2932. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  2933. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  2934. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  2935. (DeclTyName && DeclTyName == DefTyName))
  2936. Params.push_back(Idx);
  2937. else // The two parameters aren't even close
  2938. return false;
  2939. }
  2940. return true;
  2941. }
  2942. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  2943. /// declarator needs to be rebuilt in the current instantiation.
  2944. /// Any bits of declarator which appear before the name are valid for
  2945. /// consideration here. That's specifically the type in the decl spec
  2946. /// and the base type in any member-pointer chunks.
  2947. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  2948. DeclarationName Name) {
  2949. // The types we specifically need to rebuild are:
  2950. // - typenames, typeofs, and decltypes
  2951. // - types which will become injected class names
  2952. // Of course, we also need to rebuild any type referencing such a
  2953. // type. It's safest to just say "dependent", but we call out a
  2954. // few cases here.
  2955. DeclSpec &DS = D.getMutableDeclSpec();
  2956. switch (DS.getTypeSpecType()) {
  2957. case DeclSpec::TST_typename:
  2958. case DeclSpec::TST_typeofType:
  2959. case DeclSpec::TST_decltype:
  2960. case DeclSpec::TST_underlyingType:
  2961. case DeclSpec::TST_atomic: {
  2962. // Grab the type from the parser.
  2963. TypeSourceInfo *TSI = 0;
  2964. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  2965. if (T.isNull() || !T->isDependentType()) break;
  2966. // Make sure there's a type source info. This isn't really much
  2967. // of a waste; most dependent types should have type source info
  2968. // attached already.
  2969. if (!TSI)
  2970. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  2971. // Rebuild the type in the current instantiation.
  2972. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  2973. if (!TSI) return true;
  2974. // Store the new type back in the decl spec.
  2975. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  2976. DS.UpdateTypeRep(LocType);
  2977. break;
  2978. }
  2979. case DeclSpec::TST_typeofExpr: {
  2980. Expr *E = DS.getRepAsExpr();
  2981. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  2982. if (Result.isInvalid()) return true;
  2983. DS.UpdateExprRep(Result.get());
  2984. break;
  2985. }
  2986. default:
  2987. // Nothing to do for these decl specs.
  2988. break;
  2989. }
  2990. // It doesn't matter what order we do this in.
  2991. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  2992. DeclaratorChunk &Chunk = D.getTypeObject(I);
  2993. // The only type information in the declarator which can come
  2994. // before the declaration name is the base type of a member
  2995. // pointer.
  2996. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  2997. continue;
  2998. // Rebuild the scope specifier in-place.
  2999. CXXScopeSpec &SS = Chunk.Mem.Scope();
  3000. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  3001. return true;
  3002. }
  3003. return false;
  3004. }
  3005. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  3006. D.setFunctionDefinitionKind(FDK_Declaration);
  3007. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
  3008. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  3009. Dcl && Dcl->getDeclContext()->isFileContext())
  3010. Dcl->setTopLevelDeclInObjCContainer();
  3011. return Dcl;
  3012. }
  3013. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  3014. /// If T is the name of a class, then each of the following shall have a
  3015. /// name different from T:
  3016. /// - every static data member of class T;
  3017. /// - every member function of class T
  3018. /// - every member of class T that is itself a type;
  3019. /// \returns true if the declaration name violates these rules.
  3020. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  3021. DeclarationNameInfo NameInfo) {
  3022. DeclarationName Name = NameInfo.getName();
  3023. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  3024. if (Record->getIdentifier() && Record->getDeclName() == Name) {
  3025. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  3026. return true;
  3027. }
  3028. return false;
  3029. }
  3030. /// \brief Diagnose a declaration whose declarator-id has the given
  3031. /// nested-name-specifier.
  3032. ///
  3033. /// \param SS The nested-name-specifier of the declarator-id.
  3034. ///
  3035. /// \param DC The declaration context to which the nested-name-specifier
  3036. /// resolves.
  3037. ///
  3038. /// \param Name The name of the entity being declared.
  3039. ///
  3040. /// \param Loc The location of the name of the entity being declared.
  3041. ///
  3042. /// \returns true if we cannot safely recover from this error, false otherwise.
  3043. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  3044. DeclarationName Name,
  3045. SourceLocation Loc) {
  3046. DeclContext *Cur = CurContext;
  3047. while (isa<LinkageSpecDecl>(Cur))
  3048. Cur = Cur->getParent();
  3049. // C++ [dcl.meaning]p1:
  3050. // A declarator-id shall not be qualified except for the definition
  3051. // of a member function (9.3) or static data member (9.4) outside of
  3052. // its class, the definition or explicit instantiation of a function
  3053. // or variable member of a namespace outside of its namespace, or the
  3054. // definition of an explicit specialization outside of its namespace,
  3055. // or the declaration of a friend function that is a member of
  3056. // another class or namespace (11.3). [...]
  3057. // The user provided a superfluous scope specifier that refers back to the
  3058. // class or namespaces in which the entity is already declared.
  3059. //
  3060. // class X {
  3061. // void X::f();
  3062. // };
  3063. if (Cur->Equals(DC)) {
  3064. Diag(Loc, diag::warn_member_extra_qualification)
  3065. << Name << FixItHint::CreateRemoval(SS.getRange());
  3066. SS.clear();
  3067. return false;
  3068. }
  3069. // Check whether the qualifying scope encloses the scope of the original
  3070. // declaration.
  3071. if (!Cur->Encloses(DC)) {
  3072. if (Cur->isRecord())
  3073. Diag(Loc, diag::err_member_qualification)
  3074. << Name << SS.getRange();
  3075. else if (isa<TranslationUnitDecl>(DC))
  3076. Diag(Loc, diag::err_invalid_declarator_global_scope)
  3077. << Name << SS.getRange();
  3078. else if (isa<FunctionDecl>(Cur))
  3079. Diag(Loc, diag::err_invalid_declarator_in_function)
  3080. << Name << SS.getRange();
  3081. else
  3082. Diag(Loc, diag::err_invalid_declarator_scope)
  3083. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  3084. return true;
  3085. }
  3086. if (Cur->isRecord()) {
  3087. // Cannot qualify members within a class.
  3088. Diag(Loc, diag::err_member_qualification)
  3089. << Name << SS.getRange();
  3090. SS.clear();
  3091. // C++ constructors and destructors with incorrect scopes can break
  3092. // our AST invariants by having the wrong underlying types. If
  3093. // that's the case, then drop this declaration entirely.
  3094. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3095. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  3096. !Context.hasSameType(Name.getCXXNameType(),
  3097. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  3098. return true;
  3099. return false;
  3100. }
  3101. // C++11 [dcl.meaning]p1:
  3102. // [...] "The nested-name-specifier of the qualified declarator-id shall
  3103. // not begin with a decltype-specifer"
  3104. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  3105. while (SpecLoc.getPrefix())
  3106. SpecLoc = SpecLoc.getPrefix();
  3107. if (dyn_cast_or_null<DecltypeType>(
  3108. SpecLoc.getNestedNameSpecifier()->getAsType()))
  3109. Diag(Loc, diag::err_decltype_in_declarator)
  3110. << SpecLoc.getTypeLoc().getSourceRange();
  3111. return false;
  3112. }
  3113. Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  3114. MultiTemplateParamsArg TemplateParamLists) {
  3115. // TODO: consider using NameInfo for diagnostic.
  3116. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  3117. DeclarationName Name = NameInfo.getName();
  3118. // All of these full declarators require an identifier. If it doesn't have
  3119. // one, the ParsedFreeStandingDeclSpec action should be used.
  3120. if (!Name) {
  3121. if (!D.isInvalidType()) // Reject this if we think it is valid.
  3122. Diag(D.getDeclSpec().getLocStart(),
  3123. diag::err_declarator_need_ident)
  3124. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  3125. return 0;
  3126. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  3127. return 0;
  3128. // The scope passed in may not be a decl scope. Zip up the scope tree until
  3129. // we find one that is.
  3130. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  3131. (S->getFlags() & Scope::TemplateParamScope) != 0)
  3132. S = S->getParent();
  3133. DeclContext *DC = CurContext;
  3134. if (D.getCXXScopeSpec().isInvalid())
  3135. D.setInvalidType();
  3136. else if (D.getCXXScopeSpec().isSet()) {
  3137. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  3138. UPPC_DeclarationQualifier))
  3139. return 0;
  3140. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  3141. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  3142. if (!DC) {
  3143. // If we could not compute the declaration context, it's because the
  3144. // declaration context is dependent but does not refer to a class,
  3145. // class template, or class template partial specialization. Complain
  3146. // and return early, to avoid the coming semantic disaster.
  3147. Diag(D.getIdentifierLoc(),
  3148. diag::err_template_qualified_declarator_no_match)
  3149. << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
  3150. << D.getCXXScopeSpec().getRange();
  3151. return 0;
  3152. }
  3153. bool IsDependentContext = DC->isDependentContext();
  3154. if (!IsDependentContext &&
  3155. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  3156. return 0;
  3157. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  3158. Diag(D.getIdentifierLoc(),
  3159. diag::err_member_def_undefined_record)
  3160. << Name << DC << D.getCXXScopeSpec().getRange();
  3161. D.setInvalidType();
  3162. } else if (!D.getDeclSpec().isFriendSpecified()) {
  3163. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  3164. Name, D.getIdentifierLoc())) {
  3165. if (DC->isRecord())
  3166. return 0;
  3167. D.setInvalidType();
  3168. }
  3169. }
  3170. // Check whether we need to rebuild the type of the given
  3171. // declaration in the current instantiation.
  3172. if (EnteringContext && IsDependentContext &&
  3173. TemplateParamLists.size() != 0) {
  3174. ContextRAII SavedContext(*this, DC);
  3175. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  3176. D.setInvalidType();
  3177. }
  3178. }
  3179. if (DiagnoseClassNameShadow(DC, NameInfo))
  3180. // If this is a typedef, we'll end up spewing multiple diagnostics.
  3181. // Just return early; it's safer.
  3182. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3183. return 0;
  3184. NamedDecl *New;
  3185. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  3186. QualType R = TInfo->getType();
  3187. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  3188. UPPC_DeclarationType))
  3189. D.setInvalidType();
  3190. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  3191. ForRedeclaration);
  3192. // See if this is a redefinition of a variable in the same scope.
  3193. if (!D.getCXXScopeSpec().isSet()) {
  3194. bool IsLinkageLookup = false;
  3195. // If the declaration we're planning to build will be a function
  3196. // or object with linkage, then look for another declaration with
  3197. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  3198. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  3199. /* Do nothing*/;
  3200. else if (R->isFunctionType()) {
  3201. if (CurContext->isFunctionOrMethod() ||
  3202. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3203. IsLinkageLookup = true;
  3204. } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
  3205. IsLinkageLookup = true;
  3206. else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  3207. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  3208. IsLinkageLookup = true;
  3209. if (IsLinkageLookup)
  3210. Previous.clear(LookupRedeclarationWithLinkage);
  3211. LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
  3212. } else { // Something like "int foo::x;"
  3213. LookupQualifiedName(Previous, DC);
  3214. // C++ [dcl.meaning]p1:
  3215. // When the declarator-id is qualified, the declaration shall refer to a
  3216. // previously declared member of the class or namespace to which the
  3217. // qualifier refers (or, in the case of a namespace, of an element of the
  3218. // inline namespace set of that namespace (7.3.1)) or to a specialization
  3219. // thereof; [...]
  3220. //
  3221. // Note that we already checked the context above, and that we do not have
  3222. // enough information to make sure that Previous contains the declaration
  3223. // we want to match. For example, given:
  3224. //
  3225. // class X {
  3226. // void f();
  3227. // void f(float);
  3228. // };
  3229. //
  3230. // void X::f(int) { } // ill-formed
  3231. //
  3232. // In this case, Previous will point to the overload set
  3233. // containing the two f's declared in X, but neither of them
  3234. // matches.
  3235. // C++ [dcl.meaning]p1:
  3236. // [...] the member shall not merely have been introduced by a
  3237. // using-declaration in the scope of the class or namespace nominated by
  3238. // the nested-name-specifier of the declarator-id.
  3239. RemoveUsingDecls(Previous);
  3240. }
  3241. if (Previous.isSingleResult() &&
  3242. Previous.getFoundDecl()->isTemplateParameter()) {
  3243. // Maybe we will complain about the shadowed template parameter.
  3244. if (!D.isInvalidType())
  3245. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  3246. Previous.getFoundDecl());
  3247. // Just pretend that we didn't see the previous declaration.
  3248. Previous.clear();
  3249. }
  3250. // In C++, the previous declaration we find might be a tag type
  3251. // (class or enum). In this case, the new declaration will hide the
  3252. // tag type. Note that this does does not apply if we're declaring a
  3253. // typedef (C++ [dcl.typedef]p4).
  3254. if (Previous.isSingleTagDecl() &&
  3255. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
  3256. Previous.clear();
  3257. bool AddToScope = true;
  3258. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3259. if (TemplateParamLists.size()) {
  3260. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  3261. return 0;
  3262. }
  3263. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  3264. } else if (R->isFunctionType()) {
  3265. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  3266. TemplateParamLists,
  3267. AddToScope);
  3268. } else {
  3269. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
  3270. TemplateParamLists);
  3271. }
  3272. if (New == 0)
  3273. return 0;
  3274. // If this has an identifier and is not an invalid redeclaration or
  3275. // function template specialization, add it to the scope stack.
  3276. if (New->getDeclName() && AddToScope &&
  3277. !(D.isRedeclaration() && New->isInvalidDecl()))
  3278. PushOnScopeChains(New, S);
  3279. return New;
  3280. }
  3281. /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
  3282. /// types into constant array types in certain situations which would otherwise
  3283. /// be errors (for GCC compatibility).
  3284. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  3285. ASTContext &Context,
  3286. bool &SizeIsNegative,
  3287. llvm::APSInt &Oversized) {
  3288. // This method tries to turn a variable array into a constant
  3289. // array even when the size isn't an ICE. This is necessary
  3290. // for compatibility with code that depends on gcc's buggy
  3291. // constant expression folding, like struct {char x[(int)(char*)2];}
  3292. SizeIsNegative = false;
  3293. Oversized = 0;
  3294. if (T->isDependentType())
  3295. return QualType();
  3296. QualifierCollector Qs;
  3297. const Type *Ty = Qs.strip(T);
  3298. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  3299. QualType Pointee = PTy->getPointeeType();
  3300. QualType FixedType =
  3301. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  3302. Oversized);
  3303. if (FixedType.isNull()) return FixedType;
  3304. FixedType = Context.getPointerType(FixedType);
  3305. return Qs.apply(Context, FixedType);
  3306. }
  3307. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  3308. QualType Inner = PTy->getInnerType();
  3309. QualType FixedType =
  3310. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  3311. Oversized);
  3312. if (FixedType.isNull()) return FixedType;
  3313. FixedType = Context.getParenType(FixedType);
  3314. return Qs.apply(Context, FixedType);
  3315. }
  3316. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  3317. if (!VLATy)
  3318. return QualType();
  3319. // FIXME: We should probably handle this case
  3320. if (VLATy->getElementType()->isVariablyModifiedType())
  3321. return QualType();
  3322. llvm::APSInt Res;
  3323. if (!VLATy->getSizeExpr() ||
  3324. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  3325. return QualType();
  3326. // Check whether the array size is negative.
  3327. if (Res.isSigned() && Res.isNegative()) {
  3328. SizeIsNegative = true;
  3329. return QualType();
  3330. }
  3331. // Check whether the array is too large to be addressed.
  3332. unsigned ActiveSizeBits
  3333. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  3334. Res);
  3335. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  3336. Oversized = Res;
  3337. return QualType();
  3338. }
  3339. return Context.getConstantArrayType(VLATy->getElementType(),
  3340. Res, ArrayType::Normal, 0);
  3341. }
  3342. /// \brief Register the given locally-scoped external C declaration so
  3343. /// that it can be found later for redeclarations
  3344. void
  3345. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
  3346. const LookupResult &Previous,
  3347. Scope *S) {
  3348. assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
  3349. "Decl is not a locally-scoped decl!");
  3350. // Note that we have a locally-scoped external with this name.
  3351. LocallyScopedExternalDecls[ND->getDeclName()] = ND;
  3352. if (!Previous.isSingleResult())
  3353. return;
  3354. NamedDecl *PrevDecl = Previous.getFoundDecl();
  3355. // If there was a previous declaration of this variable, it may be
  3356. // in our identifier chain. Update the identifier chain with the new
  3357. // declaration.
  3358. if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
  3359. // The previous declaration was found on the identifer resolver
  3360. // chain, so remove it from its scope.
  3361. if (S->isDeclScope(PrevDecl)) {
  3362. // Special case for redeclarations in the SAME scope.
  3363. // Because this declaration is going to be added to the identifier chain
  3364. // later, we should temporarily take it OFF the chain.
  3365. IdResolver.RemoveDecl(ND);
  3366. } else {
  3367. // Find the scope for the original declaration.
  3368. while (S && !S->isDeclScope(PrevDecl))
  3369. S = S->getParent();
  3370. }
  3371. if (S)
  3372. S->RemoveDecl(PrevDecl);
  3373. }
  3374. }
  3375. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
  3376. Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
  3377. if (ExternalSource) {
  3378. // Load locally-scoped external decls from the external source.
  3379. SmallVector<NamedDecl *, 4> Decls;
  3380. ExternalSource->ReadLocallyScopedExternalDecls(Decls);
  3381. for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
  3382. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  3383. = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
  3384. if (Pos == LocallyScopedExternalDecls.end())
  3385. LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
  3386. }
  3387. }
  3388. return LocallyScopedExternalDecls.find(Name);
  3389. }
  3390. /// \brief Diagnose function specifiers on a declaration of an identifier that
  3391. /// does not identify a function.
  3392. void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
  3393. // FIXME: We should probably indicate the identifier in question to avoid
  3394. // confusion for constructs like "inline int a(), b;"
  3395. if (D.getDeclSpec().isInlineSpecified())
  3396. Diag(D.getDeclSpec().getInlineSpecLoc(),
  3397. diag::err_inline_non_function);
  3398. if (D.getDeclSpec().isVirtualSpecified())
  3399. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  3400. diag::err_virtual_non_function);
  3401. if (D.getDeclSpec().isExplicitSpecified())
  3402. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  3403. diag::err_explicit_non_function);
  3404. }
  3405. NamedDecl*
  3406. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  3407. TypeSourceInfo *TInfo, LookupResult &Previous) {
  3408. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  3409. if (D.getCXXScopeSpec().isSet()) {
  3410. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  3411. << D.getCXXScopeSpec().getRange();
  3412. D.setInvalidType();
  3413. // Pretend we didn't see the scope specifier.
  3414. DC = CurContext;
  3415. Previous.clear();
  3416. }
  3417. if (getLangOpts().CPlusPlus) {
  3418. // Check that there are no default arguments (C++ only).
  3419. CheckExtraCXXDefaultArguments(D);
  3420. }
  3421. DiagnoseFunctionSpecifiers(D);
  3422. if (D.getDeclSpec().isThreadSpecified())
  3423. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  3424. if (D.getDeclSpec().isConstexprSpecified())
  3425. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  3426. << 1;
  3427. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  3428. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  3429. << D.getName().getSourceRange();
  3430. return 0;
  3431. }
  3432. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  3433. if (!NewTD) return 0;
  3434. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3435. ProcessDeclAttributes(S, NewTD, D);
  3436. CheckTypedefForVariablyModifiedType(S, NewTD);
  3437. bool Redeclaration = D.isRedeclaration();
  3438. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  3439. D.setRedeclaration(Redeclaration);
  3440. return ND;
  3441. }
  3442. void
  3443. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  3444. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  3445. // then it shall have block scope.
  3446. // Note that variably modified types must be fixed before merging the decl so
  3447. // that redeclarations will match.
  3448. QualType T = NewTD->getUnderlyingType();
  3449. if (T->isVariablyModifiedType()) {
  3450. getCurFunction()->setHasBranchProtectedScope();
  3451. if (S->getFnParent() == 0) {
  3452. bool SizeIsNegative;
  3453. llvm::APSInt Oversized;
  3454. QualType FixedTy =
  3455. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3456. Oversized);
  3457. if (!FixedTy.isNull()) {
  3458. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  3459. NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
  3460. } else {
  3461. if (SizeIsNegative)
  3462. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  3463. else if (T->isVariableArrayType())
  3464. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  3465. else if (Oversized.getBoolValue())
  3466. Diag(NewTD->getLocation(), diag::err_array_too_large)
  3467. << Oversized.toString(10);
  3468. else
  3469. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  3470. NewTD->setInvalidDecl();
  3471. }
  3472. }
  3473. }
  3474. }
  3475. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  3476. /// declares a typedef-name, either using the 'typedef' type specifier or via
  3477. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  3478. NamedDecl*
  3479. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  3480. LookupResult &Previous, bool &Redeclaration) {
  3481. // Merge the decl with the existing one if appropriate. If the decl is
  3482. // in an outer scope, it isn't the same thing.
  3483. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
  3484. /*ExplicitInstantiationOrSpecialization=*/false);
  3485. if (!Previous.empty()) {
  3486. Redeclaration = true;
  3487. MergeTypedefNameDecl(NewTD, Previous);
  3488. }
  3489. // If this is the C FILE type, notify the AST context.
  3490. if (IdentifierInfo *II = NewTD->getIdentifier())
  3491. if (!NewTD->isInvalidDecl() &&
  3492. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  3493. if (II->isStr("FILE"))
  3494. Context.setFILEDecl(NewTD);
  3495. else if (II->isStr("jmp_buf"))
  3496. Context.setjmp_bufDecl(NewTD);
  3497. else if (II->isStr("sigjmp_buf"))
  3498. Context.setsigjmp_bufDecl(NewTD);
  3499. else if (II->isStr("ucontext_t"))
  3500. Context.setucontext_tDecl(NewTD);
  3501. }
  3502. return NewTD;
  3503. }
  3504. /// \brief Determines whether the given declaration is an out-of-scope
  3505. /// previous declaration.
  3506. ///
  3507. /// This routine should be invoked when name lookup has found a
  3508. /// previous declaration (PrevDecl) that is not in the scope where a
  3509. /// new declaration by the same name is being introduced. If the new
  3510. /// declaration occurs in a local scope, previous declarations with
  3511. /// linkage may still be considered previous declarations (C99
  3512. /// 6.2.2p4-5, C++ [basic.link]p6).
  3513. ///
  3514. /// \param PrevDecl the previous declaration found by name
  3515. /// lookup
  3516. ///
  3517. /// \param DC the context in which the new declaration is being
  3518. /// declared.
  3519. ///
  3520. /// \returns true if PrevDecl is an out-of-scope previous declaration
  3521. /// for a new delcaration with the same name.
  3522. static bool
  3523. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  3524. ASTContext &Context) {
  3525. if (!PrevDecl)
  3526. return false;
  3527. if (!PrevDecl->hasLinkage())
  3528. return false;
  3529. if (Context.getLangOpts().CPlusPlus) {
  3530. // C++ [basic.link]p6:
  3531. // If there is a visible declaration of an entity with linkage
  3532. // having the same name and type, ignoring entities declared
  3533. // outside the innermost enclosing namespace scope, the block
  3534. // scope declaration declares that same entity and receives the
  3535. // linkage of the previous declaration.
  3536. DeclContext *OuterContext = DC->getRedeclContext();
  3537. if (!OuterContext->isFunctionOrMethod())
  3538. // This rule only applies to block-scope declarations.
  3539. return false;
  3540. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  3541. if (PrevOuterContext->isRecord())
  3542. // We found a member function: ignore it.
  3543. return false;
  3544. // Find the innermost enclosing namespace for the new and
  3545. // previous declarations.
  3546. OuterContext = OuterContext->getEnclosingNamespaceContext();
  3547. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  3548. // The previous declaration is in a different namespace, so it
  3549. // isn't the same function.
  3550. if (!OuterContext->Equals(PrevOuterContext))
  3551. return false;
  3552. }
  3553. return true;
  3554. }
  3555. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  3556. CXXScopeSpec &SS = D.getCXXScopeSpec();
  3557. if (!SS.isSet()) return;
  3558. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  3559. }
  3560. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  3561. QualType type = decl->getType();
  3562. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  3563. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  3564. // Various kinds of declaration aren't allowed to be __autoreleasing.
  3565. unsigned kind = -1U;
  3566. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3567. if (var->hasAttr<BlocksAttr>())
  3568. kind = 0; // __block
  3569. else if (!var->hasLocalStorage())
  3570. kind = 1; // global
  3571. } else if (isa<ObjCIvarDecl>(decl)) {
  3572. kind = 3; // ivar
  3573. } else if (isa<FieldDecl>(decl)) {
  3574. kind = 2; // field
  3575. }
  3576. if (kind != -1U) {
  3577. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  3578. << kind;
  3579. }
  3580. } else if (lifetime == Qualifiers::OCL_None) {
  3581. // Try to infer lifetime.
  3582. if (!type->isObjCLifetimeType())
  3583. return false;
  3584. lifetime = type->getObjCARCImplicitLifetime();
  3585. type = Context.getLifetimeQualifiedType(type, lifetime);
  3586. decl->setType(type);
  3587. }
  3588. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  3589. // Thread-local variables cannot have lifetime.
  3590. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  3591. var->isThreadSpecified()) {
  3592. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  3593. << var->getType();
  3594. return true;
  3595. }
  3596. }
  3597. return false;
  3598. }
  3599. NamedDecl*
  3600. Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  3601. TypeSourceInfo *TInfo, LookupResult &Previous,
  3602. MultiTemplateParamsArg TemplateParamLists) {
  3603. QualType R = TInfo->getType();
  3604. DeclarationName Name = GetNameForDeclarator(D).getName();
  3605. // Check that there are no default arguments (C++ only).
  3606. if (getLangOpts().CPlusPlus)
  3607. CheckExtraCXXDefaultArguments(D);
  3608. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  3609. assert(SCSpec != DeclSpec::SCS_typedef &&
  3610. "Parser allowed 'typedef' as storage class VarDecl.");
  3611. VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3612. if (SCSpec == DeclSpec::SCS_mutable) {
  3613. // mutable can only appear on non-static class members, so it's always
  3614. // an error here
  3615. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  3616. D.setInvalidType();
  3617. SC = SC_None;
  3618. }
  3619. SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  3620. VarDecl::StorageClass SCAsWritten
  3621. = StorageClassSpecToVarDeclStorageClass(SCSpec);
  3622. IdentifierInfo *II = Name.getAsIdentifierInfo();
  3623. if (!II) {
  3624. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
  3625. << Name;
  3626. return 0;
  3627. }
  3628. DiagnoseFunctionSpecifiers(D);
  3629. if (!DC->isRecord() && S->getFnParent() == 0) {
  3630. // C99 6.9p2: The storage-class specifiers auto and register shall not
  3631. // appear in the declaration specifiers in an external declaration.
  3632. if (SC == SC_Auto || SC == SC_Register) {
  3633. // If this is a register variable with an asm label specified, then this
  3634. // is a GNU extension.
  3635. if (SC == SC_Register && D.getAsmLabel())
  3636. Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
  3637. else
  3638. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  3639. D.setInvalidType();
  3640. }
  3641. }
  3642. if (getLangOpts().OpenCL) {
  3643. // Set up the special work-group-local storage class for variables in the
  3644. // OpenCL __local address space.
  3645. if (R.getAddressSpace() == LangAS::opencl_local)
  3646. SC = SC_OpenCLWorkGroupLocal;
  3647. }
  3648. bool isExplicitSpecialization = false;
  3649. VarDecl *NewVD;
  3650. if (!getLangOpts().CPlusPlus) {
  3651. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  3652. D.getIdentifierLoc(), II,
  3653. R, TInfo, SC, SCAsWritten);
  3654. if (D.isInvalidType())
  3655. NewVD->setInvalidDecl();
  3656. } else {
  3657. if (DC->isRecord() && !CurContext->isRecord()) {
  3658. // This is an out-of-line definition of a static data member.
  3659. if (SC == SC_Static) {
  3660. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  3661. diag::err_static_out_of_line)
  3662. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  3663. } else if (SC == SC_None)
  3664. SC = SC_Static;
  3665. }
  3666. if (SC == SC_Static && CurContext->isRecord()) {
  3667. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  3668. if (RD->isLocalClass())
  3669. Diag(D.getIdentifierLoc(),
  3670. diag::err_static_data_member_not_allowed_in_local_class)
  3671. << Name << RD->getDeclName();
  3672. // C++98 [class.union]p1: If a union contains a static data member,
  3673. // the program is ill-formed. C++11 drops this restriction.
  3674. if (RD->isUnion())
  3675. Diag(D.getIdentifierLoc(),
  3676. getLangOpts().CPlusPlus0x
  3677. ? diag::warn_cxx98_compat_static_data_member_in_union
  3678. : diag::ext_static_data_member_in_union) << Name;
  3679. // We conservatively disallow static data members in anonymous structs.
  3680. else if (!RD->getDeclName())
  3681. Diag(D.getIdentifierLoc(),
  3682. diag::err_static_data_member_not_allowed_in_anon_struct)
  3683. << Name << RD->isUnion();
  3684. }
  3685. }
  3686. // Match up the template parameter lists with the scope specifier, then
  3687. // determine whether we have a template or a template specialization.
  3688. isExplicitSpecialization = false;
  3689. bool Invalid = false;
  3690. if (TemplateParameterList *TemplateParams
  3691. = MatchTemplateParametersToScopeSpecifier(
  3692. D.getDeclSpec().getLocStart(),
  3693. D.getIdentifierLoc(),
  3694. D.getCXXScopeSpec(),
  3695. TemplateParamLists.get(),
  3696. TemplateParamLists.size(),
  3697. /*never a friend*/ false,
  3698. isExplicitSpecialization,
  3699. Invalid)) {
  3700. if (TemplateParams->size() > 0) {
  3701. // There is no such thing as a variable template.
  3702. Diag(D.getIdentifierLoc(), diag::err_template_variable)
  3703. << II
  3704. << SourceRange(TemplateParams->getTemplateLoc(),
  3705. TemplateParams->getRAngleLoc());
  3706. return 0;
  3707. } else {
  3708. // There is an extraneous 'template<>' for this variable. Complain
  3709. // about it, but allow the declaration of the variable.
  3710. Diag(TemplateParams->getTemplateLoc(),
  3711. diag::err_template_variable_noparams)
  3712. << II
  3713. << SourceRange(TemplateParams->getTemplateLoc(),
  3714. TemplateParams->getRAngleLoc());
  3715. }
  3716. }
  3717. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  3718. D.getIdentifierLoc(), II,
  3719. R, TInfo, SC, SCAsWritten);
  3720. // If this decl has an auto type in need of deduction, make a note of the
  3721. // Decl so we can diagnose uses of it in its own initializer.
  3722. if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
  3723. R->getContainedAutoType())
  3724. ParsingInitForAutoVars.insert(NewVD);
  3725. if (D.isInvalidType() || Invalid)
  3726. NewVD->setInvalidDecl();
  3727. SetNestedNameSpecifier(NewVD, D);
  3728. if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
  3729. NewVD->setTemplateParameterListsInfo(Context,
  3730. TemplateParamLists.size(),
  3731. TemplateParamLists.get());
  3732. }
  3733. if (D.getDeclSpec().isConstexprSpecified())
  3734. NewVD->setConstexpr(true);
  3735. }
  3736. // Set the lexical context. If the declarator has a C++ scope specifier, the
  3737. // lexical context will be different from the semantic context.
  3738. NewVD->setLexicalDeclContext(CurContext);
  3739. if (D.getDeclSpec().isThreadSpecified()) {
  3740. if (NewVD->hasLocalStorage())
  3741. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
  3742. else if (!Context.getTargetInfo().isTLSSupported())
  3743. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
  3744. else
  3745. NewVD->setThreadSpecified(true);
  3746. }
  3747. if (D.getDeclSpec().isModulePrivateSpecified()) {
  3748. if (isExplicitSpecialization)
  3749. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  3750. << 2
  3751. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3752. else if (NewVD->hasLocalStorage())
  3753. Diag(NewVD->getLocation(), diag::err_module_private_local)
  3754. << 0 << NewVD->getDeclName()
  3755. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  3756. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  3757. else
  3758. NewVD->setModulePrivate();
  3759. }
  3760. // Handle attributes prior to checking for duplicates in MergeVarDecl
  3761. ProcessDeclAttributes(S, NewVD, D);
  3762. // In auto-retain/release, infer strong retension for variables of
  3763. // retainable type.
  3764. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  3765. NewVD->setInvalidDecl();
  3766. // Handle GNU asm-label extension (encoded as an attribute).
  3767. if (Expr *E = (Expr*)D.getAsmLabel()) {
  3768. // The parser guarantees this is a string.
  3769. StringLiteral *SE = cast<StringLiteral>(E);
  3770. StringRef Label = SE->getString();
  3771. if (S->getFnParent() != 0) {
  3772. switch (SC) {
  3773. case SC_None:
  3774. case SC_Auto:
  3775. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  3776. break;
  3777. case SC_Register:
  3778. if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
  3779. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  3780. break;
  3781. case SC_Static:
  3782. case SC_Extern:
  3783. case SC_PrivateExtern:
  3784. case SC_OpenCLWorkGroupLocal:
  3785. break;
  3786. }
  3787. }
  3788. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  3789. Context, Label));
  3790. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  3791. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  3792. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  3793. if (I != ExtnameUndeclaredIdentifiers.end()) {
  3794. NewVD->addAttr(I->second);
  3795. ExtnameUndeclaredIdentifiers.erase(I);
  3796. }
  3797. }
  3798. // Diagnose shadowed variables before filtering for scope.
  3799. if (!D.getCXXScopeSpec().isSet())
  3800. CheckShadow(S, NewVD, Previous);
  3801. // Don't consider existing declarations that are in a different
  3802. // scope and are out-of-semantic-context declarations (if the new
  3803. // declaration has linkage).
  3804. FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
  3805. isExplicitSpecialization);
  3806. if (!getLangOpts().CPlusPlus) {
  3807. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3808. } else {
  3809. // Merge the decl with the existing one if appropriate.
  3810. if (!Previous.empty()) {
  3811. if (Previous.isSingleResult() &&
  3812. isa<FieldDecl>(Previous.getFoundDecl()) &&
  3813. D.getCXXScopeSpec().isSet()) {
  3814. // The user tried to define a non-static data member
  3815. // out-of-line (C++ [dcl.meaning]p1).
  3816. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  3817. << D.getCXXScopeSpec().getRange();
  3818. Previous.clear();
  3819. NewVD->setInvalidDecl();
  3820. }
  3821. } else if (D.getCXXScopeSpec().isSet()) {
  3822. // No previous declaration in the qualifying scope.
  3823. Diag(D.getIdentifierLoc(), diag::err_no_member)
  3824. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  3825. << D.getCXXScopeSpec().getRange();
  3826. NewVD->setInvalidDecl();
  3827. }
  3828. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  3829. // This is an explicit specialization of a static data member. Check it.
  3830. if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
  3831. CheckMemberSpecialization(NewVD, Previous))
  3832. NewVD->setInvalidDecl();
  3833. }
  3834. // If this is a locally-scoped extern C variable, update the map of
  3835. // such variables.
  3836. if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
  3837. !NewVD->isInvalidDecl())
  3838. RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
  3839. // If there's a #pragma GCC visibility in scope, and this isn't a class
  3840. // member, set the visibility of this variable.
  3841. if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
  3842. AddPushedVisibilityAttribute(NewVD);
  3843. MarkUnusedFileScopedDecl(NewVD);
  3844. return NewVD;
  3845. }
  3846. /// \brief Diagnose variable or built-in function shadowing. Implements
  3847. /// -Wshadow.
  3848. ///
  3849. /// This method is called whenever a VarDecl is added to a "useful"
  3850. /// scope.
  3851. ///
  3852. /// \param S the scope in which the shadowing name is being declared
  3853. /// \param R the lookup of the name
  3854. ///
  3855. void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
  3856. // Return if warning is ignored.
  3857. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
  3858. DiagnosticsEngine::Ignored)
  3859. return;
  3860. // Don't diagnose declarations at file scope.
  3861. if (D->hasGlobalStorage())
  3862. return;
  3863. DeclContext *NewDC = D->getDeclContext();
  3864. // Only diagnose if we're shadowing an unambiguous field or variable.
  3865. if (R.getResultKind() != LookupResult::Found)
  3866. return;
  3867. NamedDecl* ShadowedDecl = R.getFoundDecl();
  3868. if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
  3869. return;
  3870. // Fields are not shadowed by variables in C++ static methods.
  3871. if (isa<FieldDecl>(ShadowedDecl))
  3872. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  3873. if (MD->isStatic())
  3874. return;
  3875. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  3876. if (shadowedVar->isExternC()) {
  3877. // For shadowing external vars, make sure that we point to the global
  3878. // declaration, not a locally scoped extern declaration.
  3879. for (VarDecl::redecl_iterator
  3880. I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
  3881. I != E; ++I)
  3882. if (I->isFileVarDecl()) {
  3883. ShadowedDecl = *I;
  3884. break;
  3885. }
  3886. }
  3887. DeclContext *OldDC = ShadowedDecl->getDeclContext();
  3888. // Only warn about certain kinds of shadowing for class members.
  3889. if (NewDC && NewDC->isRecord()) {
  3890. // In particular, don't warn about shadowing non-class members.
  3891. if (!OldDC->isRecord())
  3892. return;
  3893. // TODO: should we warn about static data members shadowing
  3894. // static data members from base classes?
  3895. // TODO: don't diagnose for inaccessible shadowed members.
  3896. // This is hard to do perfectly because we might friend the
  3897. // shadowing context, but that's just a false negative.
  3898. }
  3899. // Determine what kind of declaration we're shadowing.
  3900. unsigned Kind;
  3901. if (isa<RecordDecl>(OldDC)) {
  3902. if (isa<FieldDecl>(ShadowedDecl))
  3903. Kind = 3; // field
  3904. else
  3905. Kind = 2; // static data member
  3906. } else if (OldDC->isFileContext())
  3907. Kind = 1; // global
  3908. else
  3909. Kind = 0; // local
  3910. DeclarationName Name = R.getLookupName();
  3911. // Emit warning and note.
  3912. Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
  3913. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  3914. }
  3915. /// \brief Check -Wshadow without the advantage of a previous lookup.
  3916. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  3917. if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
  3918. DiagnosticsEngine::Ignored)
  3919. return;
  3920. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  3921. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  3922. LookupName(R, S);
  3923. CheckShadow(S, D, R);
  3924. }
  3925. /// \brief Perform semantic checking on a newly-created variable
  3926. /// declaration.
  3927. ///
  3928. /// This routine performs all of the type-checking required for a
  3929. /// variable declaration once it has been built. It is used both to
  3930. /// check variables after they have been parsed and their declarators
  3931. /// have been translated into a declaration, and to check variables
  3932. /// that have been instantiated from a template.
  3933. ///
  3934. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  3935. ///
  3936. /// Returns true if the variable declaration is a redeclaration.
  3937. bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
  3938. LookupResult &Previous) {
  3939. // If the decl is already known invalid, don't check it.
  3940. if (NewVD->isInvalidDecl())
  3941. return false;
  3942. QualType T = NewVD->getType();
  3943. if (T->isObjCObjectType()) {
  3944. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  3945. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  3946. T = Context.getObjCObjectPointerType(T);
  3947. NewVD->setType(T);
  3948. }
  3949. // Emit an error if an address space was applied to decl with local storage.
  3950. // This includes arrays of objects with address space qualifiers, but not
  3951. // automatic variables that point to other address spaces.
  3952. // ISO/IEC TR 18037 S5.1.2
  3953. if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  3954. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
  3955. NewVD->setInvalidDecl();
  3956. return false;
  3957. }
  3958. // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
  3959. // scope.
  3960. if ((getLangOpts().OpenCLVersion >= 120)
  3961. && NewVD->isStaticLocal()) {
  3962. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  3963. NewVD->setInvalidDecl();
  3964. return false;
  3965. }
  3966. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  3967. && !NewVD->hasAttr<BlocksAttr>()) {
  3968. if (getLangOpts().getGC() != LangOptions::NonGC)
  3969. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  3970. else
  3971. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  3972. }
  3973. bool isVM = T->isVariablyModifiedType();
  3974. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  3975. NewVD->hasAttr<BlocksAttr>())
  3976. getCurFunction()->setHasBranchProtectedScope();
  3977. if ((isVM && NewVD->hasLinkage()) ||
  3978. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  3979. bool SizeIsNegative;
  3980. llvm::APSInt Oversized;
  3981. QualType FixedTy =
  3982. TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  3983. Oversized);
  3984. if (FixedTy.isNull() && T->isVariableArrayType()) {
  3985. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  3986. // FIXME: This won't give the correct result for
  3987. // int a[10][n];
  3988. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  3989. if (NewVD->isFileVarDecl())
  3990. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  3991. << SizeRange;
  3992. else if (NewVD->getStorageClass() == SC_Static)
  3993. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  3994. << SizeRange;
  3995. else
  3996. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  3997. << SizeRange;
  3998. NewVD->setInvalidDecl();
  3999. return false;
  4000. }
  4001. if (FixedTy.isNull()) {
  4002. if (NewVD->isFileVarDecl())
  4003. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  4004. else
  4005. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  4006. NewVD->setInvalidDecl();
  4007. return false;
  4008. }
  4009. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  4010. NewVD->setType(FixedTy);
  4011. }
  4012. if (Previous.empty() && NewVD->isExternC()) {
  4013. // Since we did not find anything by this name and we're declaring
  4014. // an extern "C" variable, look for a non-visible extern "C"
  4015. // declaration with the same name.
  4016. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  4017. = findLocallyScopedExternalDecl(NewVD->getDeclName());
  4018. if (Pos != LocallyScopedExternalDecls.end())
  4019. Previous.addDecl(Pos->second);
  4020. }
  4021. if (T->isVoidType() && !NewVD->hasExternalStorage()) {
  4022. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  4023. << T;
  4024. NewVD->setInvalidDecl();
  4025. return false;
  4026. }
  4027. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  4028. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  4029. NewVD->setInvalidDecl();
  4030. return false;
  4031. }
  4032. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  4033. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  4034. NewVD->setInvalidDecl();
  4035. return false;
  4036. }
  4037. if (NewVD->isConstexpr() && !T->isDependentType() &&
  4038. RequireLiteralType(NewVD->getLocation(), T,
  4039. diag::err_constexpr_var_non_literal)) {
  4040. NewVD->setInvalidDecl();
  4041. return false;
  4042. }
  4043. if (!Previous.empty()) {
  4044. MergeVarDecl(NewVD, Previous);
  4045. return true;
  4046. }
  4047. return false;
  4048. }
  4049. /// \brief Data used with FindOverriddenMethod
  4050. struct FindOverriddenMethodData {
  4051. Sema *S;
  4052. CXXMethodDecl *Method;
  4053. };
  4054. /// \brief Member lookup function that determines whether a given C++
  4055. /// method overrides a method in a base class, to be used with
  4056. /// CXXRecordDecl::lookupInBases().
  4057. static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
  4058. CXXBasePath &Path,
  4059. void *UserData) {
  4060. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  4061. FindOverriddenMethodData *Data
  4062. = reinterpret_cast<FindOverriddenMethodData*>(UserData);
  4063. DeclarationName Name = Data->Method->getDeclName();
  4064. // FIXME: Do we care about other names here too?
  4065. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4066. // We really want to find the base class destructor here.
  4067. QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
  4068. CanQualType CT = Data->S->Context.getCanonicalType(T);
  4069. Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
  4070. }
  4071. for (Path.Decls = BaseRecord->lookup(Name);
  4072. Path.Decls.first != Path.Decls.second;
  4073. ++Path.Decls.first) {
  4074. NamedDecl *D = *Path.Decls.first;
  4075. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  4076. if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
  4077. return true;
  4078. }
  4079. }
  4080. return false;
  4081. }
  4082. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  4083. /// and if so, check that it's a valid override and remember it.
  4084. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  4085. // Look for virtual methods in base classes that this method might override.
  4086. CXXBasePaths Paths;
  4087. FindOverriddenMethodData Data;
  4088. Data.Method = MD;
  4089. Data.S = this;
  4090. bool AddedAny = false;
  4091. if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
  4092. for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
  4093. E = Paths.found_decls_end(); I != E; ++I) {
  4094. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
  4095. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  4096. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  4097. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  4098. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  4099. AddedAny = true;
  4100. }
  4101. }
  4102. }
  4103. }
  4104. return AddedAny;
  4105. }
  4106. namespace {
  4107. // Struct for holding all of the extra arguments needed by
  4108. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  4109. struct ActOnFDArgs {
  4110. Scope *S;
  4111. Declarator &D;
  4112. MultiTemplateParamsArg TemplateParamLists;
  4113. bool AddToScope;
  4114. };
  4115. }
  4116. namespace {
  4117. // Callback to only accept typo corrections that have a non-zero edit distance.
  4118. // Also only accept corrections that have the same parent decl.
  4119. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  4120. public:
  4121. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  4122. CXXRecordDecl *Parent)
  4123. : Context(Context), OriginalFD(TypoFD),
  4124. ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
  4125. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  4126. if (candidate.getEditDistance() == 0)
  4127. return false;
  4128. llvm::SmallVector<unsigned, 1> MismatchedParams;
  4129. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  4130. CDeclEnd = candidate.end();
  4131. CDecl != CDeclEnd; ++CDecl) {
  4132. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  4133. if (FD && !FD->hasBody() &&
  4134. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  4135. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  4136. CXXRecordDecl *Parent = MD->getParent();
  4137. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  4138. return true;
  4139. } else if (!ExpectedParent) {
  4140. return true;
  4141. }
  4142. }
  4143. }
  4144. return false;
  4145. }
  4146. private:
  4147. ASTContext &Context;
  4148. FunctionDecl *OriginalFD;
  4149. CXXRecordDecl *ExpectedParent;
  4150. };
  4151. }
  4152. /// \brief Generate diagnostics for an invalid function redeclaration.
  4153. ///
  4154. /// This routine handles generating the diagnostic messages for an invalid
  4155. /// function redeclaration, including finding possible similar declarations
  4156. /// or performing typo correction if there are no previous declarations with
  4157. /// the same name.
  4158. ///
  4159. /// Returns a NamedDecl iff typo correction was performed and substituting in
  4160. /// the new declaration name does not cause new errors.
  4161. static NamedDecl* DiagnoseInvalidRedeclaration(
  4162. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  4163. ActOnFDArgs &ExtraArgs) {
  4164. NamedDecl *Result = NULL;
  4165. DeclarationName Name = NewFD->getDeclName();
  4166. DeclContext *NewDC = NewFD->getDeclContext();
  4167. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  4168. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  4169. llvm::SmallVector<unsigned, 1> MismatchedParams;
  4170. llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
  4171. TypoCorrection Correction;
  4172. bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
  4173. ExtraArgs.D.getDeclSpec().isFriendSpecified());
  4174. unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
  4175. : diag::err_member_def_does_not_match;
  4176. NewFD->setInvalidDecl();
  4177. SemaRef.LookupQualifiedName(Prev, NewDC);
  4178. assert(!Prev.isAmbiguous() &&
  4179. "Cannot have an ambiguity in previous-declaration lookup");
  4180. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  4181. DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
  4182. MD ? MD->getParent() : 0);
  4183. if (!Prev.empty()) {
  4184. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  4185. Func != FuncEnd; ++Func) {
  4186. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  4187. if (FD &&
  4188. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  4189. // Add 1 to the index so that 0 can mean the mismatch didn't
  4190. // involve a parameter
  4191. unsigned ParamNum =
  4192. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  4193. NearMatches.push_back(std::make_pair(FD, ParamNum));
  4194. }
  4195. }
  4196. // If the qualified name lookup yielded nothing, try typo correction
  4197. } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
  4198. Prev.getLookupKind(), 0, 0,
  4199. Validator, NewDC))) {
  4200. // Trap errors.
  4201. Sema::SFINAETrap Trap(SemaRef);
  4202. // Set up everything for the call to ActOnFunctionDeclarator
  4203. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  4204. ExtraArgs.D.getIdentifierLoc());
  4205. Previous.clear();
  4206. Previous.setLookupName(Correction.getCorrection());
  4207. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  4208. CDeclEnd = Correction.end();
  4209. CDecl != CDeclEnd; ++CDecl) {
  4210. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  4211. if (FD && !FD->hasBody() &&
  4212. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  4213. Previous.addDecl(FD);
  4214. }
  4215. }
  4216. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  4217. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  4218. // pieces need to verify the typo-corrected C++ declaraction and hopefully
  4219. // eliminate the need for the parameter pack ExtraArgs.
  4220. Result = SemaRef.ActOnFunctionDeclarator(
  4221. ExtraArgs.S, ExtraArgs.D,
  4222. Correction.getCorrectionDecl()->getDeclContext(),
  4223. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  4224. ExtraArgs.AddToScope);
  4225. if (Trap.hasErrorOccurred()) {
  4226. // Pretend the typo correction never occurred
  4227. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  4228. ExtraArgs.D.getIdentifierLoc());
  4229. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  4230. Previous.clear();
  4231. Previous.setLookupName(Name);
  4232. Result = NULL;
  4233. } else {
  4234. for (LookupResult::iterator Func = Previous.begin(),
  4235. FuncEnd = Previous.end();
  4236. Func != FuncEnd; ++Func) {
  4237. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
  4238. NearMatches.push_back(std::make_pair(FD, 0));
  4239. }
  4240. }
  4241. if (NearMatches.empty()) {
  4242. // Ignore the correction if it didn't yield any close FunctionDecl matches
  4243. Correction = TypoCorrection();
  4244. } else {
  4245. DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
  4246. : diag::err_member_def_does_not_match_suggest;
  4247. }
  4248. }
  4249. if (Correction) {
  4250. SourceRange FixItLoc(NewFD->getLocation());
  4251. CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec();
  4252. if (Correction.getCorrectionSpecifier() && SS.isValid())
  4253. FixItLoc.setBegin(SS.getBeginLoc());
  4254. SemaRef.Diag(NewFD->getLocStart(), DiagMsg)
  4255. << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
  4256. << FixItHint::CreateReplacement(
  4257. FixItLoc, Correction.getAsString(SemaRef.getLangOpts()));
  4258. } else {
  4259. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  4260. << Name << NewDC << NewFD->getLocation();
  4261. }
  4262. bool NewFDisConst = false;
  4263. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  4264. NewFDisConst = NewMD->isConst();
  4265. for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
  4266. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  4267. NearMatch != NearMatchEnd; ++NearMatch) {
  4268. FunctionDecl *FD = NearMatch->first;
  4269. bool FDisConst = false;
  4270. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  4271. FDisConst = MD->isConst();
  4272. if (unsigned Idx = NearMatch->second) {
  4273. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  4274. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  4275. if (Loc.isInvalid()) Loc = FD->getLocation();
  4276. SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
  4277. << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
  4278. } else if (Correction) {
  4279. SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
  4280. << Correction.getQuoted(SemaRef.getLangOpts());
  4281. } else if (FDisConst != NewFDisConst) {
  4282. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  4283. << NewFDisConst << FD->getSourceRange().getEnd();
  4284. } else
  4285. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
  4286. }
  4287. return Result;
  4288. }
  4289. static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
  4290. Declarator &D) {
  4291. switch (D.getDeclSpec().getStorageClassSpec()) {
  4292. default: llvm_unreachable("Unknown storage class!");
  4293. case DeclSpec::SCS_auto:
  4294. case DeclSpec::SCS_register:
  4295. case DeclSpec::SCS_mutable:
  4296. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4297. diag::err_typecheck_sclass_func);
  4298. D.setInvalidType();
  4299. break;
  4300. case DeclSpec::SCS_unspecified: break;
  4301. case DeclSpec::SCS_extern: return SC_Extern;
  4302. case DeclSpec::SCS_static: {
  4303. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  4304. // C99 6.7.1p5:
  4305. // The declaration of an identifier for a function that has
  4306. // block scope shall have no explicit storage-class specifier
  4307. // other than extern
  4308. // See also (C++ [dcl.stc]p4).
  4309. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4310. diag::err_static_block_func);
  4311. break;
  4312. } else
  4313. return SC_Static;
  4314. }
  4315. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4316. }
  4317. // No explicit storage class has already been returned
  4318. return SC_None;
  4319. }
  4320. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  4321. DeclContext *DC, QualType &R,
  4322. TypeSourceInfo *TInfo,
  4323. FunctionDecl::StorageClass SC,
  4324. bool &IsVirtualOkay) {
  4325. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  4326. DeclarationName Name = NameInfo.getName();
  4327. FunctionDecl *NewFD = 0;
  4328. bool isInline = D.getDeclSpec().isInlineSpecified();
  4329. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
  4330. FunctionDecl::StorageClass SCAsWritten
  4331. = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
  4332. if (!SemaRef.getLangOpts().CPlusPlus) {
  4333. // Determine whether the function was written with a
  4334. // prototype. This true when:
  4335. // - there is a prototype in the declarator, or
  4336. // - the type R of the function is some kind of typedef or other reference
  4337. // to a type name (which eventually refers to a function type).
  4338. bool HasPrototype =
  4339. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  4340. (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
  4341. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  4342. D.getLocStart(), NameInfo, R,
  4343. TInfo, SC, SCAsWritten, isInline,
  4344. HasPrototype);
  4345. if (D.isInvalidType())
  4346. NewFD->setInvalidDecl();
  4347. // Set the lexical context.
  4348. NewFD->setLexicalDeclContext(SemaRef.CurContext);
  4349. return NewFD;
  4350. }
  4351. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4352. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4353. // Check that the return type is not an abstract class type.
  4354. // For record types, this is done by the AbstractClassUsageDiagnoser once
  4355. // the class has been completely parsed.
  4356. if (!DC->isRecord() &&
  4357. SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
  4358. R->getAs<FunctionType>()->getResultType(),
  4359. diag::err_abstract_type_in_decl,
  4360. SemaRef.AbstractReturnType))
  4361. D.setInvalidType();
  4362. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  4363. // This is a C++ constructor declaration.
  4364. assert(DC->isRecord() &&
  4365. "Constructors can only be declared in a member context");
  4366. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  4367. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4368. D.getLocStart(), NameInfo,
  4369. R, TInfo, isExplicit, isInline,
  4370. /*isImplicitlyDeclared=*/false,
  4371. isConstexpr);
  4372. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4373. // This is a C++ destructor declaration.
  4374. if (DC->isRecord()) {
  4375. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  4376. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  4377. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  4378. SemaRef.Context, Record,
  4379. D.getLocStart(),
  4380. NameInfo, R, TInfo, isInline,
  4381. /*isImplicitlyDeclared=*/false);
  4382. // If the class is complete, then we now create the implicit exception
  4383. // specification. If the class is incomplete or dependent, we can't do
  4384. // it yet.
  4385. if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
  4386. Record->getDefinition() && !Record->isBeingDefined() &&
  4387. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  4388. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  4389. }
  4390. IsVirtualOkay = true;
  4391. return NewDD;
  4392. } else {
  4393. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  4394. D.setInvalidType();
  4395. // Create a FunctionDecl to satisfy the function definition parsing
  4396. // code path.
  4397. return FunctionDecl::Create(SemaRef.Context, DC,
  4398. D.getLocStart(),
  4399. D.getIdentifierLoc(), Name, R, TInfo,
  4400. SC, SCAsWritten, isInline,
  4401. /*hasPrototype=*/true, isConstexpr);
  4402. }
  4403. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  4404. if (!DC->isRecord()) {
  4405. SemaRef.Diag(D.getIdentifierLoc(),
  4406. diag::err_conv_function_not_member);
  4407. return 0;
  4408. }
  4409. SemaRef.CheckConversionDeclarator(D, R, SC);
  4410. IsVirtualOkay = true;
  4411. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4412. D.getLocStart(), NameInfo,
  4413. R, TInfo, isInline, isExplicit,
  4414. isConstexpr, SourceLocation());
  4415. } else if (DC->isRecord()) {
  4416. // If the name of the function is the same as the name of the record,
  4417. // then this must be an invalid constructor that has a return type.
  4418. // (The parser checks for a return type and makes the declarator a
  4419. // constructor if it has no return type).
  4420. if (Name.getAsIdentifierInfo() &&
  4421. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  4422. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  4423. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  4424. << SourceRange(D.getIdentifierLoc());
  4425. return 0;
  4426. }
  4427. bool isStatic = SC == SC_Static;
  4428. // [class.free]p1:
  4429. // Any allocation function for a class T is a static member
  4430. // (even if not explicitly declared static).
  4431. if (Name.getCXXOverloadedOperator() == OO_New ||
  4432. Name.getCXXOverloadedOperator() == OO_Array_New)
  4433. isStatic = true;
  4434. // [class.free]p6 Any deallocation function for a class X is a static member
  4435. // (even if not explicitly declared static).
  4436. if (Name.getCXXOverloadedOperator() == OO_Delete ||
  4437. Name.getCXXOverloadedOperator() == OO_Array_Delete)
  4438. isStatic = true;
  4439. IsVirtualOkay = !isStatic;
  4440. // This is a C++ method declaration.
  4441. return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  4442. D.getLocStart(), NameInfo, R,
  4443. TInfo, isStatic, SCAsWritten, isInline,
  4444. isConstexpr, SourceLocation());
  4445. } else {
  4446. // Determine whether the function was written with a
  4447. // prototype. This true when:
  4448. // - we're in C++ (where every function has a prototype),
  4449. return FunctionDecl::Create(SemaRef.Context, DC,
  4450. D.getLocStart(),
  4451. NameInfo, R, TInfo, SC, SCAsWritten, isInline,
  4452. true/*HasPrototype*/, isConstexpr);
  4453. }
  4454. }
  4455. NamedDecl*
  4456. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  4457. TypeSourceInfo *TInfo, LookupResult &Previous,
  4458. MultiTemplateParamsArg TemplateParamLists,
  4459. bool &AddToScope) {
  4460. QualType R = TInfo->getType();
  4461. assert(R.getTypePtr()->isFunctionType());
  4462. // TODO: consider using NameInfo for diagnostic.
  4463. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4464. DeclarationName Name = NameInfo.getName();
  4465. FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
  4466. if (D.getDeclSpec().isThreadSpecified())
  4467. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  4468. // Do not allow returning a objc interface by-value.
  4469. if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
  4470. Diag(D.getIdentifierLoc(),
  4471. diag::err_object_cannot_be_passed_returned_by_value) << 0
  4472. << R->getAs<FunctionType>()->getResultType()
  4473. << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
  4474. QualType T = R->getAs<FunctionType>()->getResultType();
  4475. T = Context.getObjCObjectPointerType(T);
  4476. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
  4477. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  4478. R = Context.getFunctionType(T, FPT->arg_type_begin(),
  4479. FPT->getNumArgs(), EPI);
  4480. }
  4481. else if (isa<FunctionNoProtoType>(R))
  4482. R = Context.getFunctionNoProtoType(T);
  4483. }
  4484. bool isFriend = false;
  4485. FunctionTemplateDecl *FunctionTemplate = 0;
  4486. bool isExplicitSpecialization = false;
  4487. bool isFunctionTemplateSpecialization = false;
  4488. bool isDependentClassScopeExplicitSpecialization = false;
  4489. bool HasExplicitTemplateArgs = false;
  4490. TemplateArgumentListInfo TemplateArgs;
  4491. bool isVirtualOkay = false;
  4492. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  4493. isVirtualOkay);
  4494. if (!NewFD) return 0;
  4495. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  4496. NewFD->setTopLevelDeclInObjCContainer();
  4497. if (getLangOpts().CPlusPlus) {
  4498. bool isInline = D.getDeclSpec().isInlineSpecified();
  4499. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  4500. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  4501. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  4502. isFriend = D.getDeclSpec().isFriendSpecified();
  4503. if (isFriend && !isInline && D.isFunctionDefinition()) {
  4504. // C++ [class.friend]p5
  4505. // A function can be defined in a friend declaration of a
  4506. // class . . . . Such a function is implicitly inline.
  4507. NewFD->setImplicitlyInline();
  4508. }
  4509. SetNestedNameSpecifier(NewFD, D);
  4510. isExplicitSpecialization = false;
  4511. isFunctionTemplateSpecialization = false;
  4512. if (D.isInvalidType())
  4513. NewFD->setInvalidDecl();
  4514. // Set the lexical context. If the declarator has a C++
  4515. // scope specifier, or is the object of a friend declaration, the
  4516. // lexical context will be different from the semantic context.
  4517. NewFD->setLexicalDeclContext(CurContext);
  4518. // Match up the template parameter lists with the scope specifier, then
  4519. // determine whether we have a template or a template specialization.
  4520. bool Invalid = false;
  4521. if (TemplateParameterList *TemplateParams
  4522. = MatchTemplateParametersToScopeSpecifier(
  4523. D.getDeclSpec().getLocStart(),
  4524. D.getIdentifierLoc(),
  4525. D.getCXXScopeSpec(),
  4526. TemplateParamLists.get(),
  4527. TemplateParamLists.size(),
  4528. isFriend,
  4529. isExplicitSpecialization,
  4530. Invalid)) {
  4531. if (TemplateParams->size() > 0) {
  4532. // This is a function template
  4533. // Check that we can declare a template here.
  4534. if (CheckTemplateDeclScope(S, TemplateParams))
  4535. return 0;
  4536. // A destructor cannot be a template.
  4537. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  4538. Diag(NewFD->getLocation(), diag::err_destructor_template);
  4539. return 0;
  4540. }
  4541. // If we're adding a template to a dependent context, we may need to
  4542. // rebuilding some of the types used within the template parameter list,
  4543. // now that we know what the current instantiation is.
  4544. if (DC->isDependentContext()) {
  4545. ContextRAII SavedContext(*this, DC);
  4546. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  4547. Invalid = true;
  4548. }
  4549. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  4550. NewFD->getLocation(),
  4551. Name, TemplateParams,
  4552. NewFD);
  4553. FunctionTemplate->setLexicalDeclContext(CurContext);
  4554. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  4555. // For source fidelity, store the other template param lists.
  4556. if (TemplateParamLists.size() > 1) {
  4557. NewFD->setTemplateParameterListsInfo(Context,
  4558. TemplateParamLists.size() - 1,
  4559. TemplateParamLists.get());
  4560. }
  4561. } else {
  4562. // This is a function template specialization.
  4563. isFunctionTemplateSpecialization = true;
  4564. // For source fidelity, store all the template param lists.
  4565. NewFD->setTemplateParameterListsInfo(Context,
  4566. TemplateParamLists.size(),
  4567. TemplateParamLists.get());
  4568. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  4569. if (isFriend) {
  4570. // We want to remove the "template<>", found here.
  4571. SourceRange RemoveRange = TemplateParams->getSourceRange();
  4572. // If we remove the template<> and the name is not a
  4573. // template-id, we're actually silently creating a problem:
  4574. // the friend declaration will refer to an untemplated decl,
  4575. // and clearly the user wants a template specialization. So
  4576. // we need to insert '<>' after the name.
  4577. SourceLocation InsertLoc;
  4578. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  4579. InsertLoc = D.getName().getSourceRange().getEnd();
  4580. InsertLoc = PP.getLocForEndOfToken(InsertLoc);
  4581. }
  4582. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  4583. << Name << RemoveRange
  4584. << FixItHint::CreateRemoval(RemoveRange)
  4585. << FixItHint::CreateInsertion(InsertLoc, "<>");
  4586. }
  4587. }
  4588. }
  4589. else {
  4590. // All template param lists were matched against the scope specifier:
  4591. // this is NOT (an explicit specialization of) a template.
  4592. if (TemplateParamLists.size() > 0)
  4593. // For source fidelity, store all the template param lists.
  4594. NewFD->setTemplateParameterListsInfo(Context,
  4595. TemplateParamLists.size(),
  4596. TemplateParamLists.get());
  4597. }
  4598. if (Invalid) {
  4599. NewFD->setInvalidDecl();
  4600. if (FunctionTemplate)
  4601. FunctionTemplate->setInvalidDecl();
  4602. }
  4603. // C++ [dcl.fct.spec]p5:
  4604. // The virtual specifier shall only be used in declarations of
  4605. // nonstatic class member functions that appear within a
  4606. // member-specification of a class declaration; see 10.3.
  4607. //
  4608. if (isVirtual && !NewFD->isInvalidDecl()) {
  4609. if (!isVirtualOkay) {
  4610. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4611. diag::err_virtual_non_function);
  4612. } else if (!CurContext->isRecord()) {
  4613. // 'virtual' was specified outside of the class.
  4614. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4615. diag::err_virtual_out_of_class)
  4616. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4617. } else if (NewFD->getDescribedFunctionTemplate()) {
  4618. // C++ [temp.mem]p3:
  4619. // A member function template shall not be virtual.
  4620. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  4621. diag::err_virtual_member_function_template)
  4622. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  4623. } else {
  4624. // Okay: Add virtual to the method.
  4625. NewFD->setVirtualAsWritten(true);
  4626. }
  4627. }
  4628. // C++ [dcl.fct.spec]p3:
  4629. // The inline specifier shall not appear on a block scope function
  4630. // declaration.
  4631. if (isInline && !NewFD->isInvalidDecl()) {
  4632. if (CurContext->isFunctionOrMethod()) {
  4633. // 'inline' is not allowed on block scope function declaration.
  4634. Diag(D.getDeclSpec().getInlineSpecLoc(),
  4635. diag::err_inline_declaration_block_scope) << Name
  4636. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  4637. }
  4638. }
  4639. // C++ [dcl.fct.spec]p6:
  4640. // The explicit specifier shall be used only in the declaration of a
  4641. // constructor or conversion function within its class definition;
  4642. // see 12.3.1 and 12.3.2.
  4643. if (isExplicit && !NewFD->isInvalidDecl()) {
  4644. if (!CurContext->isRecord()) {
  4645. // 'explicit' was specified outside of the class.
  4646. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4647. diag::err_explicit_out_of_class)
  4648. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4649. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  4650. !isa<CXXConversionDecl>(NewFD)) {
  4651. // 'explicit' was specified on a function that wasn't a constructor
  4652. // or conversion function.
  4653. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  4654. diag::err_explicit_non_ctor_or_conv_function)
  4655. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  4656. }
  4657. }
  4658. if (isConstexpr) {
  4659. // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
  4660. // are implicitly inline.
  4661. NewFD->setImplicitlyInline();
  4662. // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
  4663. // be either constructors or to return a literal type. Therefore,
  4664. // destructors cannot be declared constexpr.
  4665. if (isa<CXXDestructorDecl>(NewFD))
  4666. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  4667. }
  4668. // If __module_private__ was specified, mark the function accordingly.
  4669. if (D.getDeclSpec().isModulePrivateSpecified()) {
  4670. if (isFunctionTemplateSpecialization) {
  4671. SourceLocation ModulePrivateLoc
  4672. = D.getDeclSpec().getModulePrivateSpecLoc();
  4673. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  4674. << 0
  4675. << FixItHint::CreateRemoval(ModulePrivateLoc);
  4676. } else {
  4677. NewFD->setModulePrivate();
  4678. if (FunctionTemplate)
  4679. FunctionTemplate->setModulePrivate();
  4680. }
  4681. }
  4682. if (isFriend) {
  4683. // For now, claim that the objects have no previous declaration.
  4684. if (FunctionTemplate) {
  4685. FunctionTemplate->setObjectOfFriendDecl(false);
  4686. FunctionTemplate->setAccess(AS_public);
  4687. }
  4688. NewFD->setObjectOfFriendDecl(false);
  4689. NewFD->setAccess(AS_public);
  4690. }
  4691. // If a function is defined as defaulted or deleted, mark it as such now.
  4692. switch (D.getFunctionDefinitionKind()) {
  4693. case FDK_Declaration:
  4694. case FDK_Definition:
  4695. break;
  4696. case FDK_Defaulted:
  4697. NewFD->setDefaulted();
  4698. break;
  4699. case FDK_Deleted:
  4700. NewFD->setDeletedAsWritten();
  4701. break;
  4702. }
  4703. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  4704. D.isFunctionDefinition()) {
  4705. // C++ [class.mfct]p2:
  4706. // A member function may be defined (8.4) in its class definition, in
  4707. // which case it is an inline member function (7.1.2)
  4708. NewFD->setImplicitlyInline();
  4709. }
  4710. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  4711. !CurContext->isRecord()) {
  4712. // C++ [class.static]p1:
  4713. // A data or function member of a class may be declared static
  4714. // in a class definition, in which case it is a static member of
  4715. // the class.
  4716. // Complain about the 'static' specifier if it's on an out-of-line
  4717. // member function definition.
  4718. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  4719. diag::err_static_out_of_line)
  4720. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  4721. }
  4722. }
  4723. // Filter out previous declarations that don't match the scope.
  4724. FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
  4725. isExplicitSpecialization ||
  4726. isFunctionTemplateSpecialization);
  4727. // Handle GNU asm-label extension (encoded as an attribute).
  4728. if (Expr *E = (Expr*) D.getAsmLabel()) {
  4729. // The parser guarantees this is a string.
  4730. StringLiteral *SE = cast<StringLiteral>(E);
  4731. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  4732. SE->getString()));
  4733. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  4734. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  4735. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  4736. if (I != ExtnameUndeclaredIdentifiers.end()) {
  4737. NewFD->addAttr(I->second);
  4738. ExtnameUndeclaredIdentifiers.erase(I);
  4739. }
  4740. }
  4741. // Copy the parameter declarations from the declarator D to the function
  4742. // declaration NewFD, if they are available. First scavenge them into Params.
  4743. SmallVector<ParmVarDecl*, 16> Params;
  4744. if (D.isFunctionDeclarator()) {
  4745. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  4746. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  4747. // function that takes no arguments, not a function that takes a
  4748. // single void argument.
  4749. // We let through "const void" here because Sema::GetTypeForDeclarator
  4750. // already checks for that case.
  4751. if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
  4752. FTI.ArgInfo[0].Param &&
  4753. cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
  4754. // Empty arg list, don't push any params.
  4755. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
  4756. // In C++, the empty parameter-type-list must be spelled "void"; a
  4757. // typedef of void is not permitted.
  4758. if (getLangOpts().CPlusPlus &&
  4759. Param->getType().getUnqualifiedType() != Context.VoidTy) {
  4760. bool IsTypeAlias = false;
  4761. if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
  4762. IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
  4763. else if (const TemplateSpecializationType *TST =
  4764. Param->getType()->getAs<TemplateSpecializationType>())
  4765. IsTypeAlias = TST->isTypeAlias();
  4766. Diag(Param->getLocation(), diag::err_param_typedef_of_void)
  4767. << IsTypeAlias;
  4768. }
  4769. } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
  4770. for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
  4771. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
  4772. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  4773. Param->setDeclContext(NewFD);
  4774. Params.push_back(Param);
  4775. if (Param->isInvalidDecl())
  4776. NewFD->setInvalidDecl();
  4777. }
  4778. }
  4779. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  4780. // When we're declaring a function with a typedef, typeof, etc as in the
  4781. // following example, we'll need to synthesize (unnamed)
  4782. // parameters for use in the declaration.
  4783. //
  4784. // @code
  4785. // typedef void fn(int);
  4786. // fn f;
  4787. // @endcode
  4788. // Synthesize a parameter for each argument type.
  4789. for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
  4790. AE = FT->arg_type_end(); AI != AE; ++AI) {
  4791. ParmVarDecl *Param =
  4792. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
  4793. Param->setScopeInfo(0, Params.size());
  4794. Params.push_back(Param);
  4795. }
  4796. } else {
  4797. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  4798. "Should not need args for typedef of non-prototype fn");
  4799. }
  4800. // Finally, we know we have the right number of parameters, install them.
  4801. NewFD->setParams(Params);
  4802. // Find all anonymous symbols defined during the declaration of this function
  4803. // and add to NewFD. This lets us track decls such 'enum Y' in:
  4804. //
  4805. // void f(enum Y {AA} x) {}
  4806. //
  4807. // which would otherwise incorrectly end up in the translation unit scope.
  4808. NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
  4809. DeclsInPrototypeScope.clear();
  4810. // Process the non-inheritable attributes on this declaration.
  4811. ProcessDeclAttributes(S, NewFD, D,
  4812. /*NonInheritable=*/true, /*Inheritable=*/false);
  4813. // Functions returning a variably modified type violate C99 6.7.5.2p2
  4814. // because all functions have linkage.
  4815. if (!NewFD->isInvalidDecl() &&
  4816. NewFD->getResultType()->isVariablyModifiedType()) {
  4817. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  4818. NewFD->setInvalidDecl();
  4819. }
  4820. // Handle attributes.
  4821. ProcessDeclAttributes(S, NewFD, D,
  4822. /*NonInheritable=*/false, /*Inheritable=*/true);
  4823. if (!getLangOpts().CPlusPlus) {
  4824. // Perform semantic checking on the function declaration.
  4825. bool isExplicitSpecialization=false;
  4826. if (!NewFD->isInvalidDecl()) {
  4827. if (NewFD->isMain())
  4828. CheckMain(NewFD, D.getDeclSpec());
  4829. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4830. isExplicitSpecialization));
  4831. }
  4832. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4833. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4834. "previous declaration set still overloaded");
  4835. } else {
  4836. // If the declarator is a template-id, translate the parser's template
  4837. // argument list into our AST format.
  4838. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  4839. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  4840. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  4841. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  4842. ASTTemplateArgsPtr TemplateArgsPtr(*this,
  4843. TemplateId->getTemplateArgs(),
  4844. TemplateId->NumArgs);
  4845. translateTemplateArguments(TemplateArgsPtr,
  4846. TemplateArgs);
  4847. HasExplicitTemplateArgs = true;
  4848. if (NewFD->isInvalidDecl()) {
  4849. HasExplicitTemplateArgs = false;
  4850. } else if (FunctionTemplate) {
  4851. // Function template with explicit template arguments.
  4852. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  4853. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  4854. HasExplicitTemplateArgs = false;
  4855. } else if (!isFunctionTemplateSpecialization &&
  4856. !D.getDeclSpec().isFriendSpecified()) {
  4857. // We have encountered something that the user meant to be a
  4858. // specialization (because it has explicitly-specified template
  4859. // arguments) but that was not introduced with a "template<>" (or had
  4860. // too few of them).
  4861. Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
  4862. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
  4863. << FixItHint::CreateInsertion(
  4864. D.getDeclSpec().getLocStart(),
  4865. "template<> ");
  4866. isFunctionTemplateSpecialization = true;
  4867. } else {
  4868. // "friend void foo<>(int);" is an implicit specialization decl.
  4869. isFunctionTemplateSpecialization = true;
  4870. }
  4871. } else if (isFriend && isFunctionTemplateSpecialization) {
  4872. // This combination is only possible in a recovery case; the user
  4873. // wrote something like:
  4874. // template <> friend void foo(int);
  4875. // which we're recovering from as if the user had written:
  4876. // friend void foo<>(int);
  4877. // Go ahead and fake up a template id.
  4878. HasExplicitTemplateArgs = true;
  4879. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  4880. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  4881. }
  4882. // If it's a friend (and only if it's a friend), it's possible
  4883. // that either the specialized function type or the specialized
  4884. // template is dependent, and therefore matching will fail. In
  4885. // this case, don't check the specialization yet.
  4886. bool InstantiationDependent = false;
  4887. if (isFunctionTemplateSpecialization && isFriend &&
  4888. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  4889. TemplateSpecializationType::anyDependentTemplateArguments(
  4890. TemplateArgs.getArgumentArray(), TemplateArgs.size(),
  4891. InstantiationDependent))) {
  4892. assert(HasExplicitTemplateArgs &&
  4893. "friend function specialization without template args");
  4894. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  4895. Previous))
  4896. NewFD->setInvalidDecl();
  4897. } else if (isFunctionTemplateSpecialization) {
  4898. if (CurContext->isDependentContext() && CurContext->isRecord()
  4899. && !isFriend) {
  4900. isDependentClassScopeExplicitSpecialization = true;
  4901. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  4902. diag::ext_function_specialization_in_class :
  4903. diag::err_function_specialization_in_class)
  4904. << NewFD->getDeclName();
  4905. } else if (CheckFunctionTemplateSpecialization(NewFD,
  4906. (HasExplicitTemplateArgs ? &TemplateArgs : 0),
  4907. Previous))
  4908. NewFD->setInvalidDecl();
  4909. // C++ [dcl.stc]p1:
  4910. // A storage-class-specifier shall not be specified in an explicit
  4911. // specialization (14.7.3)
  4912. if (SC != SC_None) {
  4913. if (SC != NewFD->getStorageClass())
  4914. Diag(NewFD->getLocation(),
  4915. diag::err_explicit_specialization_inconsistent_storage_class)
  4916. << SC
  4917. << FixItHint::CreateRemoval(
  4918. D.getDeclSpec().getStorageClassSpecLoc());
  4919. else
  4920. Diag(NewFD->getLocation(),
  4921. diag::ext_explicit_specialization_storage_class)
  4922. << FixItHint::CreateRemoval(
  4923. D.getDeclSpec().getStorageClassSpecLoc());
  4924. }
  4925. } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
  4926. if (CheckMemberSpecialization(NewFD, Previous))
  4927. NewFD->setInvalidDecl();
  4928. }
  4929. // Perform semantic checking on the function declaration.
  4930. if (!isDependentClassScopeExplicitSpecialization) {
  4931. if (NewFD->isInvalidDecl()) {
  4932. // If this is a class member, mark the class invalid immediately.
  4933. // This avoids some consistency errors later.
  4934. if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
  4935. methodDecl->getParent()->setInvalidDecl();
  4936. } else {
  4937. if (NewFD->isMain())
  4938. CheckMain(NewFD, D.getDeclSpec());
  4939. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  4940. isExplicitSpecialization));
  4941. }
  4942. }
  4943. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  4944. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  4945. "previous declaration set still overloaded");
  4946. NamedDecl *PrincipalDecl = (FunctionTemplate
  4947. ? cast<NamedDecl>(FunctionTemplate)
  4948. : NewFD);
  4949. if (isFriend && D.isRedeclaration()) {
  4950. AccessSpecifier Access = AS_public;
  4951. if (!NewFD->isInvalidDecl())
  4952. Access = NewFD->getPreviousDecl()->getAccess();
  4953. NewFD->setAccess(Access);
  4954. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  4955. PrincipalDecl->setObjectOfFriendDecl(true);
  4956. }
  4957. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  4958. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  4959. PrincipalDecl->setNonMemberOperator();
  4960. // If we have a function template, check the template parameter
  4961. // list. This will check and merge default template arguments.
  4962. if (FunctionTemplate) {
  4963. FunctionTemplateDecl *PrevTemplate =
  4964. FunctionTemplate->getPreviousDecl();
  4965. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  4966. PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
  4967. D.getDeclSpec().isFriendSpecified()
  4968. ? (D.isFunctionDefinition()
  4969. ? TPC_FriendFunctionTemplateDefinition
  4970. : TPC_FriendFunctionTemplate)
  4971. : (D.getCXXScopeSpec().isSet() &&
  4972. DC && DC->isRecord() &&
  4973. DC->isDependentContext())
  4974. ? TPC_ClassTemplateMember
  4975. : TPC_FunctionTemplate);
  4976. }
  4977. if (NewFD->isInvalidDecl()) {
  4978. // Ignore all the rest of this.
  4979. } else if (!D.isRedeclaration()) {
  4980. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  4981. AddToScope };
  4982. // Fake up an access specifier if it's supposed to be a class member.
  4983. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  4984. NewFD->setAccess(AS_public);
  4985. // Qualified decls generally require a previous declaration.
  4986. if (D.getCXXScopeSpec().isSet()) {
  4987. // ...with the major exception of templated-scope or
  4988. // dependent-scope friend declarations.
  4989. // TODO: we currently also suppress this check in dependent
  4990. // contexts because (1) the parameter depth will be off when
  4991. // matching friend templates and (2) we might actually be
  4992. // selecting a friend based on a dependent factor. But there
  4993. // are situations where these conditions don't apply and we
  4994. // can actually do this check immediately.
  4995. if (isFriend &&
  4996. (TemplateParamLists.size() ||
  4997. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  4998. CurContext->isDependentContext())) {
  4999. // ignore these
  5000. } else {
  5001. // The user tried to provide an out-of-line definition for a
  5002. // function that is a member of a class or namespace, but there
  5003. // was no such member function declared (C++ [class.mfct]p2,
  5004. // C++ [namespace.memdef]p2). For example:
  5005. //
  5006. // class X {
  5007. // void f() const;
  5008. // };
  5009. //
  5010. // void X::f() { } // ill-formed
  5011. //
  5012. // Complain about this problem, and attempt to suggest close
  5013. // matches (e.g., those that differ only in cv-qualifiers and
  5014. // whether the parameter types are references).
  5015. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  5016. NewFD,
  5017. ExtraArgs)) {
  5018. AddToScope = ExtraArgs.AddToScope;
  5019. return Result;
  5020. }
  5021. }
  5022. // Unqualified local friend declarations are required to resolve
  5023. // to something.
  5024. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  5025. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
  5026. NewFD,
  5027. ExtraArgs)) {
  5028. AddToScope = ExtraArgs.AddToScope;
  5029. return Result;
  5030. }
  5031. }
  5032. } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
  5033. !isFriend && !isFunctionTemplateSpecialization &&
  5034. !isExplicitSpecialization) {
  5035. // An out-of-line member function declaration must also be a
  5036. // definition (C++ [dcl.meaning]p1).
  5037. // Note that this is not the case for explicit specializations of
  5038. // function templates or member functions of class templates, per
  5039. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  5040. // extension for compatibility with old SWIG code which likes to
  5041. // generate them.
  5042. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  5043. << D.getCXXScopeSpec().getRange();
  5044. }
  5045. }
  5046. AddKnownFunctionAttributes(NewFD);
  5047. if (NewFD->hasAttr<OverloadableAttr>() &&
  5048. !NewFD->getType()->getAs<FunctionProtoType>()) {
  5049. Diag(NewFD->getLocation(),
  5050. diag::err_attribute_overloadable_no_prototype)
  5051. << NewFD;
  5052. // Turn this into a variadic function with no parameters.
  5053. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  5054. FunctionProtoType::ExtProtoInfo EPI;
  5055. EPI.Variadic = true;
  5056. EPI.ExtInfo = FT->getExtInfo();
  5057. QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
  5058. NewFD->setType(R);
  5059. }
  5060. // If there's a #pragma GCC visibility in scope, and this isn't a class
  5061. // member, set the visibility of this function.
  5062. if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
  5063. AddPushedVisibilityAttribute(NewFD);
  5064. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  5065. // marking the function.
  5066. AddCFAuditedAttribute(NewFD);
  5067. // If this is a locally-scoped extern C function, update the
  5068. // map of such names.
  5069. if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
  5070. && !NewFD->isInvalidDecl())
  5071. RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
  5072. // Set this FunctionDecl's range up to the right paren.
  5073. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  5074. if (getLangOpts().CPlusPlus) {
  5075. if (FunctionTemplate) {
  5076. if (NewFD->isInvalidDecl())
  5077. FunctionTemplate->setInvalidDecl();
  5078. return FunctionTemplate;
  5079. }
  5080. }
  5081. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  5082. if ((getLangOpts().OpenCLVersion >= 120)
  5083. && NewFD->hasAttr<OpenCLKernelAttr>()
  5084. && (SC == SC_Static)) {
  5085. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  5086. D.setInvalidType();
  5087. }
  5088. MarkUnusedFileScopedDecl(NewFD);
  5089. if (getLangOpts().CUDA)
  5090. if (IdentifierInfo *II = NewFD->getIdentifier())
  5091. if (!NewFD->isInvalidDecl() &&
  5092. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5093. if (II->isStr("cudaConfigureCall")) {
  5094. if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
  5095. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  5096. Context.setcudaConfigureCallDecl(NewFD);
  5097. }
  5098. }
  5099. // Here we have an function template explicit specialization at class scope.
  5100. // The actually specialization will be postponed to template instatiation
  5101. // time via the ClassScopeFunctionSpecializationDecl node.
  5102. if (isDependentClassScopeExplicitSpecialization) {
  5103. ClassScopeFunctionSpecializationDecl *NewSpec =
  5104. ClassScopeFunctionSpecializationDecl::Create(
  5105. Context, CurContext, SourceLocation(),
  5106. cast<CXXMethodDecl>(NewFD),
  5107. HasExplicitTemplateArgs, TemplateArgs);
  5108. CurContext->addDecl(NewSpec);
  5109. AddToScope = false;
  5110. }
  5111. return NewFD;
  5112. }
  5113. /// \brief Perform semantic checking of a new function declaration.
  5114. ///
  5115. /// Performs semantic analysis of the new function declaration
  5116. /// NewFD. This routine performs all semantic checking that does not
  5117. /// require the actual declarator involved in the declaration, and is
  5118. /// used both for the declaration of functions as they are parsed
  5119. /// (called via ActOnDeclarator) and for the declaration of functions
  5120. /// that have been instantiated via C++ template instantiation (called
  5121. /// via InstantiateDecl).
  5122. ///
  5123. /// \param IsExplicitSpecialization whether this new function declaration is
  5124. /// an explicit specialization of the previous declaration.
  5125. ///
  5126. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  5127. ///
  5128. /// \returns true if the function declaration is a redeclaration.
  5129. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  5130. LookupResult &Previous,
  5131. bool IsExplicitSpecialization) {
  5132. assert(!NewFD->getResultType()->isVariablyModifiedType()
  5133. && "Variably modified return types are not handled here");
  5134. // Check for a previous declaration of this name.
  5135. if (Previous.empty() && NewFD->isExternC()) {
  5136. // Since we did not find anything by this name and we're declaring
  5137. // an extern "C" function, look for a non-visible extern "C"
  5138. // declaration with the same name.
  5139. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  5140. = findLocallyScopedExternalDecl(NewFD->getDeclName());
  5141. if (Pos != LocallyScopedExternalDecls.end())
  5142. Previous.addDecl(Pos->second);
  5143. }
  5144. bool Redeclaration = false;
  5145. // Merge or overload the declaration with an existing declaration of
  5146. // the same name, if appropriate.
  5147. if (!Previous.empty()) {
  5148. // Determine whether NewFD is an overload of PrevDecl or
  5149. // a declaration that requires merging. If it's an overload,
  5150. // there's no more work to do here; we'll just add the new
  5151. // function to the scope.
  5152. NamedDecl *OldDecl = 0;
  5153. if (!AllowOverloadingOfFunction(Previous, Context)) {
  5154. Redeclaration = true;
  5155. OldDecl = Previous.getFoundDecl();
  5156. } else {
  5157. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  5158. /*NewIsUsingDecl*/ false)) {
  5159. case Ovl_Match:
  5160. Redeclaration = true;
  5161. break;
  5162. case Ovl_NonFunction:
  5163. Redeclaration = true;
  5164. break;
  5165. case Ovl_Overload:
  5166. Redeclaration = false;
  5167. break;
  5168. }
  5169. if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
  5170. // If a function name is overloadable in C, then every function
  5171. // with that name must be marked "overloadable".
  5172. Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
  5173. << Redeclaration << NewFD;
  5174. NamedDecl *OverloadedDecl = 0;
  5175. if (Redeclaration)
  5176. OverloadedDecl = OldDecl;
  5177. else if (!Previous.empty())
  5178. OverloadedDecl = Previous.getRepresentativeDecl();
  5179. if (OverloadedDecl)
  5180. Diag(OverloadedDecl->getLocation(),
  5181. diag::note_attribute_overloadable_prev_overload);
  5182. NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
  5183. Context));
  5184. }
  5185. }
  5186. if (Redeclaration) {
  5187. // NewFD and OldDecl represent declarations that need to be
  5188. // merged.
  5189. if (MergeFunctionDecl(NewFD, OldDecl, S)) {
  5190. NewFD->setInvalidDecl();
  5191. return Redeclaration;
  5192. }
  5193. Previous.clear();
  5194. Previous.addDecl(OldDecl);
  5195. if (FunctionTemplateDecl *OldTemplateDecl
  5196. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  5197. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  5198. FunctionTemplateDecl *NewTemplateDecl
  5199. = NewFD->getDescribedFunctionTemplate();
  5200. assert(NewTemplateDecl && "Template/non-template mismatch");
  5201. if (CXXMethodDecl *Method
  5202. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  5203. Method->setAccess(OldTemplateDecl->getAccess());
  5204. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  5205. }
  5206. // If this is an explicit specialization of a member that is a function
  5207. // template, mark it as a member specialization.
  5208. if (IsExplicitSpecialization &&
  5209. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  5210. NewTemplateDecl->setMemberSpecialization();
  5211. assert(OldTemplateDecl->isMemberSpecialization());
  5212. }
  5213. } else {
  5214. if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
  5215. NewFD->setAccess(OldDecl->getAccess());
  5216. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  5217. }
  5218. }
  5219. }
  5220. // Semantic checking for this function declaration (in isolation).
  5221. if (getLangOpts().CPlusPlus) {
  5222. // C++-specific checks.
  5223. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  5224. CheckConstructor(Constructor);
  5225. } else if (CXXDestructorDecl *Destructor =
  5226. dyn_cast<CXXDestructorDecl>(NewFD)) {
  5227. CXXRecordDecl *Record = Destructor->getParent();
  5228. QualType ClassType = Context.getTypeDeclType(Record);
  5229. // FIXME: Shouldn't we be able to perform this check even when the class
  5230. // type is dependent? Both gcc and edg can handle that.
  5231. if (!ClassType->isDependentType()) {
  5232. DeclarationName Name
  5233. = Context.DeclarationNames.getCXXDestructorName(
  5234. Context.getCanonicalType(ClassType));
  5235. if (NewFD->getDeclName() != Name) {
  5236. Diag(NewFD->getLocation(), diag::err_destructor_name);
  5237. NewFD->setInvalidDecl();
  5238. return Redeclaration;
  5239. }
  5240. }
  5241. } else if (CXXConversionDecl *Conversion
  5242. = dyn_cast<CXXConversionDecl>(NewFD)) {
  5243. ActOnConversionDeclarator(Conversion);
  5244. }
  5245. // Find any virtual functions that this function overrides.
  5246. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  5247. if (!Method->isFunctionTemplateSpecialization() &&
  5248. !Method->getDescribedFunctionTemplate()) {
  5249. if (AddOverriddenMethods(Method->getParent(), Method)) {
  5250. // If the function was marked as "static", we have a problem.
  5251. if (NewFD->getStorageClass() == SC_Static) {
  5252. Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
  5253. << NewFD->getDeclName();
  5254. for (CXXMethodDecl::method_iterator
  5255. Overridden = Method->begin_overridden_methods(),
  5256. OverriddenEnd = Method->end_overridden_methods();
  5257. Overridden != OverriddenEnd;
  5258. ++Overridden) {
  5259. Diag((*Overridden)->getLocation(),
  5260. diag::note_overridden_virtual_function);
  5261. }
  5262. }
  5263. }
  5264. }
  5265. if (Method->isStatic())
  5266. checkThisInStaticMemberFunctionType(Method);
  5267. }
  5268. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  5269. if (NewFD->isOverloadedOperator() &&
  5270. CheckOverloadedOperatorDeclaration(NewFD)) {
  5271. NewFD->setInvalidDecl();
  5272. return Redeclaration;
  5273. }
  5274. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  5275. if (NewFD->getLiteralIdentifier() &&
  5276. CheckLiteralOperatorDeclaration(NewFD)) {
  5277. NewFD->setInvalidDecl();
  5278. return Redeclaration;
  5279. }
  5280. // In C++, check default arguments now that we have merged decls. Unless
  5281. // the lexical context is the class, because in this case this is done
  5282. // during delayed parsing anyway.
  5283. if (!CurContext->isRecord())
  5284. CheckCXXDefaultArguments(NewFD);
  5285. // If this function declares a builtin function, check the type of this
  5286. // declaration against the expected type for the builtin.
  5287. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  5288. ASTContext::GetBuiltinTypeError Error;
  5289. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  5290. if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
  5291. // The type of this function differs from the type of the builtin,
  5292. // so forget about the builtin entirely.
  5293. Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
  5294. }
  5295. }
  5296. // If this function is declared as being extern "C", then check to see if
  5297. // the function returns a UDT (class, struct, or union type) that is not C
  5298. // compatible, and if it does, warn the user.
  5299. if (NewFD->isExternC()) {
  5300. QualType R = NewFD->getResultType();
  5301. if (R->isIncompleteType() && !R->isVoidType())
  5302. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  5303. << NewFD << R;
  5304. else if (!R.isPODType(Context) && !R->isVoidType() &&
  5305. !R->isObjCObjectPointerType())
  5306. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  5307. }
  5308. }
  5309. return Redeclaration;
  5310. }
  5311. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  5312. // C++11 [basic.start.main]p3: A program that declares main to be inline,
  5313. // static or constexpr is ill-formed.
  5314. // C99 6.7.4p4: In a hosted environment, the inline function specifier
  5315. // shall not appear in a declaration of main.
  5316. // static main is not an error under C99, but we should warn about it.
  5317. if (FD->getStorageClass() == SC_Static)
  5318. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  5319. ? diag::err_static_main : diag::warn_static_main)
  5320. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  5321. if (FD->isInlineSpecified())
  5322. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  5323. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  5324. if (FD->isConstexpr()) {
  5325. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  5326. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  5327. FD->setConstexpr(false);
  5328. }
  5329. QualType T = FD->getType();
  5330. assert(T->isFunctionType() && "function decl is not of function type");
  5331. const FunctionType* FT = T->castAs<FunctionType>();
  5332. // All the standards say that main() should should return 'int'.
  5333. if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
  5334. // In C and C++, main magically returns 0 if you fall off the end;
  5335. // set the flag which tells us that.
  5336. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  5337. FD->setHasImplicitReturnZero(true);
  5338. // In C with GNU extensions we allow main() to have non-integer return
  5339. // type, but we should warn about the extension, and we disable the
  5340. // implicit-return-zero rule.
  5341. } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  5342. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  5343. // Otherwise, this is just a flat-out error.
  5344. } else {
  5345. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
  5346. FD->setInvalidDecl(true);
  5347. }
  5348. // Treat protoless main() as nullary.
  5349. if (isa<FunctionNoProtoType>(FT)) return;
  5350. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  5351. unsigned nparams = FTP->getNumArgs();
  5352. assert(FD->getNumParams() == nparams);
  5353. bool HasExtraParameters = (nparams > 3);
  5354. // Darwin passes an undocumented fourth argument of type char**. If
  5355. // other platforms start sprouting these, the logic below will start
  5356. // getting shifty.
  5357. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  5358. HasExtraParameters = false;
  5359. if (HasExtraParameters) {
  5360. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  5361. FD->setInvalidDecl(true);
  5362. nparams = 3;
  5363. }
  5364. // FIXME: a lot of the following diagnostics would be improved
  5365. // if we had some location information about types.
  5366. QualType CharPP =
  5367. Context.getPointerType(Context.getPointerType(Context.CharTy));
  5368. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  5369. for (unsigned i = 0; i < nparams; ++i) {
  5370. QualType AT = FTP->getArgType(i);
  5371. bool mismatch = true;
  5372. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  5373. mismatch = false;
  5374. else if (Expected[i] == CharPP) {
  5375. // As an extension, the following forms are okay:
  5376. // char const **
  5377. // char const * const *
  5378. // char * const *
  5379. QualifierCollector qs;
  5380. const PointerType* PT;
  5381. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  5382. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  5383. (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
  5384. qs.removeConst();
  5385. mismatch = !qs.empty();
  5386. }
  5387. }
  5388. if (mismatch) {
  5389. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  5390. // TODO: suggest replacing given type with expected type
  5391. FD->setInvalidDecl(true);
  5392. }
  5393. }
  5394. if (nparams == 1 && !FD->isInvalidDecl()) {
  5395. Diag(FD->getLocation(), diag::warn_main_one_arg);
  5396. }
  5397. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  5398. Diag(FD->getLocation(), diag::err_main_template_decl);
  5399. FD->setInvalidDecl();
  5400. }
  5401. }
  5402. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  5403. // FIXME: Need strict checking. In C89, we need to check for
  5404. // any assignment, increment, decrement, function-calls, or
  5405. // commas outside of a sizeof. In C99, it's the same list,
  5406. // except that the aforementioned are allowed in unevaluated
  5407. // expressions. Everything else falls under the
  5408. // "may accept other forms of constant expressions" exception.
  5409. // (We never end up here for C++, so the constant expression
  5410. // rules there don't matter.)
  5411. if (Init->isConstantInitializer(Context, false))
  5412. return false;
  5413. Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
  5414. << Init->getSourceRange();
  5415. return true;
  5416. }
  5417. namespace {
  5418. // Visits an initialization expression to see if OrigDecl is evaluated in
  5419. // its own initialization and throws a warning if it does.
  5420. class SelfReferenceChecker
  5421. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  5422. Sema &S;
  5423. Decl *OrigDecl;
  5424. bool isRecordType;
  5425. bool isPODType;
  5426. bool isReferenceType;
  5427. public:
  5428. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  5429. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  5430. S(S), OrigDecl(OrigDecl) {
  5431. isPODType = false;
  5432. isRecordType = false;
  5433. isReferenceType = false;
  5434. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  5435. isPODType = VD->getType().isPODType(S.Context);
  5436. isRecordType = VD->getType()->isRecordType();
  5437. isReferenceType = VD->getType()->isReferenceType();
  5438. }
  5439. }
  5440. // Sometimes, the expression passed in lacks the casts that are used
  5441. // to determine which DeclRefExpr's to check. Assume that the casts
  5442. // are present and continue visiting the expression.
  5443. void HandleExpr(Expr *E) {
  5444. // Skip checking T a = a where T is not a record or reference type.
  5445. // Doing so is a way to silence uninitialized warnings.
  5446. if (isRecordType || isReferenceType)
  5447. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  5448. HandleDeclRefExpr(DRE);
  5449. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5450. HandleValue(CO->getTrueExpr());
  5451. HandleValue(CO->getFalseExpr());
  5452. }
  5453. Visit(E);
  5454. }
  5455. // For most expressions, the cast is directly above the DeclRefExpr.
  5456. // For conditional operators, the cast can be outside the conditional
  5457. // operator if both expressions are DeclRefExpr's.
  5458. void HandleValue(Expr *E) {
  5459. E = E->IgnoreParenImpCasts();
  5460. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  5461. HandleDeclRefExpr(DRE);
  5462. return;
  5463. }
  5464. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5465. HandleValue(CO->getTrueExpr());
  5466. HandleValue(CO->getFalseExpr());
  5467. }
  5468. }
  5469. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  5470. if ((!isRecordType && E->getCastKind() == CK_LValueToRValue) ||
  5471. (isRecordType && E->getCastKind() == CK_NoOp))
  5472. HandleValue(E->getSubExpr());
  5473. Inherited::VisitImplicitCastExpr(E);
  5474. }
  5475. void VisitMemberExpr(MemberExpr *E) {
  5476. // Don't warn on arrays since they can be treated as pointers.
  5477. if (E->getType()->canDecayToPointerType()) return;
  5478. ValueDecl *VD = E->getMemberDecl();
  5479. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD);
  5480. if (isa<FieldDecl>(VD) || (MD && !MD->isStatic()))
  5481. if (DeclRefExpr *DRE
  5482. = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
  5483. HandleDeclRefExpr(DRE);
  5484. return;
  5485. }
  5486. Inherited::VisitMemberExpr(E);
  5487. }
  5488. void VisitUnaryOperator(UnaryOperator *E) {
  5489. // For POD record types, addresses of its own members are well-defined.
  5490. if (E->getOpcode() == UO_AddrOf && isRecordType && isPODType &&
  5491. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) return;
  5492. Inherited::VisitUnaryOperator(E);
  5493. }
  5494. void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
  5495. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  5496. Decl* ReferenceDecl = DRE->getDecl();
  5497. if (OrigDecl != ReferenceDecl) return;
  5498. LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
  5499. Sema::NotForRedeclaration);
  5500. unsigned diag = isReferenceType
  5501. ? diag::warn_uninit_self_reference_in_reference_init
  5502. : diag::warn_uninit_self_reference_in_init;
  5503. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  5504. S.PDiag(diag)
  5505. << Result.getLookupName()
  5506. << OrigDecl->getLocation()
  5507. << DRE->getSourceRange());
  5508. }
  5509. };
  5510. }
  5511. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  5512. void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
  5513. SelfReferenceChecker(*this, OrigDecl).HandleExpr(E);
  5514. }
  5515. /// AddInitializerToDecl - Adds the initializer Init to the
  5516. /// declaration dcl. If DirectInit is true, this is C++ direct
  5517. /// initialization rather than copy initialization.
  5518. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
  5519. bool DirectInit, bool TypeMayContainAuto) {
  5520. // If there is no declaration, there was an error parsing it. Just ignore
  5521. // the initializer.
  5522. if (RealDecl == 0 || RealDecl->isInvalidDecl())
  5523. return;
  5524. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  5525. // With declarators parsed the way they are, the parser cannot
  5526. // distinguish between a normal initializer and a pure-specifier.
  5527. // Thus this grotesque test.
  5528. IntegerLiteral *IL;
  5529. if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
  5530. Context.getCanonicalType(IL->getType()) == Context.IntTy)
  5531. CheckPureMethod(Method, Init->getSourceRange());
  5532. else {
  5533. Diag(Method->getLocation(), diag::err_member_function_initialization)
  5534. << Method->getDeclName() << Init->getSourceRange();
  5535. Method->setInvalidDecl();
  5536. }
  5537. return;
  5538. }
  5539. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  5540. if (!VDecl) {
  5541. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  5542. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  5543. RealDecl->setInvalidDecl();
  5544. return;
  5545. }
  5546. // Check for self-references within variable initializers.
  5547. // Variables declared within a function/method body (except for references)
  5548. // are handled by a dataflow analysis.
  5549. // Record types initialized by initializer list are handled here.
  5550. // Initialization by constructors are handled in TryConstructorInitialization.
  5551. if ((!VDecl->hasLocalStorage() || VDecl->getType()->isReferenceType()) &&
  5552. (isa<InitListExpr>(Init) || !VDecl->getType()->isRecordType()))
  5553. CheckSelfReference(RealDecl, Init);
  5554. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  5555. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  5556. AutoType *Auto = 0;
  5557. if (TypeMayContainAuto &&
  5558. (Auto = VDecl->getType()->getContainedAutoType()) &&
  5559. !Auto->isDeduced()) {
  5560. Expr *DeduceInit = Init;
  5561. // Initializer could be a C++ direct-initializer. Deduction only works if it
  5562. // contains exactly one expression.
  5563. if (CXXDirectInit) {
  5564. if (CXXDirectInit->getNumExprs() == 0) {
  5565. // It isn't possible to write this directly, but it is possible to
  5566. // end up in this situation with "auto x(some_pack...);"
  5567. Diag(CXXDirectInit->getLocStart(),
  5568. diag::err_auto_var_init_no_expression)
  5569. << VDecl->getDeclName() << VDecl->getType()
  5570. << VDecl->getSourceRange();
  5571. RealDecl->setInvalidDecl();
  5572. return;
  5573. } else if (CXXDirectInit->getNumExprs() > 1) {
  5574. Diag(CXXDirectInit->getExpr(1)->getLocStart(),
  5575. diag::err_auto_var_init_multiple_expressions)
  5576. << VDecl->getDeclName() << VDecl->getType()
  5577. << VDecl->getSourceRange();
  5578. RealDecl->setInvalidDecl();
  5579. return;
  5580. } else {
  5581. DeduceInit = CXXDirectInit->getExpr(0);
  5582. }
  5583. }
  5584. TypeSourceInfo *DeducedType = 0;
  5585. if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
  5586. DAR_Failed)
  5587. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  5588. if (!DeducedType) {
  5589. RealDecl->setInvalidDecl();
  5590. return;
  5591. }
  5592. VDecl->setTypeSourceInfo(DeducedType);
  5593. VDecl->setType(DeducedType->getType());
  5594. VDecl->ClearLinkageCache();
  5595. // In ARC, infer lifetime.
  5596. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  5597. VDecl->setInvalidDecl();
  5598. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  5599. // 'id' instead of a specific object type prevents most of our usual checks.
  5600. // We only want to warn outside of template instantiations, though:
  5601. // inside a template, the 'id' could have come from a parameter.
  5602. if (ActiveTemplateInstantiations.empty() &&
  5603. DeducedType->getType()->isObjCIdType()) {
  5604. SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc();
  5605. Diag(Loc, diag::warn_auto_var_is_id)
  5606. << VDecl->getDeclName() << DeduceInit->getSourceRange();
  5607. }
  5608. // If this is a redeclaration, check that the type we just deduced matches
  5609. // the previously declared type.
  5610. if (VarDecl *Old = VDecl->getPreviousDecl())
  5611. MergeVarDeclTypes(VDecl, Old);
  5612. }
  5613. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  5614. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  5615. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  5616. VDecl->setInvalidDecl();
  5617. return;
  5618. }
  5619. if (!VDecl->getType()->isDependentType()) {
  5620. // A definition must end up with a complete type, which means it must be
  5621. // complete with the restriction that an array type might be completed by
  5622. // the initializer; note that later code assumes this restriction.
  5623. QualType BaseDeclType = VDecl->getType();
  5624. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  5625. BaseDeclType = Array->getElementType();
  5626. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  5627. diag::err_typecheck_decl_incomplete_type)) {
  5628. RealDecl->setInvalidDecl();
  5629. return;
  5630. }
  5631. // The variable can not have an abstract class type.
  5632. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  5633. diag::err_abstract_type_in_decl,
  5634. AbstractVariableType))
  5635. VDecl->setInvalidDecl();
  5636. }
  5637. const VarDecl *Def;
  5638. if ((Def = VDecl->getDefinition()) && Def != VDecl) {
  5639. Diag(VDecl->getLocation(), diag::err_redefinition)
  5640. << VDecl->getDeclName();
  5641. Diag(Def->getLocation(), diag::note_previous_definition);
  5642. VDecl->setInvalidDecl();
  5643. return;
  5644. }
  5645. const VarDecl* PrevInit = 0;
  5646. if (getLangOpts().CPlusPlus) {
  5647. // C++ [class.static.data]p4
  5648. // If a static data member is of const integral or const
  5649. // enumeration type, its declaration in the class definition can
  5650. // specify a constant-initializer which shall be an integral
  5651. // constant expression (5.19). In that case, the member can appear
  5652. // in integral constant expressions. The member shall still be
  5653. // defined in a namespace scope if it is used in the program and the
  5654. // namespace scope definition shall not contain an initializer.
  5655. //
  5656. // We already performed a redefinition check above, but for static
  5657. // data members we also need to check whether there was an in-class
  5658. // declaration with an initializer.
  5659. if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
  5660. Diag(VDecl->getLocation(), diag::err_redefinition)
  5661. << VDecl->getDeclName();
  5662. Diag(PrevInit->getLocation(), diag::note_previous_definition);
  5663. return;
  5664. }
  5665. if (VDecl->hasLocalStorage())
  5666. getCurFunction()->setHasBranchProtectedScope();
  5667. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  5668. VDecl->setInvalidDecl();
  5669. return;
  5670. }
  5671. }
  5672. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  5673. // a kernel function cannot be initialized."
  5674. if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
  5675. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  5676. VDecl->setInvalidDecl();
  5677. return;
  5678. }
  5679. // Get the decls type and save a reference for later, since
  5680. // CheckInitializerTypes may change it.
  5681. QualType DclT = VDecl->getType(), SavT = DclT;
  5682. // Top-level message sends default to 'id' when we're in a debugger
  5683. // and we are assigning it to a variable of 'id' type.
  5684. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
  5685. if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
  5686. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  5687. if (Result.isInvalid()) {
  5688. VDecl->setInvalidDecl();
  5689. return;
  5690. }
  5691. Init = Result.take();
  5692. }
  5693. // Perform the initialization.
  5694. if (!VDecl->isInvalidDecl()) {
  5695. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  5696. InitializationKind Kind
  5697. = DirectInit ?
  5698. CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
  5699. Init->getLocStart(),
  5700. Init->getLocEnd())
  5701. : InitializationKind::CreateDirectList(
  5702. VDecl->getLocation())
  5703. : InitializationKind::CreateCopy(VDecl->getLocation(),
  5704. Init->getLocStart());
  5705. Expr **Args = &Init;
  5706. unsigned NumArgs = 1;
  5707. if (CXXDirectInit) {
  5708. Args = CXXDirectInit->getExprs();
  5709. NumArgs = CXXDirectInit->getNumExprs();
  5710. }
  5711. InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
  5712. ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
  5713. MultiExprArg(*this, Args,NumArgs),
  5714. &DclT);
  5715. if (Result.isInvalid()) {
  5716. VDecl->setInvalidDecl();
  5717. return;
  5718. }
  5719. Init = Result.takeAs<Expr>();
  5720. }
  5721. // If the type changed, it means we had an incomplete type that was
  5722. // completed by the initializer. For example:
  5723. // int ary[] = { 1, 3, 5 };
  5724. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  5725. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  5726. VDecl->setType(DclT);
  5727. // Check any implicit conversions within the expression.
  5728. CheckImplicitConversions(Init, VDecl->getLocation());
  5729. if (!VDecl->isInvalidDecl())
  5730. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  5731. Init = MaybeCreateExprWithCleanups(Init);
  5732. // Attach the initializer to the decl.
  5733. VDecl->setInit(Init);
  5734. if (VDecl->isLocalVarDecl()) {
  5735. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  5736. // static storage duration shall be constant expressions or string literals.
  5737. // C++ does not have this restriction.
  5738. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
  5739. VDecl->getStorageClass() == SC_Static)
  5740. CheckForConstantInitializer(Init, DclT);
  5741. } else if (VDecl->isStaticDataMember() &&
  5742. VDecl->getLexicalDeclContext()->isRecord()) {
  5743. // This is an in-class initialization for a static data member, e.g.,
  5744. //
  5745. // struct S {
  5746. // static const int value = 17;
  5747. // };
  5748. // C++ [class.mem]p4:
  5749. // A member-declarator can contain a constant-initializer only
  5750. // if it declares a static member (9.4) of const integral or
  5751. // const enumeration type, see 9.4.2.
  5752. //
  5753. // C++11 [class.static.data]p3:
  5754. // If a non-volatile const static data member is of integral or
  5755. // enumeration type, its declaration in the class definition can
  5756. // specify a brace-or-equal-initializer in which every initalizer-clause
  5757. // that is an assignment-expression is a constant expression. A static
  5758. // data member of literal type can be declared in the class definition
  5759. // with the constexpr specifier; if so, its declaration shall specify a
  5760. // brace-or-equal-initializer in which every initializer-clause that is
  5761. // an assignment-expression is a constant expression.
  5762. // Do nothing on dependent types.
  5763. if (DclT->isDependentType()) {
  5764. // Allow any 'static constexpr' members, whether or not they are of literal
  5765. // type. We separately check that every constexpr variable is of literal
  5766. // type.
  5767. } else if (VDecl->isConstexpr()) {
  5768. // Require constness.
  5769. } else if (!DclT.isConstQualified()) {
  5770. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  5771. << Init->getSourceRange();
  5772. VDecl->setInvalidDecl();
  5773. // We allow integer constant expressions in all cases.
  5774. } else if (DclT->isIntegralOrEnumerationType()) {
  5775. // Check whether the expression is a constant expression.
  5776. SourceLocation Loc;
  5777. if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
  5778. // In C++11, a non-constexpr const static data member with an
  5779. // in-class initializer cannot be volatile.
  5780. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  5781. else if (Init->isValueDependent())
  5782. ; // Nothing to check.
  5783. else if (Init->isIntegerConstantExpr(Context, &Loc))
  5784. ; // Ok, it's an ICE!
  5785. else if (Init->isEvaluatable(Context)) {
  5786. // If we can constant fold the initializer through heroics, accept it,
  5787. // but report this as a use of an extension for -pedantic.
  5788. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  5789. << Init->getSourceRange();
  5790. } else {
  5791. // Otherwise, this is some crazy unknown case. Report the issue at the
  5792. // location provided by the isIntegerConstantExpr failed check.
  5793. Diag(Loc, diag::err_in_class_initializer_non_constant)
  5794. << Init->getSourceRange();
  5795. VDecl->setInvalidDecl();
  5796. }
  5797. // We allow foldable floating-point constants as an extension.
  5798. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  5799. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  5800. << DclT << Init->getSourceRange();
  5801. if (getLangOpts().CPlusPlus0x)
  5802. Diag(VDecl->getLocation(),
  5803. diag::note_in_class_initializer_float_type_constexpr)
  5804. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5805. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  5806. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  5807. << Init->getSourceRange();
  5808. VDecl->setInvalidDecl();
  5809. }
  5810. // Suggest adding 'constexpr' in C++11 for literal types.
  5811. } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
  5812. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  5813. << DclT << Init->getSourceRange()
  5814. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  5815. VDecl->setConstexpr(true);
  5816. } else {
  5817. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  5818. << DclT << Init->getSourceRange();
  5819. VDecl->setInvalidDecl();
  5820. }
  5821. } else if (VDecl->isFileVarDecl()) {
  5822. if (VDecl->getStorageClassAsWritten() == SC_Extern &&
  5823. (!getLangOpts().CPlusPlus ||
  5824. !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
  5825. Diag(VDecl->getLocation(), diag::warn_extern_init);
  5826. // C99 6.7.8p4. All file scoped initializers need to be constant.
  5827. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  5828. CheckForConstantInitializer(Init, DclT);
  5829. }
  5830. // We will represent direct-initialization similarly to copy-initialization:
  5831. // int x(1); -as-> int x = 1;
  5832. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  5833. //
  5834. // Clients that want to distinguish between the two forms, can check for
  5835. // direct initializer using VarDecl::getInitStyle().
  5836. // A major benefit is that clients that don't particularly care about which
  5837. // exactly form was it (like the CodeGen) can handle both cases without
  5838. // special case code.
  5839. // C++ 8.5p11:
  5840. // The form of initialization (using parentheses or '=') is generally
  5841. // insignificant, but does matter when the entity being initialized has a
  5842. // class type.
  5843. if (CXXDirectInit) {
  5844. assert(DirectInit && "Call-style initializer must be direct init.");
  5845. VDecl->setInitStyle(VarDecl::CallInit);
  5846. } else if (DirectInit) {
  5847. // This must be list-initialization. No other way is direct-initialization.
  5848. VDecl->setInitStyle(VarDecl::ListInit);
  5849. }
  5850. CheckCompleteVariableDeclaration(VDecl);
  5851. }
  5852. /// ActOnInitializerError - Given that there was an error parsing an
  5853. /// initializer for the given declaration, try to return to some form
  5854. /// of sanity.
  5855. void Sema::ActOnInitializerError(Decl *D) {
  5856. // Our main concern here is re-establishing invariants like "a
  5857. // variable's type is either dependent or complete".
  5858. if (!D || D->isInvalidDecl()) return;
  5859. VarDecl *VD = dyn_cast<VarDecl>(D);
  5860. if (!VD) return;
  5861. // Auto types are meaningless if we can't make sense of the initializer.
  5862. if (ParsingInitForAutoVars.count(D)) {
  5863. D->setInvalidDecl();
  5864. return;
  5865. }
  5866. QualType Ty = VD->getType();
  5867. if (Ty->isDependentType()) return;
  5868. // Require a complete type.
  5869. if (RequireCompleteType(VD->getLocation(),
  5870. Context.getBaseElementType(Ty),
  5871. diag::err_typecheck_decl_incomplete_type)) {
  5872. VD->setInvalidDecl();
  5873. return;
  5874. }
  5875. // Require an abstract type.
  5876. if (RequireNonAbstractType(VD->getLocation(), Ty,
  5877. diag::err_abstract_type_in_decl,
  5878. AbstractVariableType)) {
  5879. VD->setInvalidDecl();
  5880. return;
  5881. }
  5882. // Don't bother complaining about constructors or destructors,
  5883. // though.
  5884. }
  5885. void Sema::ActOnUninitializedDecl(Decl *RealDecl,
  5886. bool TypeMayContainAuto) {
  5887. // If there is no declaration, there was an error parsing it. Just ignore it.
  5888. if (RealDecl == 0)
  5889. return;
  5890. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  5891. QualType Type = Var->getType();
  5892. // C++11 [dcl.spec.auto]p3
  5893. if (TypeMayContainAuto && Type->getContainedAutoType()) {
  5894. Diag(Var->getLocation(), diag::err_auto_var_requires_init)
  5895. << Var->getDeclName() << Type;
  5896. Var->setInvalidDecl();
  5897. return;
  5898. }
  5899. // C++11 [class.static.data]p3: A static data member can be declared with
  5900. // the constexpr specifier; if so, its declaration shall specify
  5901. // a brace-or-equal-initializer.
  5902. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  5903. // the definition of a variable [...] or the declaration of a static data
  5904. // member.
  5905. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
  5906. if (Var->isStaticDataMember())
  5907. Diag(Var->getLocation(),
  5908. diag::err_constexpr_static_mem_var_requires_init)
  5909. << Var->getDeclName();
  5910. else
  5911. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  5912. Var->setInvalidDecl();
  5913. return;
  5914. }
  5915. switch (Var->isThisDeclarationADefinition()) {
  5916. case VarDecl::Definition:
  5917. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  5918. break;
  5919. // We have an out-of-line definition of a static data member
  5920. // that has an in-class initializer, so we type-check this like
  5921. // a declaration.
  5922. //
  5923. // Fall through
  5924. case VarDecl::DeclarationOnly:
  5925. // It's only a declaration.
  5926. // Block scope. C99 6.7p7: If an identifier for an object is
  5927. // declared with no linkage (C99 6.2.2p6), the type for the
  5928. // object shall be complete.
  5929. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  5930. !Var->getLinkage() && !Var->isInvalidDecl() &&
  5931. RequireCompleteType(Var->getLocation(), Type,
  5932. diag::err_typecheck_decl_incomplete_type))
  5933. Var->setInvalidDecl();
  5934. // Make sure that the type is not abstract.
  5935. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  5936. RequireNonAbstractType(Var->getLocation(), Type,
  5937. diag::err_abstract_type_in_decl,
  5938. AbstractVariableType))
  5939. Var->setInvalidDecl();
  5940. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  5941. Var->getStorageClass() == SC_PrivateExtern) {
  5942. Diag(Var->getLocation(), diag::warn_private_extern);
  5943. Diag(Var->getLocation(), diag::note_private_extern);
  5944. }
  5945. return;
  5946. case VarDecl::TentativeDefinition:
  5947. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  5948. // object that has file scope without an initializer, and without a
  5949. // storage-class specifier or with the storage-class specifier "static",
  5950. // constitutes a tentative definition. Note: A tentative definition with
  5951. // external linkage is valid (C99 6.2.2p5).
  5952. if (!Var->isInvalidDecl()) {
  5953. if (const IncompleteArrayType *ArrayT
  5954. = Context.getAsIncompleteArrayType(Type)) {
  5955. if (RequireCompleteType(Var->getLocation(),
  5956. ArrayT->getElementType(),
  5957. diag::err_illegal_decl_array_incomplete_type))
  5958. Var->setInvalidDecl();
  5959. } else if (Var->getStorageClass() == SC_Static) {
  5960. // C99 6.9.2p3: If the declaration of an identifier for an object is
  5961. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  5962. // declared type shall not be an incomplete type.
  5963. // NOTE: code such as the following
  5964. // static struct s;
  5965. // struct s { int a; };
  5966. // is accepted by gcc. Hence here we issue a warning instead of
  5967. // an error and we do not invalidate the static declaration.
  5968. // NOTE: to avoid multiple warnings, only check the first declaration.
  5969. if (Var->getPreviousDecl() == 0)
  5970. RequireCompleteType(Var->getLocation(), Type,
  5971. diag::ext_typecheck_decl_incomplete_type);
  5972. }
  5973. }
  5974. // Record the tentative definition; we're done.
  5975. if (!Var->isInvalidDecl())
  5976. TentativeDefinitions.push_back(Var);
  5977. return;
  5978. }
  5979. // Provide a specific diagnostic for uninitialized variable
  5980. // definitions with incomplete array type.
  5981. if (Type->isIncompleteArrayType()) {
  5982. Diag(Var->getLocation(),
  5983. diag::err_typecheck_incomplete_array_needs_initializer);
  5984. Var->setInvalidDecl();
  5985. return;
  5986. }
  5987. // Provide a specific diagnostic for uninitialized variable
  5988. // definitions with reference type.
  5989. if (Type->isReferenceType()) {
  5990. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  5991. << Var->getDeclName()
  5992. << SourceRange(Var->getLocation(), Var->getLocation());
  5993. Var->setInvalidDecl();
  5994. return;
  5995. }
  5996. // Do not attempt to type-check the default initializer for a
  5997. // variable with dependent type.
  5998. if (Type->isDependentType())
  5999. return;
  6000. if (Var->isInvalidDecl())
  6001. return;
  6002. if (RequireCompleteType(Var->getLocation(),
  6003. Context.getBaseElementType(Type),
  6004. diag::err_typecheck_decl_incomplete_type)) {
  6005. Var->setInvalidDecl();
  6006. return;
  6007. }
  6008. // The variable can not have an abstract class type.
  6009. if (RequireNonAbstractType(Var->getLocation(), Type,
  6010. diag::err_abstract_type_in_decl,
  6011. AbstractVariableType)) {
  6012. Var->setInvalidDecl();
  6013. return;
  6014. }
  6015. // Check for jumps past the implicit initializer. C++0x
  6016. // clarifies that this applies to a "variable with automatic
  6017. // storage duration", not a "local variable".
  6018. // C++11 [stmt.dcl]p3
  6019. // A program that jumps from a point where a variable with automatic
  6020. // storage duration is not in scope to a point where it is in scope is
  6021. // ill-formed unless the variable has scalar type, class type with a
  6022. // trivial default constructor and a trivial destructor, a cv-qualified
  6023. // version of one of these types, or an array of one of the preceding
  6024. // types and is declared without an initializer.
  6025. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  6026. if (const RecordType *Record
  6027. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  6028. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  6029. // Mark the function for further checking even if the looser rules of
  6030. // C++11 do not require such checks, so that we can diagnose
  6031. // incompatibilities with C++98.
  6032. if (!CXXRecord->isPOD())
  6033. getCurFunction()->setHasBranchProtectedScope();
  6034. }
  6035. }
  6036. // C++03 [dcl.init]p9:
  6037. // If no initializer is specified for an object, and the
  6038. // object is of (possibly cv-qualified) non-POD class type (or
  6039. // array thereof), the object shall be default-initialized; if
  6040. // the object is of const-qualified type, the underlying class
  6041. // type shall have a user-declared default
  6042. // constructor. Otherwise, if no initializer is specified for
  6043. // a non- static object, the object and its subobjects, if
  6044. // any, have an indeterminate initial value); if the object
  6045. // or any of its subobjects are of const-qualified type, the
  6046. // program is ill-formed.
  6047. // C++0x [dcl.init]p11:
  6048. // If no initializer is specified for an object, the object is
  6049. // default-initialized; [...].
  6050. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  6051. InitializationKind Kind
  6052. = InitializationKind::CreateDefault(Var->getLocation());
  6053. InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
  6054. ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
  6055. MultiExprArg(*this, 0, 0));
  6056. if (Init.isInvalid())
  6057. Var->setInvalidDecl();
  6058. else if (Init.get()) {
  6059. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  6060. // This is important for template substitution.
  6061. Var->setInitStyle(VarDecl::CallInit);
  6062. }
  6063. CheckCompleteVariableDeclaration(Var);
  6064. }
  6065. }
  6066. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  6067. VarDecl *VD = dyn_cast<VarDecl>(D);
  6068. if (!VD) {
  6069. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  6070. D->setInvalidDecl();
  6071. return;
  6072. }
  6073. VD->setCXXForRangeDecl(true);
  6074. // for-range-declaration cannot be given a storage class specifier.
  6075. int Error = -1;
  6076. switch (VD->getStorageClassAsWritten()) {
  6077. case SC_None:
  6078. break;
  6079. case SC_Extern:
  6080. Error = 0;
  6081. break;
  6082. case SC_Static:
  6083. Error = 1;
  6084. break;
  6085. case SC_PrivateExtern:
  6086. Error = 2;
  6087. break;
  6088. case SC_Auto:
  6089. Error = 3;
  6090. break;
  6091. case SC_Register:
  6092. Error = 4;
  6093. break;
  6094. case SC_OpenCLWorkGroupLocal:
  6095. llvm_unreachable("Unexpected storage class");
  6096. }
  6097. if (VD->isConstexpr())
  6098. Error = 5;
  6099. if (Error != -1) {
  6100. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  6101. << VD->getDeclName() << Error;
  6102. D->setInvalidDecl();
  6103. }
  6104. }
  6105. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  6106. if (var->isInvalidDecl()) return;
  6107. // In ARC, don't allow jumps past the implicit initialization of a
  6108. // local retaining variable.
  6109. if (getLangOpts().ObjCAutoRefCount &&
  6110. var->hasLocalStorage()) {
  6111. switch (var->getType().getObjCLifetime()) {
  6112. case Qualifiers::OCL_None:
  6113. case Qualifiers::OCL_ExplicitNone:
  6114. case Qualifiers::OCL_Autoreleasing:
  6115. break;
  6116. case Qualifiers::OCL_Weak:
  6117. case Qualifiers::OCL_Strong:
  6118. getCurFunction()->setHasBranchProtectedScope();
  6119. break;
  6120. }
  6121. }
  6122. // All the following checks are C++ only.
  6123. if (!getLangOpts().CPlusPlus) return;
  6124. QualType baseType = Context.getBaseElementType(var->getType());
  6125. if (baseType->isDependentType()) return;
  6126. // __block variables might require us to capture a copy-initializer.
  6127. if (var->hasAttr<BlocksAttr>()) {
  6128. // It's currently invalid to ever have a __block variable with an
  6129. // array type; should we diagnose that here?
  6130. // Regardless, we don't want to ignore array nesting when
  6131. // constructing this copy.
  6132. QualType type = var->getType();
  6133. if (type->isStructureOrClassType()) {
  6134. SourceLocation poi = var->getLocation();
  6135. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  6136. ExprResult result =
  6137. PerformCopyInitialization(
  6138. InitializedEntity::InitializeBlock(poi, type, false),
  6139. poi, Owned(varRef));
  6140. if (!result.isInvalid()) {
  6141. result = MaybeCreateExprWithCleanups(result);
  6142. Expr *init = result.takeAs<Expr>();
  6143. Context.setBlockVarCopyInits(var, init);
  6144. }
  6145. }
  6146. }
  6147. Expr *Init = var->getInit();
  6148. bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
  6149. if (!var->getDeclContext()->isDependentContext() && Init) {
  6150. if (IsGlobal && !var->isConstexpr() &&
  6151. getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
  6152. var->getLocation())
  6153. != DiagnosticsEngine::Ignored &&
  6154. !Init->isConstantInitializer(Context, baseType->isReferenceType()))
  6155. Diag(var->getLocation(), diag::warn_global_constructor)
  6156. << Init->getSourceRange();
  6157. if (var->isConstexpr()) {
  6158. llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
  6159. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  6160. SourceLocation DiagLoc = var->getLocation();
  6161. // If the note doesn't add any useful information other than a source
  6162. // location, fold it into the primary diagnostic.
  6163. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  6164. diag::note_invalid_subexpr_in_const_expr) {
  6165. DiagLoc = Notes[0].first;
  6166. Notes.clear();
  6167. }
  6168. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  6169. << var << Init->getSourceRange();
  6170. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  6171. Diag(Notes[I].first, Notes[I].second);
  6172. }
  6173. } else if (var->isUsableInConstantExpressions(Context)) {
  6174. // Check whether the initializer of a const variable of integral or
  6175. // enumeration type is an ICE now, since we can't tell whether it was
  6176. // initialized by a constant expression if we check later.
  6177. var->checkInitIsICE();
  6178. }
  6179. }
  6180. // Require the destructor.
  6181. if (const RecordType *recordType = baseType->getAs<RecordType>())
  6182. FinalizeVarWithDestructor(var, recordType);
  6183. }
  6184. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  6185. /// any semantic actions necessary after any initializer has been attached.
  6186. void
  6187. Sema::FinalizeDeclaration(Decl *ThisDecl) {
  6188. // Note that we are no longer parsing the initializer for this declaration.
  6189. ParsingInitForAutoVars.erase(ThisDecl);
  6190. // Now we have parsed the initializer and can update the table of magic
  6191. // tag values.
  6192. if (ThisDecl && ThisDecl->hasAttr<TypeTagForDatatypeAttr>()) {
  6193. const VarDecl *VD = dyn_cast<VarDecl>(ThisDecl);
  6194. if (VD && VD->getType()->isIntegralOrEnumerationType()) {
  6195. for (specific_attr_iterator<TypeTagForDatatypeAttr>
  6196. I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
  6197. E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
  6198. I != E; ++I) {
  6199. const Expr *MagicValueExpr = VD->getInit();
  6200. if (!MagicValueExpr) {
  6201. continue;
  6202. }
  6203. llvm::APSInt MagicValueInt;
  6204. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  6205. Diag(I->getRange().getBegin(),
  6206. diag::err_type_tag_for_datatype_not_ice)
  6207. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  6208. continue;
  6209. }
  6210. if (MagicValueInt.getActiveBits() > 64) {
  6211. Diag(I->getRange().getBegin(),
  6212. diag::err_type_tag_for_datatype_too_large)
  6213. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  6214. continue;
  6215. }
  6216. uint64_t MagicValue = MagicValueInt.getZExtValue();
  6217. RegisterTypeTagForDatatype(I->getArgumentKind(),
  6218. MagicValue,
  6219. I->getMatchingCType(),
  6220. I->getLayoutCompatible(),
  6221. I->getMustBeNull());
  6222. }
  6223. }
  6224. }
  6225. }
  6226. Sema::DeclGroupPtrTy
  6227. Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  6228. Decl **Group, unsigned NumDecls) {
  6229. SmallVector<Decl*, 8> Decls;
  6230. if (DS.isTypeSpecOwned())
  6231. Decls.push_back(DS.getRepAsDecl());
  6232. for (unsigned i = 0; i != NumDecls; ++i)
  6233. if (Decl *D = Group[i])
  6234. Decls.push_back(D);
  6235. return BuildDeclaratorGroup(Decls.data(), Decls.size(),
  6236. DS.getTypeSpecType() == DeclSpec::TST_auto);
  6237. }
  6238. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  6239. /// group, performing any necessary semantic checking.
  6240. Sema::DeclGroupPtrTy
  6241. Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
  6242. bool TypeMayContainAuto) {
  6243. // C++0x [dcl.spec.auto]p7:
  6244. // If the type deduced for the template parameter U is not the same in each
  6245. // deduction, the program is ill-formed.
  6246. // FIXME: When initializer-list support is added, a distinction is needed
  6247. // between the deduced type U and the deduced type which 'auto' stands for.
  6248. // auto a = 0, b = { 1, 2, 3 };
  6249. // is legal because the deduced type U is 'int' in both cases.
  6250. if (TypeMayContainAuto && NumDecls > 1) {
  6251. QualType Deduced;
  6252. CanQualType DeducedCanon;
  6253. VarDecl *DeducedDecl = 0;
  6254. for (unsigned i = 0; i != NumDecls; ++i) {
  6255. if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
  6256. AutoType *AT = D->getType()->getContainedAutoType();
  6257. // Don't reissue diagnostics when instantiating a template.
  6258. if (AT && D->isInvalidDecl())
  6259. break;
  6260. if (AT && AT->isDeduced()) {
  6261. QualType U = AT->getDeducedType();
  6262. CanQualType UCanon = Context.getCanonicalType(U);
  6263. if (Deduced.isNull()) {
  6264. Deduced = U;
  6265. DeducedCanon = UCanon;
  6266. DeducedDecl = D;
  6267. } else if (DeducedCanon != UCanon) {
  6268. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  6269. diag::err_auto_different_deductions)
  6270. << Deduced << DeducedDecl->getDeclName()
  6271. << U << D->getDeclName()
  6272. << DeducedDecl->getInit()->getSourceRange()
  6273. << D->getInit()->getSourceRange();
  6274. D->setInvalidDecl();
  6275. break;
  6276. }
  6277. }
  6278. }
  6279. }
  6280. }
  6281. ActOnDocumentableDecls(Group, NumDecls);
  6282. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
  6283. }
  6284. void Sema::ActOnDocumentableDecl(Decl *D) {
  6285. ActOnDocumentableDecls(&D, 1);
  6286. }
  6287. void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) {
  6288. // Don't parse the comment if Doxygen diagnostics are ignored.
  6289. if (NumDecls == 0 || !Group[0])
  6290. return;
  6291. if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
  6292. Group[0]->getLocation())
  6293. == DiagnosticsEngine::Ignored)
  6294. return;
  6295. if (NumDecls >= 2) {
  6296. // This is a decl group. Normally it will contain only declarations
  6297. // procuded from declarator list. But in case we have any definitions or
  6298. // additional declaration references:
  6299. // 'typedef struct S {} S;'
  6300. // 'typedef struct S *S;'
  6301. // 'struct S *pS;'
  6302. // FinalizeDeclaratorGroup adds these as separate declarations.
  6303. Decl *MaybeTagDecl = Group[0];
  6304. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  6305. Group++;
  6306. NumDecls--;
  6307. }
  6308. }
  6309. // See if there are any new comments that are not attached to a decl.
  6310. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  6311. if (!Comments.empty() &&
  6312. !Comments.back()->isAttached()) {
  6313. // There is at least one comment that not attached to a decl.
  6314. // Maybe it should be attached to one of these decls?
  6315. //
  6316. // Note that this way we pick up not only comments that precede the
  6317. // declaration, but also comments that *follow* the declaration -- thanks to
  6318. // the lookahead in the lexer: we've consumed the semicolon and looked
  6319. // ahead through comments.
  6320. for (unsigned i = 0; i != NumDecls; ++i)
  6321. Context.getCommentForDecl(Group[i]);
  6322. }
  6323. }
  6324. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  6325. /// to introduce parameters into function prototype scope.
  6326. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  6327. const DeclSpec &DS = D.getDeclSpec();
  6328. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  6329. // C++03 [dcl.stc]p2 also permits 'auto'.
  6330. VarDecl::StorageClass StorageClass = SC_None;
  6331. VarDecl::StorageClass StorageClassAsWritten = SC_None;
  6332. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  6333. StorageClass = SC_Register;
  6334. StorageClassAsWritten = SC_Register;
  6335. } else if (getLangOpts().CPlusPlus &&
  6336. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  6337. StorageClass = SC_Auto;
  6338. StorageClassAsWritten = SC_Auto;
  6339. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  6340. Diag(DS.getStorageClassSpecLoc(),
  6341. diag::err_invalid_storage_class_in_func_decl);
  6342. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6343. }
  6344. if (D.getDeclSpec().isThreadSpecified())
  6345. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  6346. if (D.getDeclSpec().isConstexprSpecified())
  6347. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  6348. << 0;
  6349. DiagnoseFunctionSpecifiers(D);
  6350. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  6351. QualType parmDeclType = TInfo->getType();
  6352. if (getLangOpts().CPlusPlus) {
  6353. // Check that there are no default arguments inside the type of this
  6354. // parameter.
  6355. CheckExtraCXXDefaultArguments(D);
  6356. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  6357. if (D.getCXXScopeSpec().isSet()) {
  6358. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  6359. << D.getCXXScopeSpec().getRange();
  6360. D.getCXXScopeSpec().clear();
  6361. }
  6362. }
  6363. // Ensure we have a valid name
  6364. IdentifierInfo *II = 0;
  6365. if (D.hasName()) {
  6366. II = D.getIdentifier();
  6367. if (!II) {
  6368. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  6369. << GetNameForDeclarator(D).getName().getAsString();
  6370. D.setInvalidType(true);
  6371. }
  6372. }
  6373. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  6374. if (II) {
  6375. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  6376. ForRedeclaration);
  6377. LookupName(R, S);
  6378. if (R.isSingleResult()) {
  6379. NamedDecl *PrevDecl = R.getFoundDecl();
  6380. if (PrevDecl->isTemplateParameter()) {
  6381. // Maybe we will complain about the shadowed template parameter.
  6382. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  6383. // Just pretend that we didn't see the previous declaration.
  6384. PrevDecl = 0;
  6385. } else if (S->isDeclScope(PrevDecl)) {
  6386. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  6387. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  6388. // Recover by removing the name
  6389. II = 0;
  6390. D.SetIdentifier(0, D.getIdentifierLoc());
  6391. D.setInvalidType(true);
  6392. }
  6393. }
  6394. }
  6395. // Temporarily put parameter variables in the translation unit, not
  6396. // the enclosing context. This prevents them from accidentally
  6397. // looking like class members in C++.
  6398. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  6399. D.getLocStart(),
  6400. D.getIdentifierLoc(), II,
  6401. parmDeclType, TInfo,
  6402. StorageClass, StorageClassAsWritten);
  6403. if (D.isInvalidType())
  6404. New->setInvalidDecl();
  6405. assert(S->isFunctionPrototypeScope());
  6406. assert(S->getFunctionPrototypeDepth() >= 1);
  6407. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  6408. S->getNextFunctionPrototypeIndex());
  6409. // Add the parameter declaration into this scope.
  6410. S->AddDecl(New);
  6411. if (II)
  6412. IdResolver.AddDecl(New);
  6413. ProcessDeclAttributes(S, New, D);
  6414. if (D.getDeclSpec().isModulePrivateSpecified())
  6415. Diag(New->getLocation(), diag::err_module_private_local)
  6416. << 1 << New->getDeclName()
  6417. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6418. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6419. if (New->hasAttr<BlocksAttr>()) {
  6420. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  6421. }
  6422. return New;
  6423. }
  6424. /// \brief Synthesizes a variable for a parameter arising from a
  6425. /// typedef.
  6426. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  6427. SourceLocation Loc,
  6428. QualType T) {
  6429. /* FIXME: setting StartLoc == Loc.
  6430. Would it be worth to modify callers so as to provide proper source
  6431. location for the unnamed parameters, embedding the parameter's type? */
  6432. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
  6433. T, Context.getTrivialTypeSourceInfo(T, Loc),
  6434. SC_None, SC_None, 0);
  6435. Param->setImplicit();
  6436. return Param;
  6437. }
  6438. void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
  6439. ParmVarDecl * const *ParamEnd) {
  6440. // Don't diagnose unused-parameter errors in template instantiations; we
  6441. // will already have done so in the template itself.
  6442. if (!ActiveTemplateInstantiations.empty())
  6443. return;
  6444. for (; Param != ParamEnd; ++Param) {
  6445. if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
  6446. !(*Param)->hasAttr<UnusedAttr>()) {
  6447. Diag((*Param)->getLocation(), diag::warn_unused_parameter)
  6448. << (*Param)->getDeclName();
  6449. }
  6450. }
  6451. }
  6452. void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
  6453. ParmVarDecl * const *ParamEnd,
  6454. QualType ReturnTy,
  6455. NamedDecl *D) {
  6456. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  6457. return;
  6458. // Warn if the return value is pass-by-value and larger than the specified
  6459. // threshold.
  6460. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  6461. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  6462. if (Size > LangOpts.NumLargeByValueCopy)
  6463. Diag(D->getLocation(), diag::warn_return_value_size)
  6464. << D->getDeclName() << Size;
  6465. }
  6466. // Warn if any parameter is pass-by-value and larger than the specified
  6467. // threshold.
  6468. for (; Param != ParamEnd; ++Param) {
  6469. QualType T = (*Param)->getType();
  6470. if (T->isDependentType() || !T.isPODType(Context))
  6471. continue;
  6472. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  6473. if (Size > LangOpts.NumLargeByValueCopy)
  6474. Diag((*Param)->getLocation(), diag::warn_parameter_size)
  6475. << (*Param)->getDeclName() << Size;
  6476. }
  6477. }
  6478. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  6479. SourceLocation NameLoc, IdentifierInfo *Name,
  6480. QualType T, TypeSourceInfo *TSInfo,
  6481. VarDecl::StorageClass StorageClass,
  6482. VarDecl::StorageClass StorageClassAsWritten) {
  6483. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  6484. if (getLangOpts().ObjCAutoRefCount &&
  6485. T.getObjCLifetime() == Qualifiers::OCL_None &&
  6486. T->isObjCLifetimeType()) {
  6487. Qualifiers::ObjCLifetime lifetime;
  6488. // Special cases for arrays:
  6489. // - if it's const, use __unsafe_unretained
  6490. // - otherwise, it's an error
  6491. if (T->isArrayType()) {
  6492. if (!T.isConstQualified()) {
  6493. DelayedDiagnostics.add(
  6494. sema::DelayedDiagnostic::makeForbiddenType(
  6495. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  6496. }
  6497. lifetime = Qualifiers::OCL_ExplicitNone;
  6498. } else {
  6499. lifetime = T->getObjCARCImplicitLifetime();
  6500. }
  6501. T = Context.getLifetimeQualifiedType(T, lifetime);
  6502. }
  6503. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  6504. Context.getAdjustedParameterType(T),
  6505. TSInfo,
  6506. StorageClass, StorageClassAsWritten,
  6507. 0);
  6508. // Parameters can not be abstract class types.
  6509. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6510. // the class has been completely parsed.
  6511. if (!CurContext->isRecord() &&
  6512. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  6513. AbstractParamType))
  6514. New->setInvalidDecl();
  6515. // Parameter declarators cannot be interface types. All ObjC objects are
  6516. // passed by reference.
  6517. if (T->isObjCObjectType()) {
  6518. SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
  6519. Diag(NameLoc,
  6520. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  6521. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  6522. T = Context.getObjCObjectPointerType(T);
  6523. New->setType(T);
  6524. }
  6525. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  6526. // duration shall not be qualified by an address-space qualifier."
  6527. // Since all parameters have automatic store duration, they can not have
  6528. // an address space.
  6529. if (T.getAddressSpace() != 0) {
  6530. Diag(NameLoc, diag::err_arg_with_address_space);
  6531. New->setInvalidDecl();
  6532. }
  6533. return New;
  6534. }
  6535. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  6536. SourceLocation LocAfterDecls) {
  6537. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  6538. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  6539. // for a K&R function.
  6540. if (!FTI.hasPrototype) {
  6541. for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
  6542. --i;
  6543. if (FTI.ArgInfo[i].Param == 0) {
  6544. SmallString<256> Code;
  6545. llvm::raw_svector_ostream(Code) << " int "
  6546. << FTI.ArgInfo[i].Ident->getName()
  6547. << ";\n";
  6548. Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
  6549. << FTI.ArgInfo[i].Ident
  6550. << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
  6551. // Implicitly declare the argument as type 'int' for lack of a better
  6552. // type.
  6553. AttributeFactory attrs;
  6554. DeclSpec DS(attrs);
  6555. const char* PrevSpec; // unused
  6556. unsigned DiagID; // unused
  6557. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
  6558. PrevSpec, DiagID);
  6559. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  6560. ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
  6561. FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
  6562. }
  6563. }
  6564. }
  6565. }
  6566. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
  6567. assert(getCurFunctionDecl() == 0 && "Function parsing confused");
  6568. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  6569. Scope *ParentScope = FnBodyScope->getParent();
  6570. D.setFunctionDefinitionKind(FDK_Definition);
  6571. Decl *DP = HandleDeclarator(ParentScope, D,
  6572. MultiTemplateParamsArg(*this));
  6573. return ActOnStartOfFunctionDef(FnBodyScope, DP);
  6574. }
  6575. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
  6576. // Don't warn about invalid declarations.
  6577. if (FD->isInvalidDecl())
  6578. return false;
  6579. // Or declarations that aren't global.
  6580. if (!FD->isGlobal())
  6581. return false;
  6582. // Don't warn about C++ member functions.
  6583. if (isa<CXXMethodDecl>(FD))
  6584. return false;
  6585. // Don't warn about 'main'.
  6586. if (FD->isMain())
  6587. return false;
  6588. // Don't warn about inline functions.
  6589. if (FD->isInlined())
  6590. return false;
  6591. // Don't warn about function templates.
  6592. if (FD->getDescribedFunctionTemplate())
  6593. return false;
  6594. // Don't warn about function template specializations.
  6595. if (FD->isFunctionTemplateSpecialization())
  6596. return false;
  6597. // Don't warn for OpenCL kernels.
  6598. if (FD->hasAttr<OpenCLKernelAttr>())
  6599. return false;
  6600. bool MissingPrototype = true;
  6601. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  6602. Prev; Prev = Prev->getPreviousDecl()) {
  6603. // Ignore any declarations that occur in function or method
  6604. // scope, because they aren't visible from the header.
  6605. if (Prev->getDeclContext()->isFunctionOrMethod())
  6606. continue;
  6607. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  6608. break;
  6609. }
  6610. return MissingPrototype;
  6611. }
  6612. void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
  6613. // Don't complain if we're in GNU89 mode and the previous definition
  6614. // was an extern inline function.
  6615. const FunctionDecl *Definition;
  6616. if (FD->isDefined(Definition) &&
  6617. !canRedefineFunction(Definition, getLangOpts())) {
  6618. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  6619. Definition->getStorageClass() == SC_Extern)
  6620. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  6621. << FD->getDeclName() << getLangOpts().CPlusPlus;
  6622. else
  6623. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  6624. Diag(Definition->getLocation(), diag::note_previous_definition);
  6625. FD->setInvalidDecl();
  6626. }
  6627. }
  6628. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
  6629. // Clear the last template instantiation error context.
  6630. LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
  6631. if (!D)
  6632. return D;
  6633. FunctionDecl *FD = 0;
  6634. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  6635. FD = FunTmpl->getTemplatedDecl();
  6636. else
  6637. FD = cast<FunctionDecl>(D);
  6638. // Enter a new function scope
  6639. PushFunctionScope();
  6640. // See if this is a redefinition.
  6641. if (!FD->isLateTemplateParsed())
  6642. CheckForFunctionRedefinition(FD);
  6643. // Builtin functions cannot be defined.
  6644. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6645. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  6646. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  6647. FD->setInvalidDecl();
  6648. }
  6649. }
  6650. // The return type of a function definition must be complete
  6651. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  6652. QualType ResultType = FD->getResultType();
  6653. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  6654. !FD->isInvalidDecl() &&
  6655. RequireCompleteType(FD->getLocation(), ResultType,
  6656. diag::err_func_def_incomplete_result))
  6657. FD->setInvalidDecl();
  6658. // GNU warning -Wmissing-prototypes:
  6659. // Warn if a global function is defined without a previous
  6660. // prototype declaration. This warning is issued even if the
  6661. // definition itself provides a prototype. The aim is to detect
  6662. // global functions that fail to be declared in header files.
  6663. if (ShouldWarnAboutMissingPrototype(FD))
  6664. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  6665. if (FnBodyScope)
  6666. PushDeclContext(FnBodyScope, FD);
  6667. // Check the validity of our function parameters
  6668. CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
  6669. /*CheckParameterNames=*/true);
  6670. // Introduce our parameters into the function scope
  6671. for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
  6672. ParmVarDecl *Param = FD->getParamDecl(p);
  6673. Param->setOwningFunction(FD);
  6674. // If this has an identifier, add it to the scope stack.
  6675. if (Param->getIdentifier() && FnBodyScope) {
  6676. CheckShadow(FnBodyScope, Param);
  6677. PushOnScopeChains(Param, FnBodyScope);
  6678. }
  6679. }
  6680. // If we had any tags defined in the function prototype,
  6681. // introduce them into the function scope.
  6682. if (FnBodyScope) {
  6683. for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
  6684. E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
  6685. NamedDecl *D = *I;
  6686. // Some of these decls (like enums) may have been pinned to the translation unit
  6687. // for lack of a real context earlier. If so, remove from the translation unit
  6688. // and reattach to the current context.
  6689. if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
  6690. // Is the decl actually in the context?
  6691. for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
  6692. DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
  6693. if (*DI == D) {
  6694. Context.getTranslationUnitDecl()->removeDecl(D);
  6695. break;
  6696. }
  6697. }
  6698. // Either way, reassign the lexical decl context to our FunctionDecl.
  6699. D->setLexicalDeclContext(CurContext);
  6700. }
  6701. // If the decl has a non-null name, make accessible in the current scope.
  6702. if (!D->getName().empty())
  6703. PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
  6704. // Similarly, dive into enums and fish their constants out, making them
  6705. // accessible in this scope.
  6706. if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  6707. for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
  6708. EE = ED->enumerator_end(); EI != EE; ++EI)
  6709. PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
  6710. }
  6711. }
  6712. }
  6713. // Ensure that the function's exception specification is instantiated.
  6714. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  6715. ResolveExceptionSpec(D->getLocation(), FPT);
  6716. // Checking attributes of current function definition
  6717. // dllimport attribute.
  6718. DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
  6719. if (DA && (!FD->getAttr<DLLExportAttr>())) {
  6720. // dllimport attribute cannot be directly applied to definition.
  6721. // Microsoft accepts dllimport for functions defined within class scope.
  6722. if (!DA->isInherited() &&
  6723. !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
  6724. Diag(FD->getLocation(),
  6725. diag::err_attribute_can_be_applied_only_to_symbol_declaration)
  6726. << "dllimport";
  6727. FD->setInvalidDecl();
  6728. return FD;
  6729. }
  6730. // Visual C++ appears to not think this is an issue, so only issue
  6731. // a warning when Microsoft extensions are disabled.
  6732. if (!LangOpts.MicrosoftExt) {
  6733. // If a symbol previously declared dllimport is later defined, the
  6734. // attribute is ignored in subsequent references, and a warning is
  6735. // emitted.
  6736. Diag(FD->getLocation(),
  6737. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  6738. << FD->getName() << "dllimport";
  6739. }
  6740. }
  6741. // We want to attach documentation to original Decl (which might be
  6742. // a function template).
  6743. ActOnDocumentableDecl(D);
  6744. return FD;
  6745. }
  6746. /// \brief Given the set of return statements within a function body,
  6747. /// compute the variables that are subject to the named return value
  6748. /// optimization.
  6749. ///
  6750. /// Each of the variables that is subject to the named return value
  6751. /// optimization will be marked as NRVO variables in the AST, and any
  6752. /// return statement that has a marked NRVO variable as its NRVO candidate can
  6753. /// use the named return value optimization.
  6754. ///
  6755. /// This function applies a very simplistic algorithm for NRVO: if every return
  6756. /// statement in the function has the same NRVO candidate, that candidate is
  6757. /// the NRVO variable.
  6758. ///
  6759. /// FIXME: Employ a smarter algorithm that accounts for multiple return
  6760. /// statements and the lifetimes of the NRVO candidates. We should be able to
  6761. /// find a maximal set of NRVO variables.
  6762. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  6763. ReturnStmt **Returns = Scope->Returns.data();
  6764. const VarDecl *NRVOCandidate = 0;
  6765. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  6766. if (!Returns[I]->getNRVOCandidate())
  6767. return;
  6768. if (!NRVOCandidate)
  6769. NRVOCandidate = Returns[I]->getNRVOCandidate();
  6770. else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
  6771. return;
  6772. }
  6773. if (NRVOCandidate)
  6774. const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
  6775. }
  6776. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  6777. return ActOnFinishFunctionBody(D, BodyArg, false);
  6778. }
  6779. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  6780. bool IsInstantiation) {
  6781. FunctionDecl *FD = 0;
  6782. FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
  6783. if (FunTmpl)
  6784. FD = FunTmpl->getTemplatedDecl();
  6785. else
  6786. FD = dyn_cast_or_null<FunctionDecl>(dcl);
  6787. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  6788. sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
  6789. if (FD) {
  6790. FD->setBody(Body);
  6791. // If the function implicitly returns zero (like 'main') or is naked,
  6792. // don't complain about missing return statements.
  6793. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  6794. WP.disableCheckFallThrough();
  6795. // MSVC permits the use of pure specifier (=0) on function definition,
  6796. // defined at class scope, warn about this non standard construct.
  6797. if (getLangOpts().MicrosoftExt && FD->isPure())
  6798. Diag(FD->getLocation(), diag::warn_pure_function_definition);
  6799. if (!FD->isInvalidDecl()) {
  6800. DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
  6801. DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
  6802. FD->getResultType(), FD);
  6803. // If this is a constructor, we need a vtable.
  6804. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  6805. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  6806. // Try to apply the named return value optimization. We have to check
  6807. // if we can do this here because lambdas keep return statements around
  6808. // to deduce an implicit return type.
  6809. if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
  6810. !FD->isDependentContext())
  6811. computeNRVO(Body, getCurFunction());
  6812. }
  6813. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  6814. "Function parsing confused");
  6815. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  6816. assert(MD == getCurMethodDecl() && "Method parsing confused");
  6817. MD->setBody(Body);
  6818. if (!MD->isInvalidDecl()) {
  6819. DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
  6820. DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
  6821. MD->getResultType(), MD);
  6822. if (Body)
  6823. computeNRVO(Body, getCurFunction());
  6824. }
  6825. if (getCurFunction()->ObjCShouldCallSuperDealloc) {
  6826. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
  6827. getCurFunction()->ObjCShouldCallSuperDealloc = false;
  6828. }
  6829. if (getCurFunction()->ObjCShouldCallSuperFinalize) {
  6830. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
  6831. getCurFunction()->ObjCShouldCallSuperFinalize = false;
  6832. }
  6833. } else {
  6834. return 0;
  6835. }
  6836. assert(!getCurFunction()->ObjCShouldCallSuperDealloc &&
  6837. "This should only be set for ObjC methods, which should have been "
  6838. "handled in the block above.");
  6839. assert(!getCurFunction()->ObjCShouldCallSuperFinalize &&
  6840. "This should only be set for ObjC methods, which should have been "
  6841. "handled in the block above.");
  6842. // Verify and clean out per-function state.
  6843. if (Body) {
  6844. // C++ constructors that have function-try-blocks can't have return
  6845. // statements in the handlers of that block. (C++ [except.handle]p14)
  6846. // Verify this.
  6847. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  6848. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  6849. // Verify that gotos and switch cases don't jump into scopes illegally.
  6850. if (getCurFunction()->NeedsScopeChecking() &&
  6851. !dcl->isInvalidDecl() &&
  6852. !hasAnyUnrecoverableErrorsInThisFunction() &&
  6853. !PP.isCodeCompletionEnabled())
  6854. DiagnoseInvalidJumps(Body);
  6855. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  6856. if (!Destructor->getParent()->isDependentType())
  6857. CheckDestructor(Destructor);
  6858. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  6859. Destructor->getParent());
  6860. }
  6861. // If any errors have occurred, clear out any temporaries that may have
  6862. // been leftover. This ensures that these temporaries won't be picked up for
  6863. // deletion in some later function.
  6864. if (PP.getDiagnostics().hasErrorOccurred() ||
  6865. PP.getDiagnostics().getSuppressAllDiagnostics()) {
  6866. DiscardCleanupsInEvaluationContext();
  6867. } else if (!isa<FunctionTemplateDecl>(dcl)) {
  6868. // Since the body is valid, issue any analysis-based warnings that are
  6869. // enabled.
  6870. ActivePolicy = &WP;
  6871. }
  6872. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  6873. (!CheckConstexprFunctionDecl(FD) ||
  6874. !CheckConstexprFunctionBody(FD, Body)))
  6875. FD->setInvalidDecl();
  6876. assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
  6877. assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
  6878. assert(MaybeODRUseExprs.empty() &&
  6879. "Leftover expressions for odr-use checking");
  6880. }
  6881. if (!IsInstantiation)
  6882. PopDeclContext();
  6883. PopFunctionScopeInfo(ActivePolicy, dcl);
  6884. // If any errors have occurred, clear out any temporaries that may have
  6885. // been leftover. This ensures that these temporaries won't be picked up for
  6886. // deletion in some later function.
  6887. if (getDiagnostics().hasErrorOccurred()) {
  6888. DiscardCleanupsInEvaluationContext();
  6889. }
  6890. return dcl;
  6891. }
  6892. /// When we finish delayed parsing of an attribute, we must attach it to the
  6893. /// relevant Decl.
  6894. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  6895. ParsedAttributes &Attrs) {
  6896. // Always attach attributes to the underlying decl.
  6897. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  6898. D = TD->getTemplatedDecl();
  6899. ProcessDeclAttributeList(S, D, Attrs.getList());
  6900. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  6901. if (Method->isStatic())
  6902. checkThisInStaticMemberFunctionAttributes(Method);
  6903. }
  6904. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  6905. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  6906. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  6907. IdentifierInfo &II, Scope *S) {
  6908. // Before we produce a declaration for an implicitly defined
  6909. // function, see whether there was a locally-scoped declaration of
  6910. // this name as a function or variable. If so, use that
  6911. // (non-visible) declaration, and complain about it.
  6912. llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
  6913. = findLocallyScopedExternalDecl(&II);
  6914. if (Pos != LocallyScopedExternalDecls.end()) {
  6915. Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
  6916. Diag(Pos->second->getLocation(), diag::note_previous_declaration);
  6917. return Pos->second;
  6918. }
  6919. // Extension in C99. Legal in C90, but warn about it.
  6920. unsigned diag_id;
  6921. if (II.getName().startswith("__builtin_"))
  6922. diag_id = diag::warn_builtin_unknown;
  6923. else if (getLangOpts().C99)
  6924. diag_id = diag::ext_implicit_function_decl;
  6925. else
  6926. diag_id = diag::warn_implicit_function_decl;
  6927. Diag(Loc, diag_id) << &II;
  6928. // Because typo correction is expensive, only do it if the implicit
  6929. // function declaration is going to be treated as an error.
  6930. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  6931. TypoCorrection Corrected;
  6932. DeclFilterCCC<FunctionDecl> Validator;
  6933. if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
  6934. LookupOrdinaryName, S, 0, Validator))) {
  6935. std::string CorrectedStr = Corrected.getAsString(getLangOpts());
  6936. std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
  6937. FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
  6938. Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
  6939. << FixItHint::CreateReplacement(Loc, CorrectedStr);
  6940. if (Func->getLocation().isValid()
  6941. && !II.getName().startswith("__builtin_"))
  6942. Diag(Func->getLocation(), diag::note_previous_decl)
  6943. << CorrectedQuotedStr;
  6944. }
  6945. }
  6946. // Set a Declarator for the implicit definition: int foo();
  6947. const char *Dummy;
  6948. AttributeFactory attrFactory;
  6949. DeclSpec DS(attrFactory);
  6950. unsigned DiagID;
  6951. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
  6952. (void)Error; // Silence warning.
  6953. assert(!Error && "Error setting up implicit decl!");
  6954. Declarator D(DS, Declarator::BlockContext);
  6955. D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, false,
  6956. SourceLocation(), 0, 0, 0, true,
  6957. SourceLocation(), SourceLocation(),
  6958. SourceLocation(), SourceLocation(),
  6959. EST_None, SourceLocation(),
  6960. 0, 0, 0, 0, Loc, Loc, D),
  6961. DS.getAttributes(),
  6962. SourceLocation());
  6963. D.SetIdentifier(&II, Loc);
  6964. // Insert this function into translation-unit scope.
  6965. DeclContext *PrevDC = CurContext;
  6966. CurContext = Context.getTranslationUnitDecl();
  6967. FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
  6968. FD->setImplicit();
  6969. CurContext = PrevDC;
  6970. AddKnownFunctionAttributes(FD);
  6971. return FD;
  6972. }
  6973. /// \brief Adds any function attributes that we know a priori based on
  6974. /// the declaration of this function.
  6975. ///
  6976. /// These attributes can apply both to implicitly-declared builtins
  6977. /// (like __builtin___printf_chk) or to library-declared functions
  6978. /// like NSLog or printf.
  6979. ///
  6980. /// We need to check for duplicate attributes both here and where user-written
  6981. /// attributes are applied to declarations.
  6982. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  6983. if (FD->isInvalidDecl())
  6984. return;
  6985. // If this is a built-in function, map its builtin attributes to
  6986. // actual attributes.
  6987. if (unsigned BuiltinID = FD->getBuiltinID()) {
  6988. // Handle printf-formatting attributes.
  6989. unsigned FormatIdx;
  6990. bool HasVAListArg;
  6991. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  6992. if (!FD->getAttr<FormatAttr>()) {
  6993. const char *fmt = "printf";
  6994. unsigned int NumParams = FD->getNumParams();
  6995. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  6996. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  6997. fmt = "NSString";
  6998. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  6999. fmt, FormatIdx+1,
  7000. HasVAListArg ? 0 : FormatIdx+2));
  7001. }
  7002. }
  7003. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  7004. HasVAListArg)) {
  7005. if (!FD->getAttr<FormatAttr>())
  7006. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7007. "scanf", FormatIdx+1,
  7008. HasVAListArg ? 0 : FormatIdx+2));
  7009. }
  7010. // Mark const if we don't care about errno and that is the only
  7011. // thing preventing the function from being const. This allows
  7012. // IRgen to use LLVM intrinsics for such functions.
  7013. if (!getLangOpts().MathErrno &&
  7014. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  7015. if (!FD->getAttr<ConstAttr>())
  7016. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  7017. }
  7018. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  7019. !FD->getAttr<ReturnsTwiceAttr>())
  7020. FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
  7021. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
  7022. FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
  7023. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
  7024. FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
  7025. }
  7026. IdentifierInfo *Name = FD->getIdentifier();
  7027. if (!Name)
  7028. return;
  7029. if ((!getLangOpts().CPlusPlus &&
  7030. FD->getDeclContext()->isTranslationUnit()) ||
  7031. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  7032. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  7033. LinkageSpecDecl::lang_c)) {
  7034. // Okay: this could be a libc/libm/Objective-C function we know
  7035. // about.
  7036. } else
  7037. return;
  7038. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  7039. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  7040. // target-specific builtins, perhaps?
  7041. if (!FD->getAttr<FormatAttr>())
  7042. FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
  7043. "printf", 2,
  7044. Name->isStr("vasprintf") ? 0 : 3));
  7045. }
  7046. if (Name->isStr("__CFStringMakeConstantString")) {
  7047. // We already have a __builtin___CFStringMakeConstantString,
  7048. // but builds that use -fno-constant-cfstrings don't go through that.
  7049. if (!FD->getAttr<FormatArgAttr>())
  7050. FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
  7051. }
  7052. }
  7053. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  7054. TypeSourceInfo *TInfo) {
  7055. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  7056. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  7057. if (!TInfo) {
  7058. assert(D.isInvalidType() && "no declarator info for valid type");
  7059. TInfo = Context.getTrivialTypeSourceInfo(T);
  7060. }
  7061. // Scope manipulation handled by caller.
  7062. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  7063. D.getLocStart(),
  7064. D.getIdentifierLoc(),
  7065. D.getIdentifier(),
  7066. TInfo);
  7067. // Bail out immediately if we have an invalid declaration.
  7068. if (D.isInvalidType()) {
  7069. NewTD->setInvalidDecl();
  7070. return NewTD;
  7071. }
  7072. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7073. if (CurContext->isFunctionOrMethod())
  7074. Diag(NewTD->getLocation(), diag::err_module_private_local)
  7075. << 2 << NewTD->getDeclName()
  7076. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  7077. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  7078. else
  7079. NewTD->setModulePrivate();
  7080. }
  7081. // C++ [dcl.typedef]p8:
  7082. // If the typedef declaration defines an unnamed class (or
  7083. // enum), the first typedef-name declared by the declaration
  7084. // to be that class type (or enum type) is used to denote the
  7085. // class type (or enum type) for linkage purposes only.
  7086. // We need to check whether the type was declared in the declaration.
  7087. switch (D.getDeclSpec().getTypeSpecType()) {
  7088. case TST_enum:
  7089. case TST_struct:
  7090. case TST_union:
  7091. case TST_class: {
  7092. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  7093. // Do nothing if the tag is not anonymous or already has an
  7094. // associated typedef (from an earlier typedef in this decl group).
  7095. if (tagFromDeclSpec->getIdentifier()) break;
  7096. if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
  7097. // A well-formed anonymous tag must always be a TUK_Definition.
  7098. assert(tagFromDeclSpec->isThisDeclarationADefinition());
  7099. // The type must match the tag exactly; no qualifiers allowed.
  7100. if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
  7101. break;
  7102. // Otherwise, set this is the anon-decl typedef for the tag.
  7103. tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  7104. break;
  7105. }
  7106. default:
  7107. break;
  7108. }
  7109. return NewTD;
  7110. }
  7111. /// \brief Check that this is a valid underlying type for an enum declaration.
  7112. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  7113. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  7114. QualType T = TI->getType();
  7115. if (T->isDependentType() || T->isIntegralType(Context))
  7116. return false;
  7117. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  7118. return true;
  7119. }
  7120. /// Check whether this is a valid redeclaration of a previous enumeration.
  7121. /// \return true if the redeclaration was invalid.
  7122. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  7123. QualType EnumUnderlyingTy,
  7124. const EnumDecl *Prev) {
  7125. bool IsFixed = !EnumUnderlyingTy.isNull();
  7126. if (IsScoped != Prev->isScoped()) {
  7127. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  7128. << Prev->isScoped();
  7129. Diag(Prev->getLocation(), diag::note_previous_use);
  7130. return true;
  7131. }
  7132. if (IsFixed && Prev->isFixed()) {
  7133. if (!EnumUnderlyingTy->isDependentType() &&
  7134. !Prev->getIntegerType()->isDependentType() &&
  7135. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  7136. Prev->getIntegerType())) {
  7137. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  7138. << EnumUnderlyingTy << Prev->getIntegerType();
  7139. Diag(Prev->getLocation(), diag::note_previous_use);
  7140. return true;
  7141. }
  7142. } else if (IsFixed != Prev->isFixed()) {
  7143. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  7144. << Prev->isFixed();
  7145. Diag(Prev->getLocation(), diag::note_previous_use);
  7146. return true;
  7147. }
  7148. return false;
  7149. }
  7150. /// \brief Determine whether a tag with a given kind is acceptable
  7151. /// as a redeclaration of the given tag declaration.
  7152. ///
  7153. /// \returns true if the new tag kind is acceptable, false otherwise.
  7154. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  7155. TagTypeKind NewTag, bool isDefinition,
  7156. SourceLocation NewTagLoc,
  7157. const IdentifierInfo &Name) {
  7158. // C++ [dcl.type.elab]p3:
  7159. // The class-key or enum keyword present in the
  7160. // elaborated-type-specifier shall agree in kind with the
  7161. // declaration to which the name in the elaborated-type-specifier
  7162. // refers. This rule also applies to the form of
  7163. // elaborated-type-specifier that declares a class-name or
  7164. // friend class since it can be construed as referring to the
  7165. // definition of the class. Thus, in any
  7166. // elaborated-type-specifier, the enum keyword shall be used to
  7167. // refer to an enumeration (7.2), the union class-key shall be
  7168. // used to refer to a union (clause 9), and either the class or
  7169. // struct class-key shall be used to refer to a class (clause 9)
  7170. // declared using the class or struct class-key.
  7171. TagTypeKind OldTag = Previous->getTagKind();
  7172. if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
  7173. if (OldTag == NewTag)
  7174. return true;
  7175. if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
  7176. (NewTag == TTK_Struct || NewTag == TTK_Class)) {
  7177. // Warn about the struct/class tag mismatch.
  7178. bool isTemplate = false;
  7179. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  7180. isTemplate = Record->getDescribedClassTemplate();
  7181. if (!ActiveTemplateInstantiations.empty()) {
  7182. // In a template instantiation, do not offer fix-its for tag mismatches
  7183. // since they usually mess up the template instead of fixing the problem.
  7184. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  7185. << (NewTag == TTK_Class) << isTemplate << &Name;
  7186. return true;
  7187. }
  7188. if (isDefinition) {
  7189. // On definitions, check previous tags and issue a fix-it for each
  7190. // one that doesn't match the current tag.
  7191. if (Previous->getDefinition()) {
  7192. // Don't suggest fix-its for redefinitions.
  7193. return true;
  7194. }
  7195. bool previousMismatch = false;
  7196. for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
  7197. E(Previous->redecls_end()); I != E; ++I) {
  7198. if (I->getTagKind() != NewTag) {
  7199. if (!previousMismatch) {
  7200. previousMismatch = true;
  7201. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  7202. << (NewTag == TTK_Class) << isTemplate << &Name;
  7203. }
  7204. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  7205. << (NewTag == TTK_Class)
  7206. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  7207. NewTag == TTK_Class?
  7208. "class" : "struct");
  7209. }
  7210. }
  7211. return true;
  7212. }
  7213. // Check for a previous definition. If current tag and definition
  7214. // are same type, do nothing. If no definition, but disagree with
  7215. // with previous tag type, give a warning, but no fix-it.
  7216. const TagDecl *Redecl = Previous->getDefinition() ?
  7217. Previous->getDefinition() : Previous;
  7218. if (Redecl->getTagKind() == NewTag) {
  7219. return true;
  7220. }
  7221. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  7222. << (NewTag == TTK_Class)
  7223. << isTemplate << &Name;
  7224. Diag(Redecl->getLocation(), diag::note_previous_use);
  7225. // If there is a previous defintion, suggest a fix-it.
  7226. if (Previous->getDefinition()) {
  7227. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  7228. << (Redecl->getTagKind() == TTK_Class)
  7229. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  7230. Redecl->getTagKind() == TTK_Class? "class" : "struct");
  7231. }
  7232. return true;
  7233. }
  7234. return false;
  7235. }
  7236. /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
  7237. /// former case, Name will be non-null. In the later case, Name will be null.
  7238. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  7239. /// reference/declaration/definition of a tag.
  7240. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  7241. SourceLocation KWLoc, CXXScopeSpec &SS,
  7242. IdentifierInfo *Name, SourceLocation NameLoc,
  7243. AttributeList *Attr, AccessSpecifier AS,
  7244. SourceLocation ModulePrivateLoc,
  7245. MultiTemplateParamsArg TemplateParameterLists,
  7246. bool &OwnedDecl, bool &IsDependent,
  7247. SourceLocation ScopedEnumKWLoc,
  7248. bool ScopedEnumUsesClassTag,
  7249. TypeResult UnderlyingType) {
  7250. // If this is not a definition, it must have a name.
  7251. IdentifierInfo *OrigName = Name;
  7252. assert((Name != 0 || TUK == TUK_Definition) &&
  7253. "Nameless record must be a definition!");
  7254. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  7255. OwnedDecl = false;
  7256. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  7257. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  7258. // FIXME: Check explicit specializations more carefully.
  7259. bool isExplicitSpecialization = false;
  7260. bool Invalid = false;
  7261. // We only need to do this matching if we have template parameters
  7262. // or a scope specifier, which also conveniently avoids this work
  7263. // for non-C++ cases.
  7264. if (TemplateParameterLists.size() > 0 ||
  7265. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  7266. if (TemplateParameterList *TemplateParams
  7267. = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
  7268. TemplateParameterLists.get(),
  7269. TemplateParameterLists.size(),
  7270. TUK == TUK_Friend,
  7271. isExplicitSpecialization,
  7272. Invalid)) {
  7273. if (TemplateParams->size() > 0) {
  7274. // This is a declaration or definition of a class template (which may
  7275. // be a member of another template).
  7276. if (Invalid)
  7277. return 0;
  7278. OwnedDecl = false;
  7279. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  7280. SS, Name, NameLoc, Attr,
  7281. TemplateParams, AS,
  7282. ModulePrivateLoc,
  7283. TemplateParameterLists.size()-1,
  7284. TemplateParameterLists.get());
  7285. return Result.get();
  7286. } else {
  7287. // The "template<>" header is extraneous.
  7288. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  7289. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  7290. isExplicitSpecialization = true;
  7291. }
  7292. }
  7293. }
  7294. // Figure out the underlying type if this a enum declaration. We need to do
  7295. // this early, because it's needed to detect if this is an incompatible
  7296. // redeclaration.
  7297. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  7298. if (Kind == TTK_Enum) {
  7299. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  7300. // No underlying type explicitly specified, or we failed to parse the
  7301. // type, default to int.
  7302. EnumUnderlying = Context.IntTy.getTypePtr();
  7303. else if (UnderlyingType.get()) {
  7304. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  7305. // integral type; any cv-qualification is ignored.
  7306. TypeSourceInfo *TI = 0;
  7307. GetTypeFromParser(UnderlyingType.get(), &TI);
  7308. EnumUnderlying = TI;
  7309. if (CheckEnumUnderlyingType(TI))
  7310. // Recover by falling back to int.
  7311. EnumUnderlying = Context.IntTy.getTypePtr();
  7312. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  7313. UPPC_FixedUnderlyingType))
  7314. EnumUnderlying = Context.IntTy.getTypePtr();
  7315. } else if (getLangOpts().MicrosoftMode)
  7316. // Microsoft enums are always of int type.
  7317. EnumUnderlying = Context.IntTy.getTypePtr();
  7318. }
  7319. DeclContext *SearchDC = CurContext;
  7320. DeclContext *DC = CurContext;
  7321. bool isStdBadAlloc = false;
  7322. RedeclarationKind Redecl = ForRedeclaration;
  7323. if (TUK == TUK_Friend || TUK == TUK_Reference)
  7324. Redecl = NotForRedeclaration;
  7325. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  7326. if (Name && SS.isNotEmpty()) {
  7327. // We have a nested-name tag ('struct foo::bar').
  7328. // Check for invalid 'foo::'.
  7329. if (SS.isInvalid()) {
  7330. Name = 0;
  7331. goto CreateNewDecl;
  7332. }
  7333. // If this is a friend or a reference to a class in a dependent
  7334. // context, don't try to make a decl for it.
  7335. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  7336. DC = computeDeclContext(SS, false);
  7337. if (!DC) {
  7338. IsDependent = true;
  7339. return 0;
  7340. }
  7341. } else {
  7342. DC = computeDeclContext(SS, true);
  7343. if (!DC) {
  7344. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  7345. << SS.getRange();
  7346. return 0;
  7347. }
  7348. }
  7349. if (RequireCompleteDeclContext(SS, DC))
  7350. return 0;
  7351. SearchDC = DC;
  7352. // Look-up name inside 'foo::'.
  7353. LookupQualifiedName(Previous, DC);
  7354. if (Previous.isAmbiguous())
  7355. return 0;
  7356. if (Previous.empty()) {
  7357. // Name lookup did not find anything. However, if the
  7358. // nested-name-specifier refers to the current instantiation,
  7359. // and that current instantiation has any dependent base
  7360. // classes, we might find something at instantiation time: treat
  7361. // this as a dependent elaborated-type-specifier.
  7362. // But this only makes any sense for reference-like lookups.
  7363. if (Previous.wasNotFoundInCurrentInstantiation() &&
  7364. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  7365. IsDependent = true;
  7366. return 0;
  7367. }
  7368. // A tag 'foo::bar' must already exist.
  7369. Diag(NameLoc, diag::err_not_tag_in_scope)
  7370. << Kind << Name << DC << SS.getRange();
  7371. Name = 0;
  7372. Invalid = true;
  7373. goto CreateNewDecl;
  7374. }
  7375. } else if (Name) {
  7376. // If this is a named struct, check to see if there was a previous forward
  7377. // declaration or definition.
  7378. // FIXME: We're looking into outer scopes here, even when we
  7379. // shouldn't be. Doing so can result in ambiguities that we
  7380. // shouldn't be diagnosing.
  7381. LookupName(Previous, S);
  7382. if (Previous.isAmbiguous() &&
  7383. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  7384. LookupResult::Filter F = Previous.makeFilter();
  7385. while (F.hasNext()) {
  7386. NamedDecl *ND = F.next();
  7387. if (ND->getDeclContext()->getRedeclContext() != SearchDC)
  7388. F.erase();
  7389. }
  7390. F.done();
  7391. }
  7392. // Note: there used to be some attempt at recovery here.
  7393. if (Previous.isAmbiguous())
  7394. return 0;
  7395. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  7396. // FIXME: This makes sure that we ignore the contexts associated
  7397. // with C structs, unions, and enums when looking for a matching
  7398. // tag declaration or definition. See the similar lookup tweak
  7399. // in Sema::LookupName; is there a better way to deal with this?
  7400. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  7401. SearchDC = SearchDC->getParent();
  7402. }
  7403. } else if (S->isFunctionPrototypeScope()) {
  7404. // If this is an enum declaration in function prototype scope, set its
  7405. // initial context to the translation unit.
  7406. // FIXME: [citation needed]
  7407. SearchDC = Context.getTranslationUnitDecl();
  7408. }
  7409. if (Previous.isSingleResult() &&
  7410. Previous.getFoundDecl()->isTemplateParameter()) {
  7411. // Maybe we will complain about the shadowed template parameter.
  7412. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  7413. // Just pretend that we didn't see the previous declaration.
  7414. Previous.clear();
  7415. }
  7416. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  7417. DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
  7418. // This is a declaration of or a reference to "std::bad_alloc".
  7419. isStdBadAlloc = true;
  7420. if (Previous.empty() && StdBadAlloc) {
  7421. // std::bad_alloc has been implicitly declared (but made invisible to
  7422. // name lookup). Fill in this implicit declaration as the previous
  7423. // declaration, so that the declarations get chained appropriately.
  7424. Previous.addDecl(getStdBadAlloc());
  7425. }
  7426. }
  7427. // If we didn't find a previous declaration, and this is a reference
  7428. // (or friend reference), move to the correct scope. In C++, we
  7429. // also need to do a redeclaration lookup there, just in case
  7430. // there's a shadow friend decl.
  7431. if (Name && Previous.empty() &&
  7432. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  7433. if (Invalid) goto CreateNewDecl;
  7434. assert(SS.isEmpty());
  7435. if (TUK == TUK_Reference) {
  7436. // C++ [basic.scope.pdecl]p5:
  7437. // -- for an elaborated-type-specifier of the form
  7438. //
  7439. // class-key identifier
  7440. //
  7441. // if the elaborated-type-specifier is used in the
  7442. // decl-specifier-seq or parameter-declaration-clause of a
  7443. // function defined in namespace scope, the identifier is
  7444. // declared as a class-name in the namespace that contains
  7445. // the declaration; otherwise, except as a friend
  7446. // declaration, the identifier is declared in the smallest
  7447. // non-class, non-function-prototype scope that contains the
  7448. // declaration.
  7449. //
  7450. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  7451. // C structs and unions.
  7452. //
  7453. // It is an error in C++ to declare (rather than define) an enum
  7454. // type, including via an elaborated type specifier. We'll
  7455. // diagnose that later; for now, declare the enum in the same
  7456. // scope as we would have picked for any other tag type.
  7457. //
  7458. // GNU C also supports this behavior as part of its incomplete
  7459. // enum types extension, while GNU C++ does not.
  7460. //
  7461. // Find the context where we'll be declaring the tag.
  7462. // FIXME: We would like to maintain the current DeclContext as the
  7463. // lexical context,
  7464. while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
  7465. SearchDC = SearchDC->getParent();
  7466. // Find the scope where we'll be declaring the tag.
  7467. while (S->isClassScope() ||
  7468. (getLangOpts().CPlusPlus &&
  7469. S->isFunctionPrototypeScope()) ||
  7470. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7471. (S->getEntity() &&
  7472. ((DeclContext *)S->getEntity())->isTransparentContext()))
  7473. S = S->getParent();
  7474. } else {
  7475. assert(TUK == TUK_Friend);
  7476. // C++ [namespace.memdef]p3:
  7477. // If a friend declaration in a non-local class first declares a
  7478. // class or function, the friend class or function is a member of
  7479. // the innermost enclosing namespace.
  7480. SearchDC = SearchDC->getEnclosingNamespaceContext();
  7481. }
  7482. // In C++, we need to do a redeclaration lookup to properly
  7483. // diagnose some problems.
  7484. if (getLangOpts().CPlusPlus) {
  7485. Previous.setRedeclarationKind(ForRedeclaration);
  7486. LookupQualifiedName(Previous, SearchDC);
  7487. }
  7488. }
  7489. if (!Previous.empty()) {
  7490. NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
  7491. // It's okay to have a tag decl in the same scope as a typedef
  7492. // which hides a tag decl in the same scope. Finding this
  7493. // insanity with a redeclaration lookup can only actually happen
  7494. // in C++.
  7495. //
  7496. // This is also okay for elaborated-type-specifiers, which is
  7497. // technically forbidden by the current standard but which is
  7498. // okay according to the likely resolution of an open issue;
  7499. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  7500. if (getLangOpts().CPlusPlus) {
  7501. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7502. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  7503. TagDecl *Tag = TT->getDecl();
  7504. if (Tag->getDeclName() == Name &&
  7505. Tag->getDeclContext()->getRedeclContext()
  7506. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  7507. PrevDecl = Tag;
  7508. Previous.clear();
  7509. Previous.addDecl(Tag);
  7510. Previous.resolveKind();
  7511. }
  7512. }
  7513. }
  7514. }
  7515. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  7516. // If this is a use of a previous tag, or if the tag is already declared
  7517. // in the same scope (so that the definition/declaration completes or
  7518. // rementions the tag), reuse the decl.
  7519. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  7520. isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
  7521. // Make sure that this wasn't declared as an enum and now used as a
  7522. // struct or something similar.
  7523. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  7524. TUK == TUK_Definition, KWLoc,
  7525. *Name)) {
  7526. bool SafeToContinue
  7527. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  7528. Kind != TTK_Enum);
  7529. if (SafeToContinue)
  7530. Diag(KWLoc, diag::err_use_with_wrong_tag)
  7531. << Name
  7532. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  7533. PrevTagDecl->getKindName());
  7534. else
  7535. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  7536. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  7537. if (SafeToContinue)
  7538. Kind = PrevTagDecl->getTagKind();
  7539. else {
  7540. // Recover by making this an anonymous redefinition.
  7541. Name = 0;
  7542. Previous.clear();
  7543. Invalid = true;
  7544. }
  7545. }
  7546. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  7547. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  7548. // If this is an elaborated-type-specifier for a scoped enumeration,
  7549. // the 'class' keyword is not necessary and not permitted.
  7550. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7551. if (ScopedEnum)
  7552. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  7553. << PrevEnum->isScoped()
  7554. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  7555. return PrevTagDecl;
  7556. }
  7557. QualType EnumUnderlyingTy;
  7558. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7559. EnumUnderlyingTy = TI->getType();
  7560. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  7561. EnumUnderlyingTy = QualType(T, 0);
  7562. // All conflicts with previous declarations are recovered by
  7563. // returning the previous declaration, unless this is a definition,
  7564. // in which case we want the caller to bail out.
  7565. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  7566. ScopedEnum, EnumUnderlyingTy, PrevEnum))
  7567. return TUK == TUK_Declaration ? PrevTagDecl : 0;
  7568. }
  7569. if (!Invalid) {
  7570. // If this is a use, just return the declaration we found.
  7571. // FIXME: In the future, return a variant or some other clue
  7572. // for the consumer of this Decl to know it doesn't own it.
  7573. // For our current ASTs this shouldn't be a problem, but will
  7574. // need to be changed with DeclGroups.
  7575. if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
  7576. getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
  7577. return PrevTagDecl;
  7578. // Diagnose attempts to redefine a tag.
  7579. if (TUK == TUK_Definition) {
  7580. if (TagDecl *Def = PrevTagDecl->getDefinition()) {
  7581. // If we're defining a specialization and the previous definition
  7582. // is from an implicit instantiation, don't emit an error
  7583. // here; we'll catch this in the general case below.
  7584. bool IsExplicitSpecializationAfterInstantiation = false;
  7585. if (isExplicitSpecialization) {
  7586. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  7587. IsExplicitSpecializationAfterInstantiation =
  7588. RD->getTemplateSpecializationKind() !=
  7589. TSK_ExplicitSpecialization;
  7590. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  7591. IsExplicitSpecializationAfterInstantiation =
  7592. ED->getTemplateSpecializationKind() !=
  7593. TSK_ExplicitSpecialization;
  7594. }
  7595. if (!IsExplicitSpecializationAfterInstantiation) {
  7596. // A redeclaration in function prototype scope in C isn't
  7597. // visible elsewhere, so merely issue a warning.
  7598. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  7599. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  7600. else
  7601. Diag(NameLoc, diag::err_redefinition) << Name;
  7602. Diag(Def->getLocation(), diag::note_previous_definition);
  7603. // If this is a redefinition, recover by making this
  7604. // struct be anonymous, which will make any later
  7605. // references get the previous definition.
  7606. Name = 0;
  7607. Previous.clear();
  7608. Invalid = true;
  7609. }
  7610. } else {
  7611. // If the type is currently being defined, complain
  7612. // about a nested redefinition.
  7613. const TagType *Tag
  7614. = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
  7615. if (Tag->isBeingDefined()) {
  7616. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  7617. Diag(PrevTagDecl->getLocation(),
  7618. diag::note_previous_definition);
  7619. Name = 0;
  7620. Previous.clear();
  7621. Invalid = true;
  7622. }
  7623. }
  7624. // Okay, this is definition of a previously declared or referenced
  7625. // tag PrevDecl. We're going to create a new Decl for it.
  7626. }
  7627. }
  7628. // If we get here we have (another) forward declaration or we
  7629. // have a definition. Just create a new decl.
  7630. } else {
  7631. // If we get here, this is a definition of a new tag type in a nested
  7632. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  7633. // new decl/type. We set PrevDecl to NULL so that the entities
  7634. // have distinct types.
  7635. Previous.clear();
  7636. }
  7637. // If we get here, we're going to create a new Decl. If PrevDecl
  7638. // is non-NULL, it's a definition of the tag declared by
  7639. // PrevDecl. If it's NULL, we have a new definition.
  7640. // Otherwise, PrevDecl is not a tag, but was found with tag
  7641. // lookup. This is only actually possible in C++, where a few
  7642. // things like templates still live in the tag namespace.
  7643. } else {
  7644. // Use a better diagnostic if an elaborated-type-specifier
  7645. // found the wrong kind of type on the first
  7646. // (non-redeclaration) lookup.
  7647. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  7648. !Previous.isForRedeclaration()) {
  7649. unsigned Kind = 0;
  7650. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7651. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7652. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7653. Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
  7654. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  7655. Invalid = true;
  7656. // Otherwise, only diagnose if the declaration is in scope.
  7657. } else if (!isDeclInScope(PrevDecl, SearchDC, S,
  7658. isExplicitSpecialization)) {
  7659. // do nothing
  7660. // Diagnose implicit declarations introduced by elaborated types.
  7661. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  7662. unsigned Kind = 0;
  7663. if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
  7664. else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
  7665. else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
  7666. Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
  7667. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7668. Invalid = true;
  7669. // Otherwise it's a declaration. Call out a particularly common
  7670. // case here.
  7671. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  7672. unsigned Kind = 0;
  7673. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  7674. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  7675. << Name << Kind << TND->getUnderlyingType();
  7676. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  7677. Invalid = true;
  7678. // Otherwise, diagnose.
  7679. } else {
  7680. // The tag name clashes with something else in the target scope,
  7681. // issue an error and recover by making this tag be anonymous.
  7682. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  7683. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  7684. Name = 0;
  7685. Invalid = true;
  7686. }
  7687. // The existing declaration isn't relevant to us; we're in a
  7688. // new scope, so clear out the previous declaration.
  7689. Previous.clear();
  7690. }
  7691. }
  7692. CreateNewDecl:
  7693. TagDecl *PrevDecl = 0;
  7694. if (Previous.isSingleResult())
  7695. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  7696. // If there is an identifier, use the location of the identifier as the
  7697. // location of the decl, otherwise use the location of the struct/union
  7698. // keyword.
  7699. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  7700. // Otherwise, create a new declaration. If there is a previous
  7701. // declaration of the same entity, the two will be linked via
  7702. // PrevDecl.
  7703. TagDecl *New;
  7704. bool IsForwardReference = false;
  7705. if (Kind == TTK_Enum) {
  7706. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7707. // enum X { A, B, C } D; D should chain to X.
  7708. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  7709. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  7710. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  7711. // If this is an undefined enum, warn.
  7712. if (TUK != TUK_Definition && !Invalid) {
  7713. TagDecl *Def;
  7714. if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
  7715. // C++0x: 7.2p2: opaque-enum-declaration.
  7716. // Conflicts are diagnosed above. Do nothing.
  7717. }
  7718. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  7719. Diag(Loc, diag::ext_forward_ref_enum_def)
  7720. << New;
  7721. Diag(Def->getLocation(), diag::note_previous_definition);
  7722. } else {
  7723. unsigned DiagID = diag::ext_forward_ref_enum;
  7724. if (getLangOpts().MicrosoftMode)
  7725. DiagID = diag::ext_ms_forward_ref_enum;
  7726. else if (getLangOpts().CPlusPlus)
  7727. DiagID = diag::err_forward_ref_enum;
  7728. Diag(Loc, DiagID);
  7729. // If this is a forward-declared reference to an enumeration, make a
  7730. // note of it; we won't actually be introducing the declaration into
  7731. // the declaration context.
  7732. if (TUK == TUK_Reference)
  7733. IsForwardReference = true;
  7734. }
  7735. }
  7736. if (EnumUnderlying) {
  7737. EnumDecl *ED = cast<EnumDecl>(New);
  7738. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  7739. ED->setIntegerTypeSourceInfo(TI);
  7740. else
  7741. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  7742. ED->setPromotionType(ED->getIntegerType());
  7743. }
  7744. } else {
  7745. // struct/union/class
  7746. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  7747. // struct X { int A; } D; D should chain to X.
  7748. if (getLangOpts().CPlusPlus) {
  7749. // FIXME: Look for a way to use RecordDecl for simple structs.
  7750. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7751. cast_or_null<CXXRecordDecl>(PrevDecl));
  7752. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  7753. StdBadAlloc = cast<CXXRecordDecl>(New);
  7754. } else
  7755. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  7756. cast_or_null<RecordDecl>(PrevDecl));
  7757. }
  7758. // Maybe add qualifier info.
  7759. if (SS.isNotEmpty()) {
  7760. if (SS.isSet()) {
  7761. // If this is either a declaration or a definition, check the
  7762. // nested-name-specifier against the current context. We don't do this
  7763. // for explicit specializations, because they have similar checking
  7764. // (with more specific diagnostics) in the call to
  7765. // CheckMemberSpecialization, below.
  7766. if (!isExplicitSpecialization &&
  7767. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  7768. diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
  7769. Invalid = true;
  7770. New->setQualifierInfo(SS.getWithLocInContext(Context));
  7771. if (TemplateParameterLists.size() > 0) {
  7772. New->setTemplateParameterListsInfo(Context,
  7773. TemplateParameterLists.size(),
  7774. TemplateParameterLists.get());
  7775. }
  7776. }
  7777. else
  7778. Invalid = true;
  7779. }
  7780. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  7781. // Add alignment attributes if necessary; these attributes are checked when
  7782. // the ASTContext lays out the structure.
  7783. //
  7784. // It is important for implementing the correct semantics that this
  7785. // happen here (in act on tag decl). The #pragma pack stack is
  7786. // maintained as a result of parser callbacks which can occur at
  7787. // many points during the parsing of a struct declaration (because
  7788. // the #pragma tokens are effectively skipped over during the
  7789. // parsing of the struct).
  7790. if (TUK == TUK_Definition) {
  7791. AddAlignmentAttributesForRecord(RD);
  7792. AddMsStructLayoutForRecord(RD);
  7793. }
  7794. }
  7795. if (ModulePrivateLoc.isValid()) {
  7796. if (isExplicitSpecialization)
  7797. Diag(New->getLocation(), diag::err_module_private_specialization)
  7798. << 2
  7799. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7800. // __module_private__ does not apply to local classes. However, we only
  7801. // diagnose this as an error when the declaration specifiers are
  7802. // freestanding. Here, we just ignore the __module_private__.
  7803. else if (!SearchDC->isFunctionOrMethod())
  7804. New->setModulePrivate();
  7805. }
  7806. // If this is a specialization of a member class (of a class template),
  7807. // check the specialization.
  7808. if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
  7809. Invalid = true;
  7810. if (Invalid)
  7811. New->setInvalidDecl();
  7812. if (Attr)
  7813. ProcessDeclAttributeList(S, New, Attr);
  7814. // If we're declaring or defining a tag in function prototype scope
  7815. // in C, note that this type can only be used within the function.
  7816. if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
  7817. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  7818. // Set the lexical context. If the tag has a C++ scope specifier, the
  7819. // lexical context will be different from the semantic context.
  7820. New->setLexicalDeclContext(CurContext);
  7821. // Mark this as a friend decl if applicable.
  7822. // In Microsoft mode, a friend declaration also acts as a forward
  7823. // declaration so we always pass true to setObjectOfFriendDecl to make
  7824. // the tag name visible.
  7825. if (TUK == TUK_Friend)
  7826. New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
  7827. getLangOpts().MicrosoftExt);
  7828. // Set the access specifier.
  7829. if (!Invalid && SearchDC->isRecord())
  7830. SetMemberAccessSpecifier(New, PrevDecl, AS);
  7831. if (TUK == TUK_Definition)
  7832. New->startDefinition();
  7833. // If this has an identifier, add it to the scope stack.
  7834. if (TUK == TUK_Friend) {
  7835. // We might be replacing an existing declaration in the lookup tables;
  7836. // if so, borrow its access specifier.
  7837. if (PrevDecl)
  7838. New->setAccess(PrevDecl->getAccess());
  7839. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  7840. DC->makeDeclVisibleInContext(New);
  7841. if (Name) // can be null along some error paths
  7842. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  7843. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  7844. } else if (Name) {
  7845. S = getNonFieldDeclScope(S);
  7846. PushOnScopeChains(New, S, !IsForwardReference);
  7847. if (IsForwardReference)
  7848. SearchDC->makeDeclVisibleInContext(New);
  7849. } else {
  7850. CurContext->addDecl(New);
  7851. }
  7852. // If this is the C FILE type, notify the AST context.
  7853. if (IdentifierInfo *II = New->getIdentifier())
  7854. if (!New->isInvalidDecl() &&
  7855. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  7856. II->isStr("FILE"))
  7857. Context.setFILEDecl(New);
  7858. // If we were in function prototype scope (and not in C++ mode), add this
  7859. // tag to the list of decls to inject into the function definition scope.
  7860. if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
  7861. InFunctionDeclarator && Name)
  7862. DeclsInPrototypeScope.push_back(New);
  7863. if (PrevDecl)
  7864. mergeDeclAttributes(New, PrevDecl);
  7865. // If there's a #pragma GCC visibility in scope, set the visibility of this
  7866. // record.
  7867. AddPushedVisibilityAttribute(New);
  7868. OwnedDecl = true;
  7869. return New;
  7870. }
  7871. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  7872. AdjustDeclIfTemplate(TagD);
  7873. TagDecl *Tag = cast<TagDecl>(TagD);
  7874. // Enter the tag context.
  7875. PushDeclContext(S, Tag);
  7876. ActOnDocumentableDecl(TagD);
  7877. // If there's a #pragma GCC visibility in scope, set the visibility of this
  7878. // record.
  7879. AddPushedVisibilityAttribute(Tag);
  7880. }
  7881. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  7882. assert(isa<ObjCContainerDecl>(IDecl) &&
  7883. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  7884. DeclContext *OCD = cast<DeclContext>(IDecl);
  7885. assert(getContainingDC(OCD) == CurContext &&
  7886. "The next DeclContext should be lexically contained in the current one.");
  7887. CurContext = OCD;
  7888. return IDecl;
  7889. }
  7890. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  7891. SourceLocation FinalLoc,
  7892. SourceLocation LBraceLoc) {
  7893. AdjustDeclIfTemplate(TagD);
  7894. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  7895. FieldCollector->StartClass();
  7896. if (!Record->getIdentifier())
  7897. return;
  7898. if (FinalLoc.isValid())
  7899. Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
  7900. // C++ [class]p2:
  7901. // [...] The class-name is also inserted into the scope of the
  7902. // class itself; this is known as the injected-class-name. For
  7903. // purposes of access checking, the injected-class-name is treated
  7904. // as if it were a public member name.
  7905. CXXRecordDecl *InjectedClassName
  7906. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  7907. Record->getLocStart(), Record->getLocation(),
  7908. Record->getIdentifier(),
  7909. /*PrevDecl=*/0,
  7910. /*DelayTypeCreation=*/true);
  7911. Context.getTypeDeclType(InjectedClassName, Record);
  7912. InjectedClassName->setImplicit();
  7913. InjectedClassName->setAccess(AS_public);
  7914. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  7915. InjectedClassName->setDescribedClassTemplate(Template);
  7916. PushOnScopeChains(InjectedClassName, S);
  7917. assert(InjectedClassName->isInjectedClassName() &&
  7918. "Broken injected-class-name");
  7919. }
  7920. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  7921. SourceLocation RBraceLoc) {
  7922. AdjustDeclIfTemplate(TagD);
  7923. TagDecl *Tag = cast<TagDecl>(TagD);
  7924. Tag->setRBraceLoc(RBraceLoc);
  7925. // Make sure we "complete" the definition even it is invalid.
  7926. if (Tag->isBeingDefined()) {
  7927. assert(Tag->isInvalidDecl() && "We should already have completed it");
  7928. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  7929. RD->completeDefinition();
  7930. }
  7931. if (isa<CXXRecordDecl>(Tag))
  7932. FieldCollector->FinishClass();
  7933. // Exit this scope of this tag's definition.
  7934. PopDeclContext();
  7935. // Notify the consumer that we've defined a tag.
  7936. Consumer.HandleTagDeclDefinition(Tag);
  7937. }
  7938. void Sema::ActOnObjCContainerFinishDefinition() {
  7939. // Exit this scope of this interface definition.
  7940. PopDeclContext();
  7941. }
  7942. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  7943. assert(DC == CurContext && "Mismatch of container contexts");
  7944. OriginalLexicalContext = DC;
  7945. ActOnObjCContainerFinishDefinition();
  7946. }
  7947. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  7948. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  7949. OriginalLexicalContext = 0;
  7950. }
  7951. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  7952. AdjustDeclIfTemplate(TagD);
  7953. TagDecl *Tag = cast<TagDecl>(TagD);
  7954. Tag->setInvalidDecl();
  7955. // Make sure we "complete" the definition even it is invalid.
  7956. if (Tag->isBeingDefined()) {
  7957. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  7958. RD->completeDefinition();
  7959. }
  7960. // We're undoing ActOnTagStartDefinition here, not
  7961. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  7962. // the FieldCollector.
  7963. PopDeclContext();
  7964. }
  7965. // Note that FieldName may be null for anonymous bitfields.
  7966. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  7967. IdentifierInfo *FieldName,
  7968. QualType FieldTy, Expr *BitWidth,
  7969. bool *ZeroWidth) {
  7970. // Default to true; that shouldn't confuse checks for emptiness
  7971. if (ZeroWidth)
  7972. *ZeroWidth = true;
  7973. // C99 6.7.2.1p4 - verify the field type.
  7974. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  7975. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  7976. // Handle incomplete types with specific error.
  7977. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  7978. return ExprError();
  7979. if (FieldName)
  7980. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  7981. << FieldName << FieldTy << BitWidth->getSourceRange();
  7982. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  7983. << FieldTy << BitWidth->getSourceRange();
  7984. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  7985. UPPC_BitFieldWidth))
  7986. return ExprError();
  7987. // If the bit-width is type- or value-dependent, don't try to check
  7988. // it now.
  7989. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  7990. return Owned(BitWidth);
  7991. llvm::APSInt Value;
  7992. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  7993. if (ICE.isInvalid())
  7994. return ICE;
  7995. BitWidth = ICE.take();
  7996. if (Value != 0 && ZeroWidth)
  7997. *ZeroWidth = false;
  7998. // Zero-width bitfield is ok for anonymous field.
  7999. if (Value == 0 && FieldName)
  8000. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  8001. if (Value.isSigned() && Value.isNegative()) {
  8002. if (FieldName)
  8003. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  8004. << FieldName << Value.toString(10);
  8005. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  8006. << Value.toString(10);
  8007. }
  8008. if (!FieldTy->isDependentType()) {
  8009. uint64_t TypeSize = Context.getTypeSize(FieldTy);
  8010. if (Value.getZExtValue() > TypeSize) {
  8011. if (!getLangOpts().CPlusPlus) {
  8012. if (FieldName)
  8013. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
  8014. << FieldName << (unsigned)Value.getZExtValue()
  8015. << (unsigned)TypeSize;
  8016. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
  8017. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  8018. }
  8019. if (FieldName)
  8020. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
  8021. << FieldName << (unsigned)Value.getZExtValue()
  8022. << (unsigned)TypeSize;
  8023. else
  8024. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
  8025. << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
  8026. }
  8027. }
  8028. return Owned(BitWidth);
  8029. }
  8030. /// ActOnField - Each field of a C struct/union is passed into this in order
  8031. /// to create a FieldDecl object for it.
  8032. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  8033. Declarator &D, Expr *BitfieldWidth) {
  8034. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  8035. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  8036. /*InitStyle=*/ICIS_NoInit, AS_public);
  8037. return Res;
  8038. }
  8039. /// HandleField - Analyze a field of a C struct or a C++ data member.
  8040. ///
  8041. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  8042. SourceLocation DeclStart,
  8043. Declarator &D, Expr *BitWidth,
  8044. InClassInitStyle InitStyle,
  8045. AccessSpecifier AS) {
  8046. IdentifierInfo *II = D.getIdentifier();
  8047. SourceLocation Loc = DeclStart;
  8048. if (II) Loc = D.getIdentifierLoc();
  8049. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8050. QualType T = TInfo->getType();
  8051. if (getLangOpts().CPlusPlus) {
  8052. CheckExtraCXXDefaultArguments(D);
  8053. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  8054. UPPC_DataMemberType)) {
  8055. D.setInvalidType();
  8056. T = Context.IntTy;
  8057. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  8058. }
  8059. }
  8060. DiagnoseFunctionSpecifiers(D);
  8061. if (D.getDeclSpec().isThreadSpecified())
  8062. Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
  8063. if (D.getDeclSpec().isConstexprSpecified())
  8064. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  8065. << 2;
  8066. // Check to see if this name was declared as a member previously
  8067. NamedDecl *PrevDecl = 0;
  8068. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  8069. LookupName(Previous, S);
  8070. switch (Previous.getResultKind()) {
  8071. case LookupResult::Found:
  8072. case LookupResult::FoundUnresolvedValue:
  8073. PrevDecl = Previous.getAsSingle<NamedDecl>();
  8074. break;
  8075. case LookupResult::FoundOverloaded:
  8076. PrevDecl = Previous.getRepresentativeDecl();
  8077. break;
  8078. case LookupResult::NotFound:
  8079. case LookupResult::NotFoundInCurrentInstantiation:
  8080. case LookupResult::Ambiguous:
  8081. break;
  8082. }
  8083. Previous.suppressDiagnostics();
  8084. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  8085. // Maybe we will complain about the shadowed template parameter.
  8086. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  8087. // Just pretend that we didn't see the previous declaration.
  8088. PrevDecl = 0;
  8089. }
  8090. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  8091. PrevDecl = 0;
  8092. bool Mutable
  8093. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  8094. SourceLocation TSSL = D.getLocStart();
  8095. FieldDecl *NewFD
  8096. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  8097. TSSL, AS, PrevDecl, &D);
  8098. if (NewFD->isInvalidDecl())
  8099. Record->setInvalidDecl();
  8100. if (D.getDeclSpec().isModulePrivateSpecified())
  8101. NewFD->setModulePrivate();
  8102. if (NewFD->isInvalidDecl() && PrevDecl) {
  8103. // Don't introduce NewFD into scope; there's already something
  8104. // with the same name in the same scope.
  8105. } else if (II) {
  8106. PushOnScopeChains(NewFD, S);
  8107. } else
  8108. Record->addDecl(NewFD);
  8109. return NewFD;
  8110. }
  8111. /// \brief Build a new FieldDecl and check its well-formedness.
  8112. ///
  8113. /// This routine builds a new FieldDecl given the fields name, type,
  8114. /// record, etc. \p PrevDecl should refer to any previous declaration
  8115. /// with the same name and in the same scope as the field to be
  8116. /// created.
  8117. ///
  8118. /// \returns a new FieldDecl.
  8119. ///
  8120. /// \todo The Declarator argument is a hack. It will be removed once
  8121. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  8122. TypeSourceInfo *TInfo,
  8123. RecordDecl *Record, SourceLocation Loc,
  8124. bool Mutable, Expr *BitWidth,
  8125. InClassInitStyle InitStyle,
  8126. SourceLocation TSSL,
  8127. AccessSpecifier AS, NamedDecl *PrevDecl,
  8128. Declarator *D) {
  8129. IdentifierInfo *II = Name.getAsIdentifierInfo();
  8130. bool InvalidDecl = false;
  8131. if (D) InvalidDecl = D->isInvalidType();
  8132. // If we receive a broken type, recover by assuming 'int' and
  8133. // marking this declaration as invalid.
  8134. if (T.isNull()) {
  8135. InvalidDecl = true;
  8136. T = Context.IntTy;
  8137. }
  8138. QualType EltTy = Context.getBaseElementType(T);
  8139. if (!EltTy->isDependentType()) {
  8140. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  8141. // Fields of incomplete type force their record to be invalid.
  8142. Record->setInvalidDecl();
  8143. InvalidDecl = true;
  8144. } else {
  8145. NamedDecl *Def;
  8146. EltTy->isIncompleteType(&Def);
  8147. if (Def && Def->isInvalidDecl()) {
  8148. Record->setInvalidDecl();
  8149. InvalidDecl = true;
  8150. }
  8151. }
  8152. }
  8153. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  8154. // than a variably modified type.
  8155. if (!InvalidDecl && T->isVariablyModifiedType()) {
  8156. bool SizeIsNegative;
  8157. llvm::APSInt Oversized;
  8158. QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
  8159. SizeIsNegative,
  8160. Oversized);
  8161. if (!FixedTy.isNull()) {
  8162. Diag(Loc, diag::warn_illegal_constant_array_size);
  8163. T = FixedTy;
  8164. } else {
  8165. if (SizeIsNegative)
  8166. Diag(Loc, diag::err_typecheck_negative_array_size);
  8167. else if (Oversized.getBoolValue())
  8168. Diag(Loc, diag::err_array_too_large)
  8169. << Oversized.toString(10);
  8170. else
  8171. Diag(Loc, diag::err_typecheck_field_variable_size);
  8172. InvalidDecl = true;
  8173. }
  8174. }
  8175. // Fields can not have abstract class types
  8176. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  8177. diag::err_abstract_type_in_decl,
  8178. AbstractFieldType))
  8179. InvalidDecl = true;
  8180. bool ZeroWidth = false;
  8181. // If this is declared as a bit-field, check the bit-field.
  8182. if (!InvalidDecl && BitWidth) {
  8183. BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
  8184. if (!BitWidth) {
  8185. InvalidDecl = true;
  8186. BitWidth = 0;
  8187. ZeroWidth = false;
  8188. }
  8189. }
  8190. // Check that 'mutable' is consistent with the type of the declaration.
  8191. if (!InvalidDecl && Mutable) {
  8192. unsigned DiagID = 0;
  8193. if (T->isReferenceType())
  8194. DiagID = diag::err_mutable_reference;
  8195. else if (T.isConstQualified())
  8196. DiagID = diag::err_mutable_const;
  8197. if (DiagID) {
  8198. SourceLocation ErrLoc = Loc;
  8199. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  8200. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  8201. Diag(ErrLoc, DiagID);
  8202. Mutable = false;
  8203. InvalidDecl = true;
  8204. }
  8205. }
  8206. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  8207. BitWidth, Mutable, InitStyle);
  8208. if (InvalidDecl)
  8209. NewFD->setInvalidDecl();
  8210. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  8211. Diag(Loc, diag::err_duplicate_member) << II;
  8212. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8213. NewFD->setInvalidDecl();
  8214. }
  8215. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  8216. if (Record->isUnion()) {
  8217. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  8218. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  8219. if (RDecl->getDefinition()) {
  8220. // C++ [class.union]p1: An object of a class with a non-trivial
  8221. // constructor, a non-trivial copy constructor, a non-trivial
  8222. // destructor, or a non-trivial copy assignment operator
  8223. // cannot be a member of a union, nor can an array of such
  8224. // objects.
  8225. if (CheckNontrivialField(NewFD))
  8226. NewFD->setInvalidDecl();
  8227. }
  8228. }
  8229. // C++ [class.union]p1: If a union contains a member of reference type,
  8230. // the program is ill-formed.
  8231. if (EltTy->isReferenceType()) {
  8232. Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
  8233. << NewFD->getDeclName() << EltTy;
  8234. NewFD->setInvalidDecl();
  8235. }
  8236. }
  8237. }
  8238. // FIXME: We need to pass in the attributes given an AST
  8239. // representation, not a parser representation.
  8240. if (D)
  8241. // FIXME: What to pass instead of TUScope?
  8242. ProcessDeclAttributes(TUScope, NewFD, *D);
  8243. // In auto-retain/release, infer strong retension for fields of
  8244. // retainable type.
  8245. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  8246. NewFD->setInvalidDecl();
  8247. if (T.isObjCGCWeak())
  8248. Diag(Loc, diag::warn_attribute_weak_on_field);
  8249. NewFD->setAccess(AS);
  8250. return NewFD;
  8251. }
  8252. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  8253. assert(FD);
  8254. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  8255. if (FD->isInvalidDecl())
  8256. return true;
  8257. QualType EltTy = Context.getBaseElementType(FD->getType());
  8258. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  8259. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  8260. if (RDecl->getDefinition()) {
  8261. // We check for copy constructors before constructors
  8262. // because otherwise we'll never get complaints about
  8263. // copy constructors.
  8264. CXXSpecialMember member = CXXInvalid;
  8265. if (!RDecl->hasTrivialCopyConstructor())
  8266. member = CXXCopyConstructor;
  8267. else if (!RDecl->hasTrivialDefaultConstructor())
  8268. member = CXXDefaultConstructor;
  8269. else if (!RDecl->hasTrivialCopyAssignment())
  8270. member = CXXCopyAssignment;
  8271. else if (!RDecl->hasTrivialDestructor())
  8272. member = CXXDestructor;
  8273. if (member != CXXInvalid) {
  8274. if (!getLangOpts().CPlusPlus0x &&
  8275. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  8276. // Objective-C++ ARC: it is an error to have a non-trivial field of
  8277. // a union. However, system headers in Objective-C programs
  8278. // occasionally have Objective-C lifetime objects within unions,
  8279. // and rather than cause the program to fail, we make those
  8280. // members unavailable.
  8281. SourceLocation Loc = FD->getLocation();
  8282. if (getSourceManager().isInSystemHeader(Loc)) {
  8283. if (!FD->hasAttr<UnavailableAttr>())
  8284. FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
  8285. "this system field has retaining ownership"));
  8286. return false;
  8287. }
  8288. }
  8289. Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
  8290. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  8291. diag::err_illegal_union_or_anon_struct_member)
  8292. << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
  8293. DiagnoseNontrivial(RT, member);
  8294. return !getLangOpts().CPlusPlus0x;
  8295. }
  8296. }
  8297. }
  8298. return false;
  8299. }
  8300. /// If the given constructor is user-provided, produce a diagnostic explaining
  8301. /// that it makes the class non-trivial.
  8302. static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
  8303. CXXConstructorDecl *CD,
  8304. Sema::CXXSpecialMember CSM) {
  8305. if (!CD->isUserProvided())
  8306. return false;
  8307. SourceLocation CtorLoc = CD->getLocation();
  8308. S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
  8309. return true;
  8310. }
  8311. /// DiagnoseNontrivial - Given that a class has a non-trivial
  8312. /// special member, figure out why.
  8313. void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
  8314. QualType QT(T, 0U);
  8315. CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
  8316. // Check whether the member was user-declared.
  8317. switch (member) {
  8318. case CXXInvalid:
  8319. break;
  8320. case CXXDefaultConstructor:
  8321. if (RD->hasUserDeclaredConstructor()) {
  8322. typedef CXXRecordDecl::ctor_iterator ctor_iter;
  8323. for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
  8324. if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
  8325. return;
  8326. // No user-provided constructors; look for constructor templates.
  8327. typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
  8328. tmpl_iter;
  8329. for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
  8330. TI != TE; ++TI) {
  8331. CXXConstructorDecl *CD =
  8332. dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
  8333. if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
  8334. return;
  8335. }
  8336. }
  8337. break;
  8338. case CXXCopyConstructor:
  8339. if (RD->hasUserDeclaredCopyConstructor()) {
  8340. SourceLocation CtorLoc =
  8341. RD->getCopyConstructor(0)->getLocation();
  8342. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  8343. return;
  8344. }
  8345. break;
  8346. case CXXMoveConstructor:
  8347. if (RD->hasUserDeclaredMoveConstructor()) {
  8348. SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
  8349. Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  8350. return;
  8351. }
  8352. break;
  8353. case CXXCopyAssignment:
  8354. if (RD->hasUserDeclaredCopyAssignment()) {
  8355. SourceLocation AssignLoc =
  8356. RD->getCopyAssignmentOperator(0)->getLocation();
  8357. Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
  8358. return;
  8359. }
  8360. break;
  8361. case CXXMoveAssignment:
  8362. if (RD->hasUserDeclaredMoveAssignment()) {
  8363. SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
  8364. Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
  8365. return;
  8366. }
  8367. break;
  8368. case CXXDestructor:
  8369. if (RD->hasUserDeclaredDestructor()) {
  8370. SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
  8371. Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
  8372. return;
  8373. }
  8374. break;
  8375. }
  8376. typedef CXXRecordDecl::base_class_iterator base_iter;
  8377. // Virtual bases and members inhibit trivial copying/construction,
  8378. // but not trivial destruction.
  8379. if (member != CXXDestructor) {
  8380. // Check for virtual bases. vbases includes indirect virtual bases,
  8381. // so we just iterate through the direct bases.
  8382. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
  8383. if (bi->isVirtual()) {
  8384. SourceLocation BaseLoc = bi->getLocStart();
  8385. Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
  8386. return;
  8387. }
  8388. // Check for virtual methods.
  8389. typedef CXXRecordDecl::method_iterator meth_iter;
  8390. for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
  8391. ++mi) {
  8392. if (mi->isVirtual()) {
  8393. SourceLocation MLoc = mi->getLocStart();
  8394. Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
  8395. return;
  8396. }
  8397. }
  8398. }
  8399. bool (CXXRecordDecl::*hasTrivial)() const;
  8400. switch (member) {
  8401. case CXXDefaultConstructor:
  8402. hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
  8403. case CXXCopyConstructor:
  8404. hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
  8405. case CXXCopyAssignment:
  8406. hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
  8407. case CXXDestructor:
  8408. hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
  8409. default:
  8410. llvm_unreachable("unexpected special member");
  8411. }
  8412. // Check for nontrivial bases (and recurse).
  8413. for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
  8414. const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
  8415. assert(BaseRT && "Don't know how to handle dependent bases");
  8416. CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
  8417. if (!(BaseRecTy->*hasTrivial)()) {
  8418. SourceLocation BaseLoc = bi->getLocStart();
  8419. Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
  8420. DiagnoseNontrivial(BaseRT, member);
  8421. return;
  8422. }
  8423. }
  8424. // Check for nontrivial members (and recurse).
  8425. typedef RecordDecl::field_iterator field_iter;
  8426. for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
  8427. ++fi) {
  8428. QualType EltTy = Context.getBaseElementType(fi->getType());
  8429. if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
  8430. CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
  8431. if (!(EltRD->*hasTrivial)()) {
  8432. SourceLocation FLoc = fi->getLocation();
  8433. Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
  8434. DiagnoseNontrivial(EltRT, member);
  8435. return;
  8436. }
  8437. }
  8438. if (EltTy->isObjCLifetimeType()) {
  8439. switch (EltTy.getObjCLifetime()) {
  8440. case Qualifiers::OCL_None:
  8441. case Qualifiers::OCL_ExplicitNone:
  8442. break;
  8443. case Qualifiers::OCL_Autoreleasing:
  8444. case Qualifiers::OCL_Weak:
  8445. case Qualifiers::OCL_Strong:
  8446. Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership)
  8447. << QT << EltTy.getObjCLifetime();
  8448. return;
  8449. }
  8450. }
  8451. }
  8452. llvm_unreachable("found no explanation for non-trivial member");
  8453. }
  8454. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  8455. /// AST enum value.
  8456. static ObjCIvarDecl::AccessControl
  8457. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  8458. switch (ivarVisibility) {
  8459. default: llvm_unreachable("Unknown visitibility kind");
  8460. case tok::objc_private: return ObjCIvarDecl::Private;
  8461. case tok::objc_public: return ObjCIvarDecl::Public;
  8462. case tok::objc_protected: return ObjCIvarDecl::Protected;
  8463. case tok::objc_package: return ObjCIvarDecl::Package;
  8464. }
  8465. }
  8466. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  8467. /// in order to create an IvarDecl object for it.
  8468. Decl *Sema::ActOnIvar(Scope *S,
  8469. SourceLocation DeclStart,
  8470. Declarator &D, Expr *BitfieldWidth,
  8471. tok::ObjCKeywordKind Visibility) {
  8472. IdentifierInfo *II = D.getIdentifier();
  8473. Expr *BitWidth = (Expr*)BitfieldWidth;
  8474. SourceLocation Loc = DeclStart;
  8475. if (II) Loc = D.getIdentifierLoc();
  8476. // FIXME: Unnamed fields can be handled in various different ways, for
  8477. // example, unnamed unions inject all members into the struct namespace!
  8478. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  8479. QualType T = TInfo->getType();
  8480. if (BitWidth) {
  8481. // 6.7.2.1p3, 6.7.2.1p4
  8482. BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
  8483. if (!BitWidth)
  8484. D.setInvalidType();
  8485. } else {
  8486. // Not a bitfield.
  8487. // validate II.
  8488. }
  8489. if (T->isReferenceType()) {
  8490. Diag(Loc, diag::err_ivar_reference_type);
  8491. D.setInvalidType();
  8492. }
  8493. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  8494. // than a variably modified type.
  8495. else if (T->isVariablyModifiedType()) {
  8496. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  8497. D.setInvalidType();
  8498. }
  8499. // Get the visibility (access control) for this ivar.
  8500. ObjCIvarDecl::AccessControl ac =
  8501. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  8502. : ObjCIvarDecl::None;
  8503. // Must set ivar's DeclContext to its enclosing interface.
  8504. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  8505. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  8506. return 0;
  8507. ObjCContainerDecl *EnclosingContext;
  8508. if (ObjCImplementationDecl *IMPDecl =
  8509. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  8510. if (LangOpts.ObjCRuntime.isFragile()) {
  8511. // Case of ivar declared in an implementation. Context is that of its class.
  8512. EnclosingContext = IMPDecl->getClassInterface();
  8513. assert(EnclosingContext && "Implementation has no class interface!");
  8514. }
  8515. else
  8516. EnclosingContext = EnclosingDecl;
  8517. } else {
  8518. if (ObjCCategoryDecl *CDecl =
  8519. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8520. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  8521. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  8522. return 0;
  8523. }
  8524. }
  8525. EnclosingContext = EnclosingDecl;
  8526. }
  8527. // Construct the decl.
  8528. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  8529. DeclStart, Loc, II, T,
  8530. TInfo, ac, (Expr *)BitfieldWidth);
  8531. if (II) {
  8532. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  8533. ForRedeclaration);
  8534. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  8535. && !isa<TagDecl>(PrevDecl)) {
  8536. Diag(Loc, diag::err_duplicate_member) << II;
  8537. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  8538. NewID->setInvalidDecl();
  8539. }
  8540. }
  8541. // Process attributes attached to the ivar.
  8542. ProcessDeclAttributes(S, NewID, D);
  8543. if (D.isInvalidType())
  8544. NewID->setInvalidDecl();
  8545. // In ARC, infer 'retaining' for ivars of retainable type.
  8546. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  8547. NewID->setInvalidDecl();
  8548. if (D.getDeclSpec().isModulePrivateSpecified())
  8549. NewID->setModulePrivate();
  8550. if (II) {
  8551. // FIXME: When interfaces are DeclContexts, we'll need to add
  8552. // these to the interface.
  8553. S->AddDecl(NewID);
  8554. IdResolver.AddDecl(NewID);
  8555. }
  8556. if (LangOpts.ObjCRuntime.isNonFragile() &&
  8557. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  8558. Diag(Loc, diag::warn_ivars_in_interface);
  8559. return NewID;
  8560. }
  8561. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  8562. /// class and class extensions. For every class @interface and class
  8563. /// extension @interface, if the last ivar is a bitfield of any type,
  8564. /// then add an implicit `char :0` ivar to the end of that interface.
  8565. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  8566. SmallVectorImpl<Decl *> &AllIvarDecls) {
  8567. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  8568. return;
  8569. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  8570. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  8571. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  8572. return;
  8573. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  8574. if (!ID) {
  8575. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  8576. if (!CD->IsClassExtension())
  8577. return;
  8578. }
  8579. // No need to add this to end of @implementation.
  8580. else
  8581. return;
  8582. }
  8583. // All conditions are met. Add a new bitfield to the tail end of ivars.
  8584. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  8585. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  8586. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  8587. DeclLoc, DeclLoc, 0,
  8588. Context.CharTy,
  8589. Context.getTrivialTypeSourceInfo(Context.CharTy,
  8590. DeclLoc),
  8591. ObjCIvarDecl::Private, BW,
  8592. true);
  8593. AllIvarDecls.push_back(Ivar);
  8594. }
  8595. void Sema::ActOnFields(Scope* S,
  8596. SourceLocation RecLoc, Decl *EnclosingDecl,
  8597. llvm::ArrayRef<Decl *> Fields,
  8598. SourceLocation LBrac, SourceLocation RBrac,
  8599. AttributeList *Attr) {
  8600. assert(EnclosingDecl && "missing record or interface decl");
  8601. // If this is an Objective-C @implementation or category and we have
  8602. // new fields here we should reset the layout of the interface since
  8603. // it will now change.
  8604. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  8605. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  8606. switch (DC->getKind()) {
  8607. default: break;
  8608. case Decl::ObjCCategory:
  8609. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  8610. break;
  8611. case Decl::ObjCImplementation:
  8612. Context.
  8613. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  8614. break;
  8615. }
  8616. }
  8617. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  8618. // Start counting up the number of named members; make sure to include
  8619. // members of anonymous structs and unions in the total.
  8620. unsigned NumNamedMembers = 0;
  8621. if (Record) {
  8622. for (RecordDecl::decl_iterator i = Record->decls_begin(),
  8623. e = Record->decls_end(); i != e; i++) {
  8624. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
  8625. if (IFD->getDeclName())
  8626. ++NumNamedMembers;
  8627. }
  8628. }
  8629. // Verify that all the fields are okay.
  8630. SmallVector<FieldDecl*, 32> RecFields;
  8631. bool ARCErrReported = false;
  8632. for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  8633. i != end; ++i) {
  8634. FieldDecl *FD = cast<FieldDecl>(*i);
  8635. // Get the type for the field.
  8636. const Type *FDTy = FD->getType().getTypePtr();
  8637. if (!FD->isAnonymousStructOrUnion()) {
  8638. // Remember all fields written by the user.
  8639. RecFields.push_back(FD);
  8640. }
  8641. // If the field is already invalid for some reason, don't emit more
  8642. // diagnostics about it.
  8643. if (FD->isInvalidDecl()) {
  8644. EnclosingDecl->setInvalidDecl();
  8645. continue;
  8646. }
  8647. // C99 6.7.2.1p2:
  8648. // A structure or union shall not contain a member with
  8649. // incomplete or function type (hence, a structure shall not
  8650. // contain an instance of itself, but may contain a pointer to
  8651. // an instance of itself), except that the last member of a
  8652. // structure with more than one named member may have incomplete
  8653. // array type; such a structure (and any union containing,
  8654. // possibly recursively, a member that is such a structure)
  8655. // shall not be a member of a structure or an element of an
  8656. // array.
  8657. if (FDTy->isFunctionType()) {
  8658. // Field declared as a function.
  8659. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  8660. << FD->getDeclName();
  8661. FD->setInvalidDecl();
  8662. EnclosingDecl->setInvalidDecl();
  8663. continue;
  8664. } else if (FDTy->isIncompleteArrayType() && Record &&
  8665. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  8666. ((getLangOpts().MicrosoftExt ||
  8667. getLangOpts().CPlusPlus) &&
  8668. (i + 1 == Fields.end() || Record->isUnion())))) {
  8669. // Flexible array member.
  8670. // Microsoft and g++ is more permissive regarding flexible array.
  8671. // It will accept flexible array in union and also
  8672. // as the sole element of a struct/class.
  8673. if (getLangOpts().MicrosoftExt) {
  8674. if (Record->isUnion())
  8675. Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
  8676. << FD->getDeclName();
  8677. else if (Fields.size() == 1)
  8678. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
  8679. << FD->getDeclName() << Record->getTagKind();
  8680. } else if (getLangOpts().CPlusPlus) {
  8681. if (Record->isUnion())
  8682. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  8683. << FD->getDeclName();
  8684. else if (Fields.size() == 1)
  8685. Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
  8686. << FD->getDeclName() << Record->getTagKind();
  8687. } else if (!getLangOpts().C99) {
  8688. if (Record->isUnion())
  8689. Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
  8690. << FD->getDeclName();
  8691. else
  8692. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  8693. << FD->getDeclName() << Record->getTagKind();
  8694. } else if (NumNamedMembers < 1) {
  8695. Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
  8696. << FD->getDeclName();
  8697. FD->setInvalidDecl();
  8698. EnclosingDecl->setInvalidDecl();
  8699. continue;
  8700. }
  8701. if (!FD->getType()->isDependentType() &&
  8702. !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
  8703. Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
  8704. << FD->getDeclName() << FD->getType();
  8705. FD->setInvalidDecl();
  8706. EnclosingDecl->setInvalidDecl();
  8707. continue;
  8708. }
  8709. // Okay, we have a legal flexible array member at the end of the struct.
  8710. if (Record)
  8711. Record->setHasFlexibleArrayMember(true);
  8712. } else if (!FDTy->isDependentType() &&
  8713. RequireCompleteType(FD->getLocation(), FD->getType(),
  8714. diag::err_field_incomplete)) {
  8715. // Incomplete type
  8716. FD->setInvalidDecl();
  8717. EnclosingDecl->setInvalidDecl();
  8718. continue;
  8719. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  8720. if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
  8721. // If this is a member of a union, then entire union becomes "flexible".
  8722. if (Record && Record->isUnion()) {
  8723. Record->setHasFlexibleArrayMember(true);
  8724. } else {
  8725. // If this is a struct/class and this is not the last element, reject
  8726. // it. Note that GCC supports variable sized arrays in the middle of
  8727. // structures.
  8728. if (i + 1 != Fields.end())
  8729. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  8730. << FD->getDeclName() << FD->getType();
  8731. else {
  8732. // We support flexible arrays at the end of structs in
  8733. // other structs as an extension.
  8734. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  8735. << FD->getDeclName();
  8736. if (Record)
  8737. Record->setHasFlexibleArrayMember(true);
  8738. }
  8739. }
  8740. }
  8741. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  8742. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  8743. diag::err_abstract_type_in_decl,
  8744. AbstractIvarType)) {
  8745. // Ivars can not have abstract class types
  8746. FD->setInvalidDecl();
  8747. }
  8748. if (Record && FDTTy->getDecl()->hasObjectMember())
  8749. Record->setHasObjectMember(true);
  8750. } else if (FDTy->isObjCObjectType()) {
  8751. /// A field cannot be an Objective-c object
  8752. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  8753. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  8754. QualType T = Context.getObjCObjectPointerType(FD->getType());
  8755. FD->setType(T);
  8756. } else if (!getLangOpts().CPlusPlus) {
  8757. if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
  8758. // It's an error in ARC if a field has lifetime.
  8759. // We don't want to report this in a system header, though,
  8760. // so we just make the field unavailable.
  8761. // FIXME: that's really not sufficient; we need to make the type
  8762. // itself invalid to, say, initialize or copy.
  8763. QualType T = FD->getType();
  8764. Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
  8765. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
  8766. SourceLocation loc = FD->getLocation();
  8767. if (getSourceManager().isInSystemHeader(loc)) {
  8768. if (!FD->hasAttr<UnavailableAttr>()) {
  8769. FD->addAttr(new (Context) UnavailableAttr(loc, Context,
  8770. "this system field has retaining ownership"));
  8771. }
  8772. } else {
  8773. Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
  8774. << T->isBlockPointerType();
  8775. }
  8776. ARCErrReported = true;
  8777. }
  8778. }
  8779. else if (getLangOpts().ObjC1 &&
  8780. getLangOpts().getGC() != LangOptions::NonGC &&
  8781. Record && !Record->hasObjectMember()) {
  8782. if (FD->getType()->isObjCObjectPointerType() ||
  8783. FD->getType().isObjCGCStrong())
  8784. Record->setHasObjectMember(true);
  8785. else if (Context.getAsArrayType(FD->getType())) {
  8786. QualType BaseType = Context.getBaseElementType(FD->getType());
  8787. if (BaseType->isRecordType() &&
  8788. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  8789. Record->setHasObjectMember(true);
  8790. else if (BaseType->isObjCObjectPointerType() ||
  8791. BaseType.isObjCGCStrong())
  8792. Record->setHasObjectMember(true);
  8793. }
  8794. }
  8795. }
  8796. // Keep track of the number of named members.
  8797. if (FD->getIdentifier())
  8798. ++NumNamedMembers;
  8799. }
  8800. // Okay, we successfully defined 'Record'.
  8801. if (Record) {
  8802. bool Completed = false;
  8803. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  8804. if (!CXXRecord->isInvalidDecl()) {
  8805. // Set access bits correctly on the directly-declared conversions.
  8806. UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
  8807. for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
  8808. I != E; ++I)
  8809. Convs->setAccess(I, (*I)->getAccess());
  8810. if (!CXXRecord->isDependentType()) {
  8811. // Objective-C Automatic Reference Counting:
  8812. // If a class has a non-static data member of Objective-C pointer
  8813. // type (or array thereof), it is a non-POD type and its
  8814. // default constructor (if any), copy constructor, copy assignment
  8815. // operator, and destructor are non-trivial.
  8816. //
  8817. // This rule is also handled by CXXRecordDecl::completeDefinition().
  8818. // However, here we check whether this particular class is only
  8819. // non-POD because of the presence of an Objective-C pointer member.
  8820. // If so, objects of this type cannot be shared between code compiled
  8821. // with ARC and code compiled with manual retain/release.
  8822. if (getLangOpts().ObjCAutoRefCount &&
  8823. CXXRecord->hasObjectMember() &&
  8824. CXXRecord->getLinkage() == ExternalLinkage) {
  8825. if (CXXRecord->isPOD()) {
  8826. Diag(CXXRecord->getLocation(),
  8827. diag::warn_arc_non_pod_class_with_object_member)
  8828. << CXXRecord;
  8829. } else {
  8830. // FIXME: Fix-Its would be nice here, but finding a good location
  8831. // for them is going to be tricky.
  8832. if (CXXRecord->hasTrivialCopyConstructor())
  8833. Diag(CXXRecord->getLocation(),
  8834. diag::warn_arc_trivial_member_function_with_object_member)
  8835. << CXXRecord << 0;
  8836. if (CXXRecord->hasTrivialCopyAssignment())
  8837. Diag(CXXRecord->getLocation(),
  8838. diag::warn_arc_trivial_member_function_with_object_member)
  8839. << CXXRecord << 1;
  8840. if (CXXRecord->hasTrivialDestructor())
  8841. Diag(CXXRecord->getLocation(),
  8842. diag::warn_arc_trivial_member_function_with_object_member)
  8843. << CXXRecord << 2;
  8844. }
  8845. }
  8846. // Adjust user-defined destructor exception spec.
  8847. if (getLangOpts().CPlusPlus0x &&
  8848. CXXRecord->hasUserDeclaredDestructor())
  8849. AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
  8850. // Add any implicitly-declared members to this class.
  8851. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  8852. // If we have virtual base classes, we may end up finding multiple
  8853. // final overriders for a given virtual function. Check for this
  8854. // problem now.
  8855. if (CXXRecord->getNumVBases()) {
  8856. CXXFinalOverriderMap FinalOverriders;
  8857. CXXRecord->getFinalOverriders(FinalOverriders);
  8858. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  8859. MEnd = FinalOverriders.end();
  8860. M != MEnd; ++M) {
  8861. for (OverridingMethods::iterator SO = M->second.begin(),
  8862. SOEnd = M->second.end();
  8863. SO != SOEnd; ++SO) {
  8864. assert(SO->second.size() > 0 &&
  8865. "Virtual function without overridding functions?");
  8866. if (SO->second.size() == 1)
  8867. continue;
  8868. // C++ [class.virtual]p2:
  8869. // In a derived class, if a virtual member function of a base
  8870. // class subobject has more than one final overrider the
  8871. // program is ill-formed.
  8872. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  8873. << (NamedDecl *)M->first << Record;
  8874. Diag(M->first->getLocation(),
  8875. diag::note_overridden_virtual_function);
  8876. for (OverridingMethods::overriding_iterator
  8877. OM = SO->second.begin(),
  8878. OMEnd = SO->second.end();
  8879. OM != OMEnd; ++OM)
  8880. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  8881. << (NamedDecl *)M->first << OM->Method->getParent();
  8882. Record->setInvalidDecl();
  8883. }
  8884. }
  8885. CXXRecord->completeDefinition(&FinalOverriders);
  8886. Completed = true;
  8887. }
  8888. }
  8889. }
  8890. }
  8891. if (!Completed)
  8892. Record->completeDefinition();
  8893. } else {
  8894. ObjCIvarDecl **ClsFields =
  8895. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  8896. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  8897. ID->setEndOfDefinitionLoc(RBrac);
  8898. // Add ivar's to class's DeclContext.
  8899. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8900. ClsFields[i]->setLexicalDeclContext(ID);
  8901. ID->addDecl(ClsFields[i]);
  8902. }
  8903. // Must enforce the rule that ivars in the base classes may not be
  8904. // duplicates.
  8905. if (ID->getSuperClass())
  8906. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  8907. } else if (ObjCImplementationDecl *IMPDecl =
  8908. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  8909. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  8910. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  8911. // Ivar declared in @implementation never belongs to the implementation.
  8912. // Only it is in implementation's lexical context.
  8913. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  8914. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  8915. IMPDecl->setIvarLBraceLoc(LBrac);
  8916. IMPDecl->setIvarRBraceLoc(RBrac);
  8917. } else if (ObjCCategoryDecl *CDecl =
  8918. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  8919. // case of ivars in class extension; all other cases have been
  8920. // reported as errors elsewhere.
  8921. // FIXME. Class extension does not have a LocEnd field.
  8922. // CDecl->setLocEnd(RBrac);
  8923. // Add ivar's to class extension's DeclContext.
  8924. // Diagnose redeclaration of private ivars.
  8925. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  8926. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  8927. if (IDecl) {
  8928. if (const ObjCIvarDecl *ClsIvar =
  8929. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8930. Diag(ClsFields[i]->getLocation(),
  8931. diag::err_duplicate_ivar_declaration);
  8932. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  8933. continue;
  8934. }
  8935. for (const ObjCCategoryDecl *ClsExtDecl =
  8936. IDecl->getFirstClassExtension();
  8937. ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
  8938. if (const ObjCIvarDecl *ClsExtIvar =
  8939. ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  8940. Diag(ClsFields[i]->getLocation(),
  8941. diag::err_duplicate_ivar_declaration);
  8942. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  8943. continue;
  8944. }
  8945. }
  8946. }
  8947. ClsFields[i]->setLexicalDeclContext(CDecl);
  8948. CDecl->addDecl(ClsFields[i]);
  8949. }
  8950. CDecl->setIvarLBraceLoc(LBrac);
  8951. CDecl->setIvarRBraceLoc(RBrac);
  8952. }
  8953. }
  8954. if (Attr)
  8955. ProcessDeclAttributeList(S, Record, Attr);
  8956. }
  8957. /// \brief Determine whether the given integral value is representable within
  8958. /// the given type T.
  8959. static bool isRepresentableIntegerValue(ASTContext &Context,
  8960. llvm::APSInt &Value,
  8961. QualType T) {
  8962. assert(T->isIntegralType(Context) && "Integral type required!");
  8963. unsigned BitWidth = Context.getIntWidth(T);
  8964. if (Value.isUnsigned() || Value.isNonNegative()) {
  8965. if (T->isSignedIntegerOrEnumerationType())
  8966. --BitWidth;
  8967. return Value.getActiveBits() <= BitWidth;
  8968. }
  8969. return Value.getMinSignedBits() <= BitWidth;
  8970. }
  8971. // \brief Given an integral type, return the next larger integral type
  8972. // (or a NULL type of no such type exists).
  8973. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  8974. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  8975. // enum checking below.
  8976. assert(T->isIntegralType(Context) && "Integral type required!");
  8977. const unsigned NumTypes = 4;
  8978. QualType SignedIntegralTypes[NumTypes] = {
  8979. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  8980. };
  8981. QualType UnsignedIntegralTypes[NumTypes] = {
  8982. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  8983. Context.UnsignedLongLongTy
  8984. };
  8985. unsigned BitWidth = Context.getTypeSize(T);
  8986. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  8987. : UnsignedIntegralTypes;
  8988. for (unsigned I = 0; I != NumTypes; ++I)
  8989. if (Context.getTypeSize(Types[I]) > BitWidth)
  8990. return Types[I];
  8991. return QualType();
  8992. }
  8993. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  8994. EnumConstantDecl *LastEnumConst,
  8995. SourceLocation IdLoc,
  8996. IdentifierInfo *Id,
  8997. Expr *Val) {
  8998. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  8999. llvm::APSInt EnumVal(IntWidth);
  9000. QualType EltTy;
  9001. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  9002. Val = 0;
  9003. if (Val)
  9004. Val = DefaultLvalueConversion(Val).take();
  9005. if (Val) {
  9006. if (Enum->isDependentType() || Val->isTypeDependent())
  9007. EltTy = Context.DependentTy;
  9008. else {
  9009. SourceLocation ExpLoc;
  9010. if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
  9011. !getLangOpts().MicrosoftMode) {
  9012. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  9013. // constant-expression in the enumerator-definition shall be a converted
  9014. // constant expression of the underlying type.
  9015. EltTy = Enum->getIntegerType();
  9016. ExprResult Converted =
  9017. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  9018. CCEK_Enumerator);
  9019. if (Converted.isInvalid())
  9020. Val = 0;
  9021. else
  9022. Val = Converted.take();
  9023. } else if (!Val->isValueDependent() &&
  9024. !(Val = VerifyIntegerConstantExpression(Val,
  9025. &EnumVal).take())) {
  9026. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  9027. } else {
  9028. if (Enum->isFixed()) {
  9029. EltTy = Enum->getIntegerType();
  9030. // In Obj-C and Microsoft mode, require the enumeration value to be
  9031. // representable in the underlying type of the enumeration. In C++11,
  9032. // we perform a non-narrowing conversion as part of converted constant
  9033. // expression checking.
  9034. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  9035. if (getLangOpts().MicrosoftMode) {
  9036. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  9037. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  9038. } else
  9039. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  9040. } else
  9041. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
  9042. } else if (getLangOpts().CPlusPlus) {
  9043. // C++11 [dcl.enum]p5:
  9044. // If the underlying type is not fixed, the type of each enumerator
  9045. // is the type of its initializing value:
  9046. // - If an initializer is specified for an enumerator, the
  9047. // initializing value has the same type as the expression.
  9048. EltTy = Val->getType();
  9049. } else {
  9050. // C99 6.7.2.2p2:
  9051. // The expression that defines the value of an enumeration constant
  9052. // shall be an integer constant expression that has a value
  9053. // representable as an int.
  9054. // Complain if the value is not representable in an int.
  9055. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  9056. Diag(IdLoc, diag::ext_enum_value_not_int)
  9057. << EnumVal.toString(10) << Val->getSourceRange()
  9058. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  9059. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  9060. // Force the type of the expression to 'int'.
  9061. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
  9062. }
  9063. EltTy = Val->getType();
  9064. }
  9065. }
  9066. }
  9067. }
  9068. if (!Val) {
  9069. if (Enum->isDependentType())
  9070. EltTy = Context.DependentTy;
  9071. else if (!LastEnumConst) {
  9072. // C++0x [dcl.enum]p5:
  9073. // If the underlying type is not fixed, the type of each enumerator
  9074. // is the type of its initializing value:
  9075. // - If no initializer is specified for the first enumerator, the
  9076. // initializing value has an unspecified integral type.
  9077. //
  9078. // GCC uses 'int' for its unspecified integral type, as does
  9079. // C99 6.7.2.2p3.
  9080. if (Enum->isFixed()) {
  9081. EltTy = Enum->getIntegerType();
  9082. }
  9083. else {
  9084. EltTy = Context.IntTy;
  9085. }
  9086. } else {
  9087. // Assign the last value + 1.
  9088. EnumVal = LastEnumConst->getInitVal();
  9089. ++EnumVal;
  9090. EltTy = LastEnumConst->getType();
  9091. // Check for overflow on increment.
  9092. if (EnumVal < LastEnumConst->getInitVal()) {
  9093. // C++0x [dcl.enum]p5:
  9094. // If the underlying type is not fixed, the type of each enumerator
  9095. // is the type of its initializing value:
  9096. //
  9097. // - Otherwise the type of the initializing value is the same as
  9098. // the type of the initializing value of the preceding enumerator
  9099. // unless the incremented value is not representable in that type,
  9100. // in which case the type is an unspecified integral type
  9101. // sufficient to contain the incremented value. If no such type
  9102. // exists, the program is ill-formed.
  9103. QualType T = getNextLargerIntegralType(Context, EltTy);
  9104. if (T.isNull() || Enum->isFixed()) {
  9105. // There is no integral type larger enough to represent this
  9106. // value. Complain, then allow the value to wrap around.
  9107. EnumVal = LastEnumConst->getInitVal();
  9108. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  9109. ++EnumVal;
  9110. if (Enum->isFixed())
  9111. // When the underlying type is fixed, this is ill-formed.
  9112. Diag(IdLoc, diag::err_enumerator_wrapped)
  9113. << EnumVal.toString(10)
  9114. << EltTy;
  9115. else
  9116. Diag(IdLoc, diag::warn_enumerator_too_large)
  9117. << EnumVal.toString(10);
  9118. } else {
  9119. EltTy = T;
  9120. }
  9121. // Retrieve the last enumerator's value, extent that type to the
  9122. // type that is supposed to be large enough to represent the incremented
  9123. // value, then increment.
  9124. EnumVal = LastEnumConst->getInitVal();
  9125. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  9126. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  9127. ++EnumVal;
  9128. // If we're not in C++, diagnose the overflow of enumerator values,
  9129. // which in C99 means that the enumerator value is not representable in
  9130. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  9131. // permits enumerator values that are representable in some larger
  9132. // integral type.
  9133. if (!getLangOpts().CPlusPlus && !T.isNull())
  9134. Diag(IdLoc, diag::warn_enum_value_overflow);
  9135. } else if (!getLangOpts().CPlusPlus &&
  9136. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  9137. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  9138. Diag(IdLoc, diag::ext_enum_value_not_int)
  9139. << EnumVal.toString(10) << 1;
  9140. }
  9141. }
  9142. }
  9143. if (!EltTy->isDependentType()) {
  9144. // Make the enumerator value match the signedness and size of the
  9145. // enumerator's type.
  9146. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  9147. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  9148. }
  9149. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  9150. Val, EnumVal);
  9151. }
  9152. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  9153. SourceLocation IdLoc, IdentifierInfo *Id,
  9154. AttributeList *Attr,
  9155. SourceLocation EqualLoc, Expr *Val) {
  9156. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  9157. EnumConstantDecl *LastEnumConst =
  9158. cast_or_null<EnumConstantDecl>(lastEnumConst);
  9159. // The scope passed in may not be a decl scope. Zip up the scope tree until
  9160. // we find one that is.
  9161. S = getNonFieldDeclScope(S);
  9162. // Verify that there isn't already something declared with this name in this
  9163. // scope.
  9164. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  9165. ForRedeclaration);
  9166. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  9167. // Maybe we will complain about the shadowed template parameter.
  9168. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  9169. // Just pretend that we didn't see the previous declaration.
  9170. PrevDecl = 0;
  9171. }
  9172. if (PrevDecl) {
  9173. // When in C++, we may get a TagDecl with the same name; in this case the
  9174. // enum constant will 'hide' the tag.
  9175. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  9176. "Received TagDecl when not in C++!");
  9177. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  9178. if (isa<EnumConstantDecl>(PrevDecl))
  9179. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  9180. else
  9181. Diag(IdLoc, diag::err_redefinition) << Id;
  9182. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  9183. return 0;
  9184. }
  9185. }
  9186. // C++ [class.mem]p15:
  9187. // If T is the name of a class, then each of the following shall have a name
  9188. // different from T:
  9189. // - every enumerator of every member of class T that is an unscoped
  9190. // enumerated type
  9191. if (CXXRecordDecl *Record
  9192. = dyn_cast<CXXRecordDecl>(
  9193. TheEnumDecl->getDeclContext()->getRedeclContext()))
  9194. if (!TheEnumDecl->isScoped() &&
  9195. Record->getIdentifier() && Record->getIdentifier() == Id)
  9196. Diag(IdLoc, diag::err_member_name_of_class) << Id;
  9197. EnumConstantDecl *New =
  9198. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  9199. if (New) {
  9200. // Process attributes.
  9201. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  9202. // Register this decl in the current scope stack.
  9203. New->setAccess(TheEnumDecl->getAccess());
  9204. PushOnScopeChains(New, S);
  9205. }
  9206. ActOnDocumentableDecl(New);
  9207. return New;
  9208. }
  9209. // Emits a warning if every element in the enum is the same value and if
  9210. // every element is initialized with a integer or boolean literal.
  9211. static void CheckForUniqueEnumValues(Sema &S, Decl **Elements,
  9212. unsigned NumElements, EnumDecl *Enum,
  9213. QualType EnumType) {
  9214. if (S.Diags.getDiagnosticLevel(diag::warn_identical_enum_values,
  9215. Enum->getLocation()) ==
  9216. DiagnosticsEngine::Ignored)
  9217. return;
  9218. if (NumElements < 2)
  9219. return;
  9220. if (!Enum->getIdentifier())
  9221. return;
  9222. llvm::APSInt FirstVal;
  9223. for (unsigned i = 0; i != NumElements; ++i) {
  9224. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  9225. if (!ECD)
  9226. return;
  9227. Expr *InitExpr = ECD->getInitExpr();
  9228. if (!InitExpr)
  9229. return;
  9230. InitExpr = InitExpr->IgnoreImpCasts();
  9231. if (!isa<IntegerLiteral>(InitExpr) && !isa<CXXBoolLiteralExpr>(InitExpr))
  9232. return;
  9233. if (i == 0) {
  9234. FirstVal = ECD->getInitVal();
  9235. continue;
  9236. }
  9237. if (!llvm::APSInt::isSameValue(FirstVal, ECD->getInitVal()))
  9238. return;
  9239. }
  9240. S.Diag(Enum->getLocation(), diag::warn_identical_enum_values)
  9241. << EnumType << FirstVal.toString(10)
  9242. << Enum->getSourceRange();
  9243. EnumConstantDecl *Last = cast<EnumConstantDecl>(Elements[NumElements - 1]),
  9244. *Next = cast<EnumConstantDecl>(Elements[NumElements - 2]);
  9245. S.Diag(Last->getLocation(), diag::note_identical_enum_values)
  9246. << FixItHint::CreateReplacement(Last->getInitExpr()->getSourceRange(),
  9247. Next->getName());
  9248. }
  9249. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
  9250. SourceLocation RBraceLoc, Decl *EnumDeclX,
  9251. Decl **Elements, unsigned NumElements,
  9252. Scope *S, AttributeList *Attr) {
  9253. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  9254. QualType EnumType = Context.getTypeDeclType(Enum);
  9255. if (Attr)
  9256. ProcessDeclAttributeList(S, Enum, Attr);
  9257. if (Enum->isDependentType()) {
  9258. for (unsigned i = 0; i != NumElements; ++i) {
  9259. EnumConstantDecl *ECD =
  9260. cast_or_null<EnumConstantDecl>(Elements[i]);
  9261. if (!ECD) continue;
  9262. ECD->setType(EnumType);
  9263. }
  9264. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  9265. return;
  9266. }
  9267. // TODO: If the result value doesn't fit in an int, it must be a long or long
  9268. // long value. ISO C does not support this, but GCC does as an extension,
  9269. // emit a warning.
  9270. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  9271. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  9272. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  9273. // Verify that all the values are okay, compute the size of the values, and
  9274. // reverse the list.
  9275. unsigned NumNegativeBits = 0;
  9276. unsigned NumPositiveBits = 0;
  9277. // Keep track of whether all elements have type int.
  9278. bool AllElementsInt = true;
  9279. for (unsigned i = 0; i != NumElements; ++i) {
  9280. EnumConstantDecl *ECD =
  9281. cast_or_null<EnumConstantDecl>(Elements[i]);
  9282. if (!ECD) continue; // Already issued a diagnostic.
  9283. const llvm::APSInt &InitVal = ECD->getInitVal();
  9284. // Keep track of the size of positive and negative values.
  9285. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  9286. NumPositiveBits = std::max(NumPositiveBits,
  9287. (unsigned)InitVal.getActiveBits());
  9288. else
  9289. NumNegativeBits = std::max(NumNegativeBits,
  9290. (unsigned)InitVal.getMinSignedBits());
  9291. // Keep track of whether every enum element has type int (very commmon).
  9292. if (AllElementsInt)
  9293. AllElementsInt = ECD->getType() == Context.IntTy;
  9294. }
  9295. // Figure out the type that should be used for this enum.
  9296. QualType BestType;
  9297. unsigned BestWidth;
  9298. // C++0x N3000 [conv.prom]p3:
  9299. // An rvalue of an unscoped enumeration type whose underlying
  9300. // type is not fixed can be converted to an rvalue of the first
  9301. // of the following types that can represent all the values of
  9302. // the enumeration: int, unsigned int, long int, unsigned long
  9303. // int, long long int, or unsigned long long int.
  9304. // C99 6.4.4.3p2:
  9305. // An identifier declared as an enumeration constant has type int.
  9306. // The C99 rule is modified by a gcc extension
  9307. QualType BestPromotionType;
  9308. bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
  9309. // -fshort-enums is the equivalent to specifying the packed attribute on all
  9310. // enum definitions.
  9311. if (LangOpts.ShortEnums)
  9312. Packed = true;
  9313. if (Enum->isFixed()) {
  9314. BestType = Enum->getIntegerType();
  9315. if (BestType->isPromotableIntegerType())
  9316. BestPromotionType = Context.getPromotedIntegerType(BestType);
  9317. else
  9318. BestPromotionType = BestType;
  9319. // We don't need to set BestWidth, because BestType is going to be the type
  9320. // of the enumerators, but we do anyway because otherwise some compilers
  9321. // warn that it might be used uninitialized.
  9322. BestWidth = CharWidth;
  9323. }
  9324. else if (NumNegativeBits) {
  9325. // If there is a negative value, figure out the smallest integer type (of
  9326. // int/long/longlong) that fits.
  9327. // If it's packed, check also if it fits a char or a short.
  9328. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  9329. BestType = Context.SignedCharTy;
  9330. BestWidth = CharWidth;
  9331. } else if (Packed && NumNegativeBits <= ShortWidth &&
  9332. NumPositiveBits < ShortWidth) {
  9333. BestType = Context.ShortTy;
  9334. BestWidth = ShortWidth;
  9335. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  9336. BestType = Context.IntTy;
  9337. BestWidth = IntWidth;
  9338. } else {
  9339. BestWidth = Context.getTargetInfo().getLongWidth();
  9340. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  9341. BestType = Context.LongTy;
  9342. } else {
  9343. BestWidth = Context.getTargetInfo().getLongLongWidth();
  9344. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  9345. Diag(Enum->getLocation(), diag::warn_enum_too_large);
  9346. BestType = Context.LongLongTy;
  9347. }
  9348. }
  9349. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  9350. } else {
  9351. // If there is no negative value, figure out the smallest type that fits
  9352. // all of the enumerator values.
  9353. // If it's packed, check also if it fits a char or a short.
  9354. if (Packed && NumPositiveBits <= CharWidth) {
  9355. BestType = Context.UnsignedCharTy;
  9356. BestPromotionType = Context.IntTy;
  9357. BestWidth = CharWidth;
  9358. } else if (Packed && NumPositiveBits <= ShortWidth) {
  9359. BestType = Context.UnsignedShortTy;
  9360. BestPromotionType = Context.IntTy;
  9361. BestWidth = ShortWidth;
  9362. } else if (NumPositiveBits <= IntWidth) {
  9363. BestType = Context.UnsignedIntTy;
  9364. BestWidth = IntWidth;
  9365. BestPromotionType
  9366. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9367. ? Context.UnsignedIntTy : Context.IntTy;
  9368. } else if (NumPositiveBits <=
  9369. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  9370. BestType = Context.UnsignedLongTy;
  9371. BestPromotionType
  9372. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9373. ? Context.UnsignedLongTy : Context.LongTy;
  9374. } else {
  9375. BestWidth = Context.getTargetInfo().getLongLongWidth();
  9376. assert(NumPositiveBits <= BestWidth &&
  9377. "How could an initializer get larger than ULL?");
  9378. BestType = Context.UnsignedLongLongTy;
  9379. BestPromotionType
  9380. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  9381. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  9382. }
  9383. }
  9384. // Loop over all of the enumerator constants, changing their types to match
  9385. // the type of the enum if needed.
  9386. for (unsigned i = 0; i != NumElements; ++i) {
  9387. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  9388. if (!ECD) continue; // Already issued a diagnostic.
  9389. // Standard C says the enumerators have int type, but we allow, as an
  9390. // extension, the enumerators to be larger than int size. If each
  9391. // enumerator value fits in an int, type it as an int, otherwise type it the
  9392. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  9393. // that X has type 'int', not 'unsigned'.
  9394. // Determine whether the value fits into an int.
  9395. llvm::APSInt InitVal = ECD->getInitVal();
  9396. // If it fits into an integer type, force it. Otherwise force it to match
  9397. // the enum decl type.
  9398. QualType NewTy;
  9399. unsigned NewWidth;
  9400. bool NewSign;
  9401. if (!getLangOpts().CPlusPlus &&
  9402. !Enum->isFixed() &&
  9403. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  9404. NewTy = Context.IntTy;
  9405. NewWidth = IntWidth;
  9406. NewSign = true;
  9407. } else if (ECD->getType() == BestType) {
  9408. // Already the right type!
  9409. if (getLangOpts().CPlusPlus)
  9410. // C++ [dcl.enum]p4: Following the closing brace of an
  9411. // enum-specifier, each enumerator has the type of its
  9412. // enumeration.
  9413. ECD->setType(EnumType);
  9414. continue;
  9415. } else {
  9416. NewTy = BestType;
  9417. NewWidth = BestWidth;
  9418. NewSign = BestType->isSignedIntegerOrEnumerationType();
  9419. }
  9420. // Adjust the APSInt value.
  9421. InitVal = InitVal.extOrTrunc(NewWidth);
  9422. InitVal.setIsSigned(NewSign);
  9423. ECD->setInitVal(InitVal);
  9424. // Adjust the Expr initializer and type.
  9425. if (ECD->getInitExpr() &&
  9426. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  9427. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  9428. CK_IntegralCast,
  9429. ECD->getInitExpr(),
  9430. /*base paths*/ 0,
  9431. VK_RValue));
  9432. if (getLangOpts().CPlusPlus)
  9433. // C++ [dcl.enum]p4: Following the closing brace of an
  9434. // enum-specifier, each enumerator has the type of its
  9435. // enumeration.
  9436. ECD->setType(EnumType);
  9437. else
  9438. ECD->setType(NewTy);
  9439. }
  9440. Enum->completeDefinition(BestType, BestPromotionType,
  9441. NumPositiveBits, NumNegativeBits);
  9442. // If we're declaring a function, ensure this decl isn't forgotten about -
  9443. // it needs to go into the function scope.
  9444. if (InFunctionDeclarator)
  9445. DeclsInPrototypeScope.push_back(Enum);
  9446. CheckForUniqueEnumValues(*this, Elements, NumElements, Enum, EnumType);
  9447. }
  9448. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  9449. SourceLocation StartLoc,
  9450. SourceLocation EndLoc) {
  9451. StringLiteral *AsmString = cast<StringLiteral>(expr);
  9452. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  9453. AsmString, StartLoc,
  9454. EndLoc);
  9455. CurContext->addDecl(New);
  9456. return New;
  9457. }
  9458. DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
  9459. SourceLocation ImportLoc,
  9460. ModuleIdPath Path) {
  9461. Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
  9462. Module::AllVisible,
  9463. /*IsIncludeDirective=*/false);
  9464. if (!Mod)
  9465. return true;
  9466. llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
  9467. Module *ModCheck = Mod;
  9468. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  9469. // If we've run out of module parents, just drop the remaining identifiers.
  9470. // We need the length to be consistent.
  9471. if (!ModCheck)
  9472. break;
  9473. ModCheck = ModCheck->Parent;
  9474. IdentifierLocs.push_back(Path[I].second);
  9475. }
  9476. ImportDecl *Import = ImportDecl::Create(Context,
  9477. Context.getTranslationUnitDecl(),
  9478. AtLoc.isValid()? AtLoc : ImportLoc,
  9479. Mod, IdentifierLocs);
  9480. Context.getTranslationUnitDecl()->addDecl(Import);
  9481. return Import;
  9482. }
  9483. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  9484. IdentifierInfo* AliasName,
  9485. SourceLocation PragmaLoc,
  9486. SourceLocation NameLoc,
  9487. SourceLocation AliasNameLoc) {
  9488. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  9489. LookupOrdinaryName);
  9490. AsmLabelAttr *Attr =
  9491. ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
  9492. if (PrevDecl)
  9493. PrevDecl->addAttr(Attr);
  9494. else
  9495. (void)ExtnameUndeclaredIdentifiers.insert(
  9496. std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
  9497. }
  9498. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  9499. SourceLocation PragmaLoc,
  9500. SourceLocation NameLoc) {
  9501. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  9502. if (PrevDecl) {
  9503. PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
  9504. } else {
  9505. (void)WeakUndeclaredIdentifiers.insert(
  9506. std::pair<IdentifierInfo*,WeakInfo>
  9507. (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
  9508. }
  9509. }
  9510. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  9511. IdentifierInfo* AliasName,
  9512. SourceLocation PragmaLoc,
  9513. SourceLocation NameLoc,
  9514. SourceLocation AliasNameLoc) {
  9515. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  9516. LookupOrdinaryName);
  9517. WeakInfo W = WeakInfo(Name, NameLoc);
  9518. if (PrevDecl) {
  9519. if (!PrevDecl->hasAttr<AliasAttr>())
  9520. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  9521. DeclApplyPragmaWeak(TUScope, ND, W);
  9522. } else {
  9523. (void)WeakUndeclaredIdentifiers.insert(
  9524. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  9525. }
  9526. }
  9527. Decl *Sema::getObjCDeclContext() const {
  9528. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  9529. }
  9530. AvailabilityResult Sema::getCurContextAvailability() const {
  9531. const Decl *D = cast<Decl>(getCurLexicalContext());
  9532. // A category implicitly has the availability of the interface.
  9533. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
  9534. D = CatD->getClassInterface();
  9535. return D->getAvailability();
  9536. }