SemaDecl.cpp 643 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559
  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 "TypeLocBuilder.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/CommentDiagnostic.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  32. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  33. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using namespace sema;
  51. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  52. if (OwnedType) {
  53. Decl *Group[2] = { OwnedType, Ptr };
  54. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  55. }
  56. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  57. }
  58. namespace {
  59. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  60. public:
  61. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  62. bool AllowTemplates = false,
  63. bool AllowNonTemplates = true)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. if (!AllowInvalidDecl && ND->isInvalidDecl())
  73. return false;
  74. if (getAsTypeTemplateDecl(ND))
  75. return AllowTemplates;
  76. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  77. if (!IsType)
  78. return false;
  79. if (AllowNonTemplates)
  80. return true;
  81. // An injected-class-name of a class template (specialization) is valid
  82. // as a template or as a non-template.
  83. if (AllowTemplates) {
  84. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  85. if (!RD || !RD->isInjectedClassName())
  86. return false;
  87. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  88. return RD->getDescribedClassTemplate() ||
  89. isa<ClassTemplateSpecializationDecl>(RD);
  90. }
  91. return false;
  92. }
  93. return !WantClassName && candidate.isKeyword();
  94. }
  95. private:
  96. bool AllowInvalidDecl;
  97. bool WantClassName;
  98. bool AllowTemplates;
  99. bool AllowNonTemplates;
  100. };
  101. } // end anonymous namespace
  102. /// \brief Determine whether the token kind starts a simple-type-specifier.
  103. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  104. switch (Kind) {
  105. // FIXME: Take into account the current language when deciding whether a
  106. // token kind is a valid type specifier
  107. case tok::kw_short:
  108. case tok::kw_long:
  109. case tok::kw___int64:
  110. case tok::kw___int128:
  111. case tok::kw_signed:
  112. case tok::kw_unsigned:
  113. case tok::kw_void:
  114. case tok::kw_char:
  115. case tok::kw_int:
  116. case tok::kw_half:
  117. case tok::kw_float:
  118. case tok::kw_double:
  119. case tok::kw__Float16:
  120. case tok::kw___float128:
  121. case tok::kw_wchar_t:
  122. case tok::kw_bool:
  123. case tok::kw___underlying_type:
  124. case tok::kw___auto_type:
  125. return true;
  126. case tok::annot_typename:
  127. case tok::kw_char16_t:
  128. case tok::kw_char32_t:
  129. case tok::kw_typeof:
  130. case tok::annot_decltype:
  131. case tok::kw_decltype:
  132. return getLangOpts().CPlusPlus;
  133. default:
  134. break;
  135. }
  136. return false;
  137. }
  138. namespace {
  139. enum class UnqualifiedTypeNameLookupResult {
  140. NotFound,
  141. FoundNonType,
  142. FoundType
  143. };
  144. } // end anonymous namespace
  145. /// \brief Tries to perform unqualified lookup of the type decls in bases for
  146. /// dependent class.
  147. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  148. /// type decl, \a FoundType if only type decls are found.
  149. static UnqualifiedTypeNameLookupResult
  150. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  151. SourceLocation NameLoc,
  152. const CXXRecordDecl *RD) {
  153. if (!RD->hasDefinition())
  154. return UnqualifiedTypeNameLookupResult::NotFound;
  155. // Look for type decls in base classes.
  156. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  157. UnqualifiedTypeNameLookupResult::NotFound;
  158. for (const auto &Base : RD->bases()) {
  159. const CXXRecordDecl *BaseRD = nullptr;
  160. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  161. BaseRD = BaseTT->getAsCXXRecordDecl();
  162. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  163. // Look for type decls in dependent base classes that have known primary
  164. // templates.
  165. if (!TST || !TST->isDependentType())
  166. continue;
  167. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  168. if (!TD)
  169. continue;
  170. if (auto *BasePrimaryTemplate =
  171. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  172. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  173. BaseRD = BasePrimaryTemplate;
  174. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  175. if (const ClassTemplatePartialSpecializationDecl *PS =
  176. CTD->findPartialSpecialization(Base.getType()))
  177. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  178. BaseRD = PS;
  179. }
  180. }
  181. }
  182. if (BaseRD) {
  183. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  184. if (!isa<TypeDecl>(ND))
  185. return UnqualifiedTypeNameLookupResult::FoundNonType;
  186. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  187. }
  188. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  189. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  190. case UnqualifiedTypeNameLookupResult::FoundNonType:
  191. return UnqualifiedTypeNameLookupResult::FoundNonType;
  192. case UnqualifiedTypeNameLookupResult::FoundType:
  193. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  194. break;
  195. case UnqualifiedTypeNameLookupResult::NotFound:
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. return FoundTypeDecl;
  202. }
  203. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  204. const IdentifierInfo &II,
  205. SourceLocation NameLoc) {
  206. // Lookup in the parent class template context, if any.
  207. const CXXRecordDecl *RD = nullptr;
  208. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  209. UnqualifiedTypeNameLookupResult::NotFound;
  210. for (DeclContext *DC = S.CurContext;
  211. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  212. DC = DC->getParent()) {
  213. // Look for type decls in dependent base classes that have known primary
  214. // templates.
  215. RD = dyn_cast<CXXRecordDecl>(DC);
  216. if (RD && RD->getDescribedClassTemplate())
  217. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  218. }
  219. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  220. return nullptr;
  221. // We found some types in dependent base classes. Recover as if the user
  222. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  223. // lookup during template instantiation.
  224. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  225. ASTContext &Context = S.Context;
  226. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  227. cast<Type>(Context.getRecordType(RD)));
  228. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  229. CXXScopeSpec SS;
  230. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  231. TypeLocBuilder Builder;
  232. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  233. DepTL.setNameLoc(NameLoc);
  234. DepTL.setElaboratedKeywordLoc(SourceLocation());
  235. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  236. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  237. }
  238. /// \brief If the identifier refers to a type name within this scope,
  239. /// return the declaration of that type.
  240. ///
  241. /// This routine performs ordinary name lookup of the identifier II
  242. /// within the given scope, with optional C++ scope specifier SS, to
  243. /// determine whether the name refers to a type. If so, returns an
  244. /// opaque pointer (actually a QualType) corresponding to that
  245. /// type. Otherwise, returns NULL.
  246. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  247. Scope *S, CXXScopeSpec *SS,
  248. bool isClassName, bool HasTrailingDot,
  249. ParsedType ObjectTypePtr,
  250. bool IsCtorOrDtorName,
  251. bool WantNontrivialTypeSourceInfo,
  252. bool IsClassTemplateDeductionContext,
  253. IdentifierInfo **CorrectedII) {
  254. // FIXME: Consider allowing this outside C++1z mode as an extension.
  255. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  256. getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
  257. !isClassName && !HasTrailingDot;
  258. // Determine where we will perform name lookup.
  259. DeclContext *LookupCtx = nullptr;
  260. if (ObjectTypePtr) {
  261. QualType ObjectType = ObjectTypePtr.get();
  262. if (ObjectType->isRecordType())
  263. LookupCtx = computeDeclContext(ObjectType);
  264. } else if (SS && SS->isNotEmpty()) {
  265. LookupCtx = computeDeclContext(*SS, false);
  266. if (!LookupCtx) {
  267. if (isDependentScopeSpecifier(*SS)) {
  268. // C++ [temp.res]p3:
  269. // A qualified-id that refers to a type and in which the
  270. // nested-name-specifier depends on a template-parameter (14.6.2)
  271. // shall be prefixed by the keyword typename to indicate that the
  272. // qualified-id denotes a type, forming an
  273. // elaborated-type-specifier (7.1.5.3).
  274. //
  275. // We therefore do not perform any name lookup if the result would
  276. // refer to a member of an unknown specialization.
  277. if (!isClassName && !IsCtorOrDtorName)
  278. return nullptr;
  279. // We know from the grammar that this name refers to a type,
  280. // so build a dependent node to describe the type.
  281. if (WantNontrivialTypeSourceInfo)
  282. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  283. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  284. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  285. II, NameLoc);
  286. return ParsedType::make(T);
  287. }
  288. return nullptr;
  289. }
  290. if (!LookupCtx->isDependentContext() &&
  291. RequireCompleteDeclContext(*SS, LookupCtx))
  292. return nullptr;
  293. }
  294. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  295. // lookup for class-names.
  296. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  297. LookupOrdinaryName;
  298. LookupResult Result(*this, &II, NameLoc, Kind);
  299. if (LookupCtx) {
  300. // Perform "qualified" name lookup into the declaration context we
  301. // computed, which is either the type of the base of a member access
  302. // expression or the declaration context associated with a prior
  303. // nested-name-specifier.
  304. LookupQualifiedName(Result, LookupCtx);
  305. if (ObjectTypePtr && Result.empty()) {
  306. // C++ [basic.lookup.classref]p3:
  307. // If the unqualified-id is ~type-name, the type-name is looked up
  308. // in the context of the entire postfix-expression. If the type T of
  309. // the object expression is of a class type C, the type-name is also
  310. // looked up in the scope of class C. At least one of the lookups shall
  311. // find a name that refers to (possibly cv-qualified) T.
  312. LookupName(Result, S);
  313. }
  314. } else {
  315. // Perform unqualified name lookup.
  316. LookupName(Result, S);
  317. // For unqualified lookup in a class template in MSVC mode, look into
  318. // dependent base classes where the primary class template is known.
  319. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  320. if (ParsedType TypeInBase =
  321. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  322. return TypeInBase;
  323. }
  324. }
  325. NamedDecl *IIDecl = nullptr;
  326. switch (Result.getResultKind()) {
  327. case LookupResult::NotFound:
  328. case LookupResult::NotFoundInCurrentInstantiation:
  329. if (CorrectedII) {
  330. TypoCorrection Correction =
  331. CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
  332. llvm::make_unique<TypeNameValidatorCCC>(
  333. true, isClassName, AllowDeducedTemplate),
  334. CTK_ErrorRecovery);
  335. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  336. TemplateTy Template;
  337. bool MemberOfUnknownSpecialization;
  338. UnqualifiedId TemplateName;
  339. TemplateName.setIdentifier(NewII, NameLoc);
  340. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  341. CXXScopeSpec NewSS, *NewSSPtr = SS;
  342. if (SS && NNS) {
  343. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  344. NewSSPtr = &NewSS;
  345. }
  346. if (Correction && (NNS || NewII != &II) &&
  347. // Ignore a correction to a template type as the to-be-corrected
  348. // identifier is not a template (typo correction for template names
  349. // is handled elsewhere).
  350. !(getLangOpts().CPlusPlus && NewSSPtr &&
  351. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  352. Template, MemberOfUnknownSpecialization))) {
  353. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  354. isClassName, HasTrailingDot, ObjectTypePtr,
  355. IsCtorOrDtorName,
  356. WantNontrivialTypeSourceInfo,
  357. IsClassTemplateDeductionContext);
  358. if (Ty) {
  359. diagnoseTypo(Correction,
  360. PDiag(diag::err_unknown_type_or_class_name_suggest)
  361. << Result.getLookupName() << isClassName);
  362. if (SS && NNS)
  363. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  364. *CorrectedII = NewII;
  365. return Ty;
  366. }
  367. }
  368. }
  369. // If typo correction failed or was not performed, fall through
  370. LLVM_FALLTHROUGH;
  371. case LookupResult::FoundOverloaded:
  372. case LookupResult::FoundUnresolvedValue:
  373. Result.suppressDiagnostics();
  374. return nullptr;
  375. case LookupResult::Ambiguous:
  376. // Recover from type-hiding ambiguities by hiding the type. We'll
  377. // do the lookup again when looking for an object, and we can
  378. // diagnose the error then. If we don't do this, then the error
  379. // about hiding the type will be immediately followed by an error
  380. // that only makes sense if the identifier was treated like a type.
  381. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  382. Result.suppressDiagnostics();
  383. return nullptr;
  384. }
  385. // Look to see if we have a type anywhere in the list of results.
  386. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  387. Res != ResEnd; ++Res) {
  388. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  389. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  390. if (!IIDecl ||
  391. (*Res)->getLocation().getRawEncoding() <
  392. IIDecl->getLocation().getRawEncoding())
  393. IIDecl = *Res;
  394. }
  395. }
  396. if (!IIDecl) {
  397. // None of the entities we found is a type, so there is no way
  398. // to even assume that the result is a type. In this case, don't
  399. // complain about the ambiguity. The parser will either try to
  400. // perform this lookup again (e.g., as an object name), which
  401. // will produce the ambiguity, or will complain that it expected
  402. // a type name.
  403. Result.suppressDiagnostics();
  404. return nullptr;
  405. }
  406. // We found a type within the ambiguous lookup; diagnose the
  407. // ambiguity and then return that type. This might be the right
  408. // answer, or it might not be, but it suppresses any attempt to
  409. // perform the name lookup again.
  410. break;
  411. case LookupResult::Found:
  412. IIDecl = Result.getFoundDecl();
  413. break;
  414. }
  415. assert(IIDecl && "Didn't find decl");
  416. QualType T;
  417. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  418. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  419. // instead names the constructors of the class, except when naming a class.
  420. // This is ill-formed when we're not actually forming a ctor or dtor name.
  421. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  422. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  423. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  424. FoundRD->isInjectedClassName() &&
  425. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  426. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  427. << &II << /*Type*/1;
  428. DiagnoseUseOfDecl(IIDecl, NameLoc);
  429. T = Context.getTypeDeclType(TD);
  430. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  431. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  432. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  433. if (!HasTrailingDot)
  434. T = Context.getObjCInterfaceType(IDecl);
  435. } else if (AllowDeducedTemplate) {
  436. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  437. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  438. QualType(), false);
  439. }
  440. if (T.isNull()) {
  441. // If it's not plausibly a type, suppress diagnostics.
  442. Result.suppressDiagnostics();
  443. return nullptr;
  444. }
  445. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  446. // constructor or destructor name (in such a case, the scope specifier
  447. // will be attached to the enclosing Expr or Decl node).
  448. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  449. !isa<ObjCInterfaceDecl>(IIDecl)) {
  450. if (WantNontrivialTypeSourceInfo) {
  451. // Construct a type with type-source information.
  452. TypeLocBuilder Builder;
  453. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  454. T = getElaboratedType(ETK_None, *SS, T);
  455. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  456. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  457. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  458. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  459. } else {
  460. T = getElaboratedType(ETK_None, *SS, T);
  461. }
  462. }
  463. return ParsedType::make(T);
  464. }
  465. // Builds a fake NNS for the given decl context.
  466. static NestedNameSpecifier *
  467. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  468. for (;; DC = DC->getLookupParent()) {
  469. DC = DC->getPrimaryContext();
  470. auto *ND = dyn_cast<NamespaceDecl>(DC);
  471. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  472. return NestedNameSpecifier::Create(Context, nullptr, ND);
  473. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  474. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  475. RD->getTypeForDecl());
  476. else if (isa<TranslationUnitDecl>(DC))
  477. return NestedNameSpecifier::GlobalSpecifier(Context);
  478. }
  479. llvm_unreachable("something isn't in TU scope?");
  480. }
  481. /// Find the parent class with dependent bases of the innermost enclosing method
  482. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  483. /// up allowing unqualified dependent type names at class-level, which MSVC
  484. /// correctly rejects.
  485. static const CXXRecordDecl *
  486. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  487. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  488. DC = DC->getPrimaryContext();
  489. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  490. if (MD->getParent()->hasAnyDependentBases())
  491. return MD->getParent();
  492. }
  493. return nullptr;
  494. }
  495. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  496. SourceLocation NameLoc,
  497. bool IsTemplateTypeArg) {
  498. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  499. NestedNameSpecifier *NNS = nullptr;
  500. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  501. // If we weren't able to parse a default template argument, delay lookup
  502. // until instantiation time by making a non-dependent DependentTypeName. We
  503. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  504. // lookup is retried.
  505. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  506. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  507. // name specifiers.
  508. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  509. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  510. } else if (const CXXRecordDecl *RD =
  511. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  512. // Build a DependentNameType that will perform lookup into RD at
  513. // instantiation time.
  514. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  515. RD->getTypeForDecl());
  516. // Diagnose that this identifier was undeclared, and retry the lookup during
  517. // template instantiation.
  518. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  519. << RD;
  520. } else {
  521. // This is not a situation that we should recover from.
  522. return ParsedType();
  523. }
  524. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  525. // Build type location information. We synthesized the qualifier, so we have
  526. // to build a fake NestedNameSpecifierLoc.
  527. NestedNameSpecifierLocBuilder NNSLocBuilder;
  528. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  529. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  530. TypeLocBuilder Builder;
  531. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  532. DepTL.setNameLoc(NameLoc);
  533. DepTL.setElaboratedKeywordLoc(SourceLocation());
  534. DepTL.setQualifierLoc(QualifierLoc);
  535. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  536. }
  537. /// isTagName() - This method is called *for error recovery purposes only*
  538. /// to determine if the specified name is a valid tag name ("struct foo"). If
  539. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  540. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  541. /// cases in C where the user forgot to specify the tag.
  542. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  543. // Do a tag name lookup in this scope.
  544. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  545. LookupName(R, S, false);
  546. R.suppressDiagnostics();
  547. if (R.getResultKind() == LookupResult::Found)
  548. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  549. switch (TD->getTagKind()) {
  550. case TTK_Struct: return DeclSpec::TST_struct;
  551. case TTK_Interface: return DeclSpec::TST_interface;
  552. case TTK_Union: return DeclSpec::TST_union;
  553. case TTK_Class: return DeclSpec::TST_class;
  554. case TTK_Enum: return DeclSpec::TST_enum;
  555. }
  556. }
  557. return DeclSpec::TST_unspecified;
  558. }
  559. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  560. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  561. /// then downgrade the missing typename error to a warning.
  562. /// This is needed for MSVC compatibility; Example:
  563. /// @code
  564. /// template<class T> class A {
  565. /// public:
  566. /// typedef int TYPE;
  567. /// };
  568. /// template<class T> class B : public A<T> {
  569. /// public:
  570. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  571. /// };
  572. /// @endcode
  573. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  574. if (CurContext->isRecord()) {
  575. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  576. return true;
  577. const Type *Ty = SS->getScopeRep()->getAsType();
  578. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  579. for (const auto &Base : RD->bases())
  580. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  581. return true;
  582. return S->isFunctionPrototypeScope();
  583. }
  584. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  585. }
  586. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  587. SourceLocation IILoc,
  588. Scope *S,
  589. CXXScopeSpec *SS,
  590. ParsedType &SuggestedType,
  591. bool IsTemplateName) {
  592. // Don't report typename errors for editor placeholders.
  593. if (II->isEditorPlaceholder())
  594. return;
  595. // We don't have anything to suggest (yet).
  596. SuggestedType = nullptr;
  597. // There may have been a typo in the name of the type. Look up typo
  598. // results, in case we have something that we can suggest.
  599. if (TypoCorrection Corrected =
  600. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  601. llvm::make_unique<TypeNameValidatorCCC>(
  602. false, false, IsTemplateName, !IsTemplateName),
  603. CTK_ErrorRecovery)) {
  604. // FIXME: Support error recovery for the template-name case.
  605. bool CanRecover = !IsTemplateName;
  606. if (Corrected.isKeyword()) {
  607. // We corrected to a keyword.
  608. diagnoseTypo(Corrected,
  609. PDiag(IsTemplateName ? diag::err_no_template_suggest
  610. : diag::err_unknown_typename_suggest)
  611. << II);
  612. II = Corrected.getCorrectionAsIdentifierInfo();
  613. } else {
  614. // We found a similarly-named type or interface; suggest that.
  615. if (!SS || !SS->isSet()) {
  616. diagnoseTypo(Corrected,
  617. PDiag(IsTemplateName ? diag::err_no_template_suggest
  618. : diag::err_unknown_typename_suggest)
  619. << II, CanRecover);
  620. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  621. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  622. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  623. II->getName().equals(CorrectedStr);
  624. diagnoseTypo(Corrected,
  625. PDiag(IsTemplateName
  626. ? diag::err_no_member_template_suggest
  627. : diag::err_unknown_nested_typename_suggest)
  628. << II << DC << DroppedSpecifier << SS->getRange(),
  629. CanRecover);
  630. } else {
  631. llvm_unreachable("could not have corrected a typo here");
  632. }
  633. if (!CanRecover)
  634. return;
  635. CXXScopeSpec tmpSS;
  636. if (Corrected.getCorrectionSpecifier())
  637. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  638. SourceRange(IILoc));
  639. // FIXME: Support class template argument deduction here.
  640. SuggestedType =
  641. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  642. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  643. /*IsCtorOrDtorName=*/false,
  644. /*NonTrivialTypeSourceInfo=*/true);
  645. }
  646. return;
  647. }
  648. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  649. // See if II is a class template that the user forgot to pass arguments to.
  650. UnqualifiedId Name;
  651. Name.setIdentifier(II, IILoc);
  652. CXXScopeSpec EmptySS;
  653. TemplateTy TemplateResult;
  654. bool MemberOfUnknownSpecialization;
  655. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  656. Name, nullptr, true, TemplateResult,
  657. MemberOfUnknownSpecialization) == TNK_Type_template) {
  658. TemplateName TplName = TemplateResult.get();
  659. Diag(IILoc, diag::err_template_missing_args)
  660. << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
  661. if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
  662. Diag(TplDecl->getLocation(), diag::note_template_decl_here)
  663. << TplDecl->getTemplateParameters()->getSourceRange();
  664. }
  665. return;
  666. }
  667. }
  668. // FIXME: Should we move the logic that tries to recover from a missing tag
  669. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  670. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  671. Diag(IILoc, IsTemplateName ? diag::err_no_template
  672. : diag::err_unknown_typename)
  673. << II;
  674. else if (DeclContext *DC = computeDeclContext(*SS, false))
  675. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  676. : diag::err_typename_nested_not_found)
  677. << II << DC << SS->getRange();
  678. else if (isDependentScopeSpecifier(*SS)) {
  679. unsigned DiagID = diag::err_typename_missing;
  680. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  681. DiagID = diag::ext_typename_missing;
  682. Diag(SS->getRange().getBegin(), DiagID)
  683. << SS->getScopeRep() << II->getName()
  684. << SourceRange(SS->getRange().getBegin(), IILoc)
  685. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  686. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  687. *SS, *II, IILoc).get();
  688. } else {
  689. assert(SS && SS->isInvalid() &&
  690. "Invalid scope specifier has already been diagnosed");
  691. }
  692. }
  693. /// \brief Determine whether the given result set contains either a type name
  694. /// or
  695. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  696. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  697. NextToken.is(tok::less);
  698. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  699. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  700. return true;
  701. if (CheckTemplate && isa<TemplateDecl>(*I))
  702. return true;
  703. }
  704. return false;
  705. }
  706. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  707. Scope *S, CXXScopeSpec &SS,
  708. IdentifierInfo *&Name,
  709. SourceLocation NameLoc) {
  710. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  711. SemaRef.LookupParsedName(R, S, &SS);
  712. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  713. StringRef FixItTagName;
  714. switch (Tag->getTagKind()) {
  715. case TTK_Class:
  716. FixItTagName = "class ";
  717. break;
  718. case TTK_Enum:
  719. FixItTagName = "enum ";
  720. break;
  721. case TTK_Struct:
  722. FixItTagName = "struct ";
  723. break;
  724. case TTK_Interface:
  725. FixItTagName = "__interface ";
  726. break;
  727. case TTK_Union:
  728. FixItTagName = "union ";
  729. break;
  730. }
  731. StringRef TagName = FixItTagName.drop_back();
  732. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  733. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  734. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  735. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  736. I != IEnd; ++I)
  737. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  738. << Name << TagName;
  739. // Replace lookup results with just the tag decl.
  740. Result.clear(Sema::LookupTagName);
  741. SemaRef.LookupParsedName(Result, S, &SS);
  742. return true;
  743. }
  744. return false;
  745. }
  746. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  747. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  748. QualType T, SourceLocation NameLoc) {
  749. ASTContext &Context = S.Context;
  750. TypeLocBuilder Builder;
  751. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  752. T = S.getElaboratedType(ETK_None, SS, T);
  753. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  754. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  755. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  756. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  757. }
  758. Sema::NameClassification
  759. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  760. SourceLocation NameLoc, const Token &NextToken,
  761. bool IsAddressOfOperand,
  762. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  763. DeclarationNameInfo NameInfo(Name, NameLoc);
  764. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  765. if (NextToken.is(tok::coloncolon)) {
  766. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  767. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  768. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  769. isCurrentClassName(*Name, S, &SS)) {
  770. // Per [class.qual]p2, this names the constructors of SS, not the
  771. // injected-class-name. We don't have a classification for that.
  772. // There's not much point caching this result, since the parser
  773. // will reject it later.
  774. return NameClassification::Unknown();
  775. }
  776. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  777. LookupParsedName(Result, S, &SS, !CurMethod);
  778. // For unqualified lookup in a class template in MSVC mode, look into
  779. // dependent base classes where the primary class template is known.
  780. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  781. if (ParsedType TypeInBase =
  782. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  783. return TypeInBase;
  784. }
  785. // Perform lookup for Objective-C instance variables (including automatically
  786. // synthesized instance variables), if we're in an Objective-C method.
  787. // FIXME: This lookup really, really needs to be folded in to the normal
  788. // unqualified lookup mechanism.
  789. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  790. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  791. if (E.get() || E.isInvalid())
  792. return E;
  793. }
  794. bool SecondTry = false;
  795. bool IsFilteredTemplateName = false;
  796. Corrected:
  797. switch (Result.getResultKind()) {
  798. case LookupResult::NotFound:
  799. // If an unqualified-id is followed by a '(', then we have a function
  800. // call.
  801. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  802. // In C++, this is an ADL-only call.
  803. // FIXME: Reference?
  804. if (getLangOpts().CPlusPlus)
  805. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  806. // C90 6.3.2.2:
  807. // If the expression that precedes the parenthesized argument list in a
  808. // function call consists solely of an identifier, and if no
  809. // declaration is visible for this identifier, the identifier is
  810. // implicitly declared exactly as if, in the innermost block containing
  811. // the function call, the declaration
  812. //
  813. // extern int identifier ();
  814. //
  815. // appeared.
  816. //
  817. // We also allow this in C99 as an extension.
  818. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  819. Result.addDecl(D);
  820. Result.resolveKind();
  821. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  822. }
  823. }
  824. // In C, we first see whether there is a tag type by the same name, in
  825. // which case it's likely that the user just forgot to write "enum",
  826. // "struct", or "union".
  827. if (!getLangOpts().CPlusPlus && !SecondTry &&
  828. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  829. break;
  830. }
  831. // Perform typo correction to determine if there is another name that is
  832. // close to this name.
  833. if (!SecondTry && CCC) {
  834. SecondTry = true;
  835. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  836. Result.getLookupKind(), S,
  837. &SS, std::move(CCC),
  838. CTK_ErrorRecovery)) {
  839. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  840. unsigned QualifiedDiag = diag::err_no_member_suggest;
  841. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  842. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  843. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  844. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  845. UnqualifiedDiag = diag::err_no_template_suggest;
  846. QualifiedDiag = diag::err_no_member_template_suggest;
  847. } else if (UnderlyingFirstDecl &&
  848. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  849. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  850. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  851. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  852. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  853. }
  854. if (SS.isEmpty()) {
  855. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  856. } else {// FIXME: is this even reachable? Test it.
  857. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  858. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  859. Name->getName().equals(CorrectedStr);
  860. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  861. << Name << computeDeclContext(SS, false)
  862. << DroppedSpecifier << SS.getRange());
  863. }
  864. // Update the name, so that the caller has the new name.
  865. Name = Corrected.getCorrectionAsIdentifierInfo();
  866. // Typo correction corrected to a keyword.
  867. if (Corrected.isKeyword())
  868. return Name;
  869. // Also update the LookupResult...
  870. // FIXME: This should probably go away at some point
  871. Result.clear();
  872. Result.setLookupName(Corrected.getCorrection());
  873. if (FirstDecl)
  874. Result.addDecl(FirstDecl);
  875. // If we found an Objective-C instance variable, let
  876. // LookupInObjCMethod build the appropriate expression to
  877. // reference the ivar.
  878. // FIXME: This is a gross hack.
  879. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  880. Result.clear();
  881. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  882. return E;
  883. }
  884. goto Corrected;
  885. }
  886. }
  887. // We failed to correct; just fall through and let the parser deal with it.
  888. Result.suppressDiagnostics();
  889. return NameClassification::Unknown();
  890. case LookupResult::NotFoundInCurrentInstantiation: {
  891. // We performed name lookup into the current instantiation, and there were
  892. // dependent bases, so we treat this result the same way as any other
  893. // dependent nested-name-specifier.
  894. // C++ [temp.res]p2:
  895. // A name used in a template declaration or definition and that is
  896. // dependent on a template-parameter is assumed not to name a type
  897. // unless the applicable name lookup finds a type name or the name is
  898. // qualified by the keyword typename.
  899. //
  900. // FIXME: If the next token is '<', we might want to ask the parser to
  901. // perform some heroics to see if we actually have a
  902. // template-argument-list, which would indicate a missing 'template'
  903. // keyword here.
  904. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  905. NameInfo, IsAddressOfOperand,
  906. /*TemplateArgs=*/nullptr);
  907. }
  908. case LookupResult::Found:
  909. case LookupResult::FoundOverloaded:
  910. case LookupResult::FoundUnresolvedValue:
  911. break;
  912. case LookupResult::Ambiguous:
  913. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  914. hasAnyAcceptableTemplateNames(Result)) {
  915. // C++ [temp.local]p3:
  916. // A lookup that finds an injected-class-name (10.2) can result in an
  917. // ambiguity in certain cases (for example, if it is found in more than
  918. // one base class). If all of the injected-class-names that are found
  919. // refer to specializations of the same class template, and if the name
  920. // is followed by a template-argument-list, the reference refers to the
  921. // class template itself and not a specialization thereof, and is not
  922. // ambiguous.
  923. //
  924. // This filtering can make an ambiguous result into an unambiguous one,
  925. // so try again after filtering out template names.
  926. FilterAcceptableTemplateNames(Result);
  927. if (!Result.isAmbiguous()) {
  928. IsFilteredTemplateName = true;
  929. break;
  930. }
  931. }
  932. // Diagnose the ambiguity and return an error.
  933. return NameClassification::Error();
  934. }
  935. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  936. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  937. // C++ [temp.names]p3:
  938. // After name lookup (3.4) finds that a name is a template-name or that
  939. // an operator-function-id or a literal- operator-id refers to a set of
  940. // overloaded functions any member of which is a function template if
  941. // this is followed by a <, the < is always taken as the delimiter of a
  942. // template-argument-list and never as the less-than operator.
  943. if (!IsFilteredTemplateName)
  944. FilterAcceptableTemplateNames(Result);
  945. if (!Result.empty()) {
  946. bool IsFunctionTemplate;
  947. bool IsVarTemplate;
  948. TemplateName Template;
  949. if (Result.end() - Result.begin() > 1) {
  950. IsFunctionTemplate = true;
  951. Template = Context.getOverloadedTemplateName(Result.begin(),
  952. Result.end());
  953. } else {
  954. TemplateDecl *TD
  955. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  956. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  957. IsVarTemplate = isa<VarTemplateDecl>(TD);
  958. if (SS.isSet() && !SS.isInvalid())
  959. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  960. /*TemplateKeyword=*/false,
  961. TD);
  962. else
  963. Template = TemplateName(TD);
  964. }
  965. if (IsFunctionTemplate) {
  966. // Function templates always go through overload resolution, at which
  967. // point we'll perform the various checks (e.g., accessibility) we need
  968. // to based on which function we selected.
  969. Result.suppressDiagnostics();
  970. return NameClassification::FunctionTemplate(Template);
  971. }
  972. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  973. : NameClassification::TypeTemplate(Template);
  974. }
  975. }
  976. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  977. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  978. DiagnoseUseOfDecl(Type, NameLoc);
  979. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  980. QualType T = Context.getTypeDeclType(Type);
  981. if (SS.isNotEmpty())
  982. return buildNestedType(*this, SS, T, NameLoc);
  983. return ParsedType::make(T);
  984. }
  985. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  986. if (!Class) {
  987. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  988. if (ObjCCompatibleAliasDecl *Alias =
  989. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  990. Class = Alias->getClassInterface();
  991. }
  992. if (Class) {
  993. DiagnoseUseOfDecl(Class, NameLoc);
  994. if (NextToken.is(tok::period)) {
  995. // Interface. <something> is parsed as a property reference expression.
  996. // Just return "unknown" as a fall-through for now.
  997. Result.suppressDiagnostics();
  998. return NameClassification::Unknown();
  999. }
  1000. QualType T = Context.getObjCInterfaceType(Class);
  1001. return ParsedType::make(T);
  1002. }
  1003. // We can have a type template here if we're classifying a template argument.
  1004. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1005. !isa<VarTemplateDecl>(FirstDecl))
  1006. return NameClassification::TypeTemplate(
  1007. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1008. // Check for a tag type hidden by a non-type decl in a few cases where it
  1009. // seems likely a type is wanted instead of the non-type that was found.
  1010. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1011. if ((NextToken.is(tok::identifier) ||
  1012. (NextIsOp &&
  1013. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1014. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1015. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1016. DiagnoseUseOfDecl(Type, NameLoc);
  1017. QualType T = Context.getTypeDeclType(Type);
  1018. if (SS.isNotEmpty())
  1019. return buildNestedType(*this, SS, T, NameLoc);
  1020. return ParsedType::make(T);
  1021. }
  1022. if (FirstDecl->isCXXClassMember())
  1023. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1024. nullptr, S);
  1025. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1026. return BuildDeclarationNameExpr(SS, Result, ADL);
  1027. }
  1028. Sema::TemplateNameKindForDiagnostics
  1029. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1030. auto *TD = Name.getAsTemplateDecl();
  1031. if (!TD)
  1032. return TemplateNameKindForDiagnostics::DependentTemplate;
  1033. if (isa<ClassTemplateDecl>(TD))
  1034. return TemplateNameKindForDiagnostics::ClassTemplate;
  1035. if (isa<FunctionTemplateDecl>(TD))
  1036. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1037. if (isa<VarTemplateDecl>(TD))
  1038. return TemplateNameKindForDiagnostics::VarTemplate;
  1039. if (isa<TypeAliasTemplateDecl>(TD))
  1040. return TemplateNameKindForDiagnostics::AliasTemplate;
  1041. if (isa<TemplateTemplateParmDecl>(TD))
  1042. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1043. return TemplateNameKindForDiagnostics::DependentTemplate;
  1044. }
  1045. // Determines the context to return to after temporarily entering a
  1046. // context. This depends in an unnecessarily complicated way on the
  1047. // exact ordering of callbacks from the parser.
  1048. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1049. // Functions defined inline within classes aren't parsed until we've
  1050. // finished parsing the top-level class, so the top-level class is
  1051. // the context we'll need to return to.
  1052. // A Lambda call operator whose parent is a class must not be treated
  1053. // as an inline member function. A Lambda can be used legally
  1054. // either as an in-class member initializer or a default argument. These
  1055. // are parsed once the class has been marked complete and so the containing
  1056. // context would be the nested class (when the lambda is defined in one);
  1057. // If the class is not complete, then the lambda is being used in an
  1058. // ill-formed fashion (such as to specify the width of a bit-field, or
  1059. // in an array-bound) - in which case we still want to return the
  1060. // lexically containing DC (which could be a nested class).
  1061. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1062. DC = DC->getLexicalParent();
  1063. // A function not defined within a class will always return to its
  1064. // lexical context.
  1065. if (!isa<CXXRecordDecl>(DC))
  1066. return DC;
  1067. // A C++ inline method/friend is parsed *after* the topmost class
  1068. // it was declared in is fully parsed ("complete"); the topmost
  1069. // class is the context we need to return to.
  1070. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1071. DC = RD;
  1072. // Return the declaration context of the topmost class the inline method is
  1073. // declared in.
  1074. return DC;
  1075. }
  1076. return DC->getLexicalParent();
  1077. }
  1078. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1079. assert(getContainingDC(DC) == CurContext &&
  1080. "The next DeclContext should be lexically contained in the current one.");
  1081. CurContext = DC;
  1082. S->setEntity(DC);
  1083. }
  1084. void Sema::PopDeclContext() {
  1085. assert(CurContext && "DeclContext imbalance!");
  1086. CurContext = getContainingDC(CurContext);
  1087. assert(CurContext && "Popped translation unit!");
  1088. }
  1089. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1090. Decl *D) {
  1091. // Unlike PushDeclContext, the context to which we return is not necessarily
  1092. // the containing DC of TD, because the new context will be some pre-existing
  1093. // TagDecl definition instead of a fresh one.
  1094. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1095. CurContext = cast<TagDecl>(D)->getDefinition();
  1096. assert(CurContext && "skipping definition of undefined tag");
  1097. // Start lookups from the parent of the current context; we don't want to look
  1098. // into the pre-existing complete definition.
  1099. S->setEntity(CurContext->getLookupParent());
  1100. return Result;
  1101. }
  1102. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1103. CurContext = static_cast<decltype(CurContext)>(Context);
  1104. }
  1105. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1106. /// of a declarator's nested name specifier.
  1107. ///
  1108. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1109. // C++0x [basic.lookup.unqual]p13:
  1110. // A name used in the definition of a static data member of class
  1111. // X (after the qualified-id of the static member) is looked up as
  1112. // if the name was used in a member function of X.
  1113. // C++0x [basic.lookup.unqual]p14:
  1114. // If a variable member of a namespace is defined outside of the
  1115. // scope of its namespace then any name used in the definition of
  1116. // the variable member (after the declarator-id) is looked up as
  1117. // if the definition of the variable member occurred in its
  1118. // namespace.
  1119. // Both of these imply that we should push a scope whose context
  1120. // is the semantic context of the declaration. We can't use
  1121. // PushDeclContext here because that context is not necessarily
  1122. // lexically contained in the current context. Fortunately,
  1123. // the containing scope should have the appropriate information.
  1124. assert(!S->getEntity() && "scope already has entity");
  1125. #ifndef NDEBUG
  1126. Scope *Ancestor = S->getParent();
  1127. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1128. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1129. #endif
  1130. CurContext = DC;
  1131. S->setEntity(DC);
  1132. }
  1133. void Sema::ExitDeclaratorContext(Scope *S) {
  1134. assert(S->getEntity() == CurContext && "Context imbalance!");
  1135. // Switch back to the lexical context. The safety of this is
  1136. // enforced by an assert in EnterDeclaratorContext.
  1137. Scope *Ancestor = S->getParent();
  1138. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1139. CurContext = Ancestor->getEntity();
  1140. // We don't need to do anything with the scope, which is going to
  1141. // disappear.
  1142. }
  1143. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1144. // We assume that the caller has already called
  1145. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1146. FunctionDecl *FD = D->getAsFunction();
  1147. if (!FD)
  1148. return;
  1149. // Same implementation as PushDeclContext, but enters the context
  1150. // from the lexical parent, rather than the top-level class.
  1151. assert(CurContext == FD->getLexicalParent() &&
  1152. "The next DeclContext should be lexically contained in the current one.");
  1153. CurContext = FD;
  1154. S->setEntity(CurContext);
  1155. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1156. ParmVarDecl *Param = FD->getParamDecl(P);
  1157. // If the parameter has an identifier, then add it to the scope
  1158. if (Param->getIdentifier()) {
  1159. S->AddDecl(Param);
  1160. IdResolver.AddDecl(Param);
  1161. }
  1162. }
  1163. }
  1164. void Sema::ActOnExitFunctionContext() {
  1165. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1166. // rather than the top-level class.
  1167. assert(CurContext && "DeclContext imbalance!");
  1168. CurContext = CurContext->getLexicalParent();
  1169. assert(CurContext && "Popped translation unit!");
  1170. }
  1171. /// \brief Determine whether we allow overloading of the function
  1172. /// PrevDecl with another declaration.
  1173. ///
  1174. /// This routine determines whether overloading is possible, not
  1175. /// whether some new function is actually an overload. It will return
  1176. /// true in C++ (where we can always provide overloads) or, as an
  1177. /// extension, in C when the previous function is already an
  1178. /// overloaded function declaration or has the "overloadable"
  1179. /// attribute.
  1180. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1181. ASTContext &Context,
  1182. const FunctionDecl *New) {
  1183. if (Context.getLangOpts().CPlusPlus)
  1184. return true;
  1185. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1186. return true;
  1187. return Previous.getResultKind() == LookupResult::Found &&
  1188. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1189. New->hasAttr<OverloadableAttr>());
  1190. }
  1191. /// Add this decl to the scope shadowed decl chains.
  1192. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1193. // Move up the scope chain until we find the nearest enclosing
  1194. // non-transparent context. The declaration will be introduced into this
  1195. // scope.
  1196. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1197. S = S->getParent();
  1198. // Add scoped declarations into their context, so that they can be
  1199. // found later. Declarations without a context won't be inserted
  1200. // into any context.
  1201. if (AddToContext)
  1202. CurContext->addDecl(D);
  1203. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1204. // are function-local declarations.
  1205. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1206. !D->getDeclContext()->getRedeclContext()->Equals(
  1207. D->getLexicalDeclContext()->getRedeclContext()) &&
  1208. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1209. return;
  1210. // Template instantiations should also not be pushed into scope.
  1211. if (isa<FunctionDecl>(D) &&
  1212. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1213. return;
  1214. // If this replaces anything in the current scope,
  1215. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1216. IEnd = IdResolver.end();
  1217. for (; I != IEnd; ++I) {
  1218. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1219. S->RemoveDecl(*I);
  1220. IdResolver.RemoveDecl(*I);
  1221. // Should only need to replace one decl.
  1222. break;
  1223. }
  1224. }
  1225. S->AddDecl(D);
  1226. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1227. // Implicitly-generated labels may end up getting generated in an order that
  1228. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1229. // the label at the appropriate place in the identifier chain.
  1230. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1231. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1232. if (IDC == CurContext) {
  1233. if (!S->isDeclScope(*I))
  1234. continue;
  1235. } else if (IDC->Encloses(CurContext))
  1236. break;
  1237. }
  1238. IdResolver.InsertDeclAfter(I, D);
  1239. } else {
  1240. IdResolver.AddDecl(D);
  1241. }
  1242. }
  1243. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1244. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1245. TUScope->AddDecl(D);
  1246. }
  1247. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1248. bool AllowInlineNamespace) {
  1249. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1250. }
  1251. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1252. DeclContext *TargetDC = DC->getPrimaryContext();
  1253. do {
  1254. if (DeclContext *ScopeDC = S->getEntity())
  1255. if (ScopeDC->getPrimaryContext() == TargetDC)
  1256. return S;
  1257. } while ((S = S->getParent()));
  1258. return nullptr;
  1259. }
  1260. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1261. DeclContext*,
  1262. ASTContext&);
  1263. /// Filters out lookup results that don't fall within the given scope
  1264. /// as determined by isDeclInScope.
  1265. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1266. bool ConsiderLinkage,
  1267. bool AllowInlineNamespace) {
  1268. LookupResult::Filter F = R.makeFilter();
  1269. while (F.hasNext()) {
  1270. NamedDecl *D = F.next();
  1271. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1272. continue;
  1273. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1274. continue;
  1275. F.erase();
  1276. }
  1277. F.done();
  1278. }
  1279. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1280. /// have compatible owning modules.
  1281. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1282. // FIXME: The Modules TS is not clear about how friend declarations are
  1283. // to be treated. It's not meaningful to have different owning modules for
  1284. // linkage in redeclarations of the same entity, so for now allow the
  1285. // redeclaration and change the owning modules to match.
  1286. if (New->getFriendObjectKind() &&
  1287. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1288. New->setLocalOwningModule(Old->getOwningModule());
  1289. makeMergedDefinitionVisible(New);
  1290. return false;
  1291. }
  1292. Module *NewM = New->getOwningModule();
  1293. Module *OldM = Old->getOwningModule();
  1294. if (NewM == OldM)
  1295. return false;
  1296. // FIXME: Check proclaimed-ownership-declarations here too.
  1297. bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
  1298. bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
  1299. if (NewIsModuleInterface || OldIsModuleInterface) {
  1300. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1301. // if a declaration of D [...] appears in the purview of a module, all
  1302. // other such declarations shall appear in the purview of the same module
  1303. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1304. << New
  1305. << NewIsModuleInterface
  1306. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1307. << OldIsModuleInterface
  1308. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1309. Diag(Old->getLocation(), diag::note_previous_declaration);
  1310. New->setInvalidDecl();
  1311. return true;
  1312. }
  1313. return false;
  1314. }
  1315. static bool isUsingDecl(NamedDecl *D) {
  1316. return isa<UsingShadowDecl>(D) ||
  1317. isa<UnresolvedUsingTypenameDecl>(D) ||
  1318. isa<UnresolvedUsingValueDecl>(D);
  1319. }
  1320. /// Removes using shadow declarations from the lookup results.
  1321. static void RemoveUsingDecls(LookupResult &R) {
  1322. LookupResult::Filter F = R.makeFilter();
  1323. while (F.hasNext())
  1324. if (isUsingDecl(F.next()))
  1325. F.erase();
  1326. F.done();
  1327. }
  1328. /// \brief Check for this common pattern:
  1329. /// @code
  1330. /// class S {
  1331. /// S(const S&); // DO NOT IMPLEMENT
  1332. /// void operator=(const S&); // DO NOT IMPLEMENT
  1333. /// };
  1334. /// @endcode
  1335. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1336. // FIXME: Should check for private access too but access is set after we get
  1337. // the decl here.
  1338. if (D->doesThisDeclarationHaveABody())
  1339. return false;
  1340. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1341. return CD->isCopyConstructor();
  1342. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1343. return Method->isCopyAssignmentOperator();
  1344. return false;
  1345. }
  1346. // We need this to handle
  1347. //
  1348. // typedef struct {
  1349. // void *foo() { return 0; }
  1350. // } A;
  1351. //
  1352. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1353. // for example. If 'A', foo will have external linkage. If we have '*A',
  1354. // foo will have no linkage. Since we can't know until we get to the end
  1355. // of the typedef, this function finds out if D might have non-external linkage.
  1356. // Callers should verify at the end of the TU if it D has external linkage or
  1357. // not.
  1358. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1359. const DeclContext *DC = D->getDeclContext();
  1360. while (!DC->isTranslationUnit()) {
  1361. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1362. if (!RD->hasNameForLinkage())
  1363. return true;
  1364. }
  1365. DC = DC->getParent();
  1366. }
  1367. return !D->isExternallyVisible();
  1368. }
  1369. // FIXME: This needs to be refactored; some other isInMainFile users want
  1370. // these semantics.
  1371. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1372. if (S.TUKind != TU_Complete)
  1373. return false;
  1374. return S.SourceMgr.isInMainFile(Loc);
  1375. }
  1376. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1377. assert(D);
  1378. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1379. return false;
  1380. // Ignore all entities declared within templates, and out-of-line definitions
  1381. // of members of class templates.
  1382. if (D->getDeclContext()->isDependentContext() ||
  1383. D->getLexicalDeclContext()->isDependentContext())
  1384. return false;
  1385. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1386. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1387. return false;
  1388. // A non-out-of-line declaration of a member specialization was implicitly
  1389. // instantiated; it's the out-of-line declaration that we're interested in.
  1390. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1391. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1392. return false;
  1393. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1394. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1395. return false;
  1396. } else {
  1397. // 'static inline' functions are defined in headers; don't warn.
  1398. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1399. return false;
  1400. }
  1401. if (FD->doesThisDeclarationHaveABody() &&
  1402. Context.DeclMustBeEmitted(FD))
  1403. return false;
  1404. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1405. // Constants and utility variables are defined in headers with internal
  1406. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1407. // like "inline".)
  1408. if (!isMainFileLoc(*this, VD->getLocation()))
  1409. return false;
  1410. if (Context.DeclMustBeEmitted(VD))
  1411. return false;
  1412. if (VD->isStaticDataMember() &&
  1413. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1414. return false;
  1415. if (VD->isStaticDataMember() &&
  1416. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1417. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1418. return false;
  1419. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1420. return false;
  1421. } else {
  1422. return false;
  1423. }
  1424. // Only warn for unused decls internal to the translation unit.
  1425. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1426. // for inline functions defined in the main source file, for instance.
  1427. return mightHaveNonExternalLinkage(D);
  1428. }
  1429. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1430. if (!D)
  1431. return;
  1432. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1433. const FunctionDecl *First = FD->getFirstDecl();
  1434. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1435. return; // First should already be in the vector.
  1436. }
  1437. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1438. const VarDecl *First = VD->getFirstDecl();
  1439. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1440. return; // First should already be in the vector.
  1441. }
  1442. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1443. UnusedFileScopedDecls.push_back(D);
  1444. }
  1445. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1446. if (D->isInvalidDecl())
  1447. return false;
  1448. bool Referenced = false;
  1449. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1450. // For a decomposition declaration, warn if none of the bindings are
  1451. // referenced, instead of if the variable itself is referenced (which
  1452. // it is, by the bindings' expressions).
  1453. for (auto *BD : DD->bindings()) {
  1454. if (BD->isReferenced()) {
  1455. Referenced = true;
  1456. break;
  1457. }
  1458. }
  1459. } else if (!D->getDeclName()) {
  1460. return false;
  1461. } else if (D->isReferenced() || D->isUsed()) {
  1462. Referenced = true;
  1463. }
  1464. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1465. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1466. return false;
  1467. if (isa<LabelDecl>(D))
  1468. return true;
  1469. // Except for labels, we only care about unused decls that are local to
  1470. // functions.
  1471. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1472. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1473. // For dependent types, the diagnostic is deferred.
  1474. WithinFunction =
  1475. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1476. if (!WithinFunction)
  1477. return false;
  1478. if (isa<TypedefNameDecl>(D))
  1479. return true;
  1480. // White-list anything that isn't a local variable.
  1481. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1482. return false;
  1483. // Types of valid local variables should be complete, so this should succeed.
  1484. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1485. // White-list anything with an __attribute__((unused)) type.
  1486. const auto *Ty = VD->getType().getTypePtr();
  1487. // Only look at the outermost level of typedef.
  1488. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1489. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1490. return false;
  1491. }
  1492. // If we failed to complete the type for some reason, or if the type is
  1493. // dependent, don't diagnose the variable.
  1494. if (Ty->isIncompleteType() || Ty->isDependentType())
  1495. return false;
  1496. // Look at the element type to ensure that the warning behaviour is
  1497. // consistent for both scalars and arrays.
  1498. Ty = Ty->getBaseElementTypeUnsafe();
  1499. if (const TagType *TT = Ty->getAs<TagType>()) {
  1500. const TagDecl *Tag = TT->getDecl();
  1501. if (Tag->hasAttr<UnusedAttr>())
  1502. return false;
  1503. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1504. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1505. return false;
  1506. if (const Expr *Init = VD->getInit()) {
  1507. if (const ExprWithCleanups *Cleanups =
  1508. dyn_cast<ExprWithCleanups>(Init))
  1509. Init = Cleanups->getSubExpr();
  1510. const CXXConstructExpr *Construct =
  1511. dyn_cast<CXXConstructExpr>(Init);
  1512. if (Construct && !Construct->isElidable()) {
  1513. CXXConstructorDecl *CD = Construct->getConstructor();
  1514. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1515. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1516. return false;
  1517. }
  1518. }
  1519. }
  1520. }
  1521. // TODO: __attribute__((unused)) templates?
  1522. }
  1523. return true;
  1524. }
  1525. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1526. FixItHint &Hint) {
  1527. if (isa<LabelDecl>(D)) {
  1528. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1529. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1530. if (AfterColon.isInvalid())
  1531. return;
  1532. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1533. getCharRange(D->getLocStart(), AfterColon));
  1534. }
  1535. }
  1536. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1537. if (D->getTypeForDecl()->isDependentType())
  1538. return;
  1539. for (auto *TmpD : D->decls()) {
  1540. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1541. DiagnoseUnusedDecl(T);
  1542. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1543. DiagnoseUnusedNestedTypedefs(R);
  1544. }
  1545. }
  1546. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1547. /// unless they are marked attr(unused).
  1548. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1549. if (!ShouldDiagnoseUnusedDecl(D))
  1550. return;
  1551. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1552. // typedefs can be referenced later on, so the diagnostics are emitted
  1553. // at end-of-translation-unit.
  1554. UnusedLocalTypedefNameCandidates.insert(TD);
  1555. return;
  1556. }
  1557. FixItHint Hint;
  1558. GenerateFixForUnusedDecl(D, Context, Hint);
  1559. unsigned DiagID;
  1560. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1561. DiagID = diag::warn_unused_exception_param;
  1562. else if (isa<LabelDecl>(D))
  1563. DiagID = diag::warn_unused_label;
  1564. else
  1565. DiagID = diag::warn_unused_variable;
  1566. Diag(D->getLocation(), DiagID) << D << Hint;
  1567. }
  1568. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1569. // Verify that we have no forward references left. If so, there was a goto
  1570. // or address of a label taken, but no definition of it. Label fwd
  1571. // definitions are indicated with a null substmt which is also not a resolved
  1572. // MS inline assembly label name.
  1573. bool Diagnose = false;
  1574. if (L->isMSAsmLabel())
  1575. Diagnose = !L->isResolvedMSAsmLabel();
  1576. else
  1577. Diagnose = L->getStmt() == nullptr;
  1578. if (Diagnose)
  1579. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1580. }
  1581. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1582. S->mergeNRVOIntoParent();
  1583. if (S->decl_empty()) return;
  1584. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1585. "Scope shouldn't contain decls!");
  1586. for (auto *TmpD : S->decls()) {
  1587. assert(TmpD && "This decl didn't get pushed??");
  1588. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1589. NamedDecl *D = cast<NamedDecl>(TmpD);
  1590. // Diagnose unused variables in this scope.
  1591. if (!S->hasUnrecoverableErrorOccurred()) {
  1592. DiagnoseUnusedDecl(D);
  1593. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1594. DiagnoseUnusedNestedTypedefs(RD);
  1595. }
  1596. if (!D->getDeclName()) continue;
  1597. // If this was a forward reference to a label, verify it was defined.
  1598. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1599. CheckPoppedLabel(LD, *this);
  1600. // Remove this name from our lexical scope, and warn on it if we haven't
  1601. // already.
  1602. IdResolver.RemoveDecl(D);
  1603. auto ShadowI = ShadowingDecls.find(D);
  1604. if (ShadowI != ShadowingDecls.end()) {
  1605. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1606. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1607. << D << FD << FD->getParent();
  1608. Diag(FD->getLocation(), diag::note_previous_declaration);
  1609. }
  1610. ShadowingDecls.erase(ShadowI);
  1611. }
  1612. }
  1613. }
  1614. /// \brief Look for an Objective-C class in the translation unit.
  1615. ///
  1616. /// \param Id The name of the Objective-C class we're looking for. If
  1617. /// typo-correction fixes this name, the Id will be updated
  1618. /// to the fixed name.
  1619. ///
  1620. /// \param IdLoc The location of the name in the translation unit.
  1621. ///
  1622. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1623. /// if there is no class with the given name.
  1624. ///
  1625. /// \returns The declaration of the named Objective-C class, or NULL if the
  1626. /// class could not be found.
  1627. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1628. SourceLocation IdLoc,
  1629. bool DoTypoCorrection) {
  1630. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1631. // creation from this context.
  1632. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1633. if (!IDecl && DoTypoCorrection) {
  1634. // Perform typo correction at the given location, but only if we
  1635. // find an Objective-C class name.
  1636. if (TypoCorrection C = CorrectTypo(
  1637. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1638. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1639. CTK_ErrorRecovery)) {
  1640. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1641. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1642. Id = IDecl->getIdentifier();
  1643. }
  1644. }
  1645. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1646. // This routine must always return a class definition, if any.
  1647. if (Def && Def->getDefinition())
  1648. Def = Def->getDefinition();
  1649. return Def;
  1650. }
  1651. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1652. /// from S, where a non-field would be declared. This routine copes
  1653. /// with the difference between C and C++ scoping rules in structs and
  1654. /// unions. For example, the following code is well-formed in C but
  1655. /// ill-formed in C++:
  1656. /// @code
  1657. /// struct S6 {
  1658. /// enum { BAR } e;
  1659. /// };
  1660. ///
  1661. /// void test_S6() {
  1662. /// struct S6 a;
  1663. /// a.e = BAR;
  1664. /// }
  1665. /// @endcode
  1666. /// For the declaration of BAR, this routine will return a different
  1667. /// scope. The scope S will be the scope of the unnamed enumeration
  1668. /// within S6. In C++, this routine will return the scope associated
  1669. /// with S6, because the enumeration's scope is a transparent
  1670. /// context but structures can contain non-field names. In C, this
  1671. /// routine will return the translation unit scope, since the
  1672. /// enumeration's scope is a transparent context and structures cannot
  1673. /// contain non-field names.
  1674. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1675. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1676. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1677. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1678. S = S->getParent();
  1679. return S;
  1680. }
  1681. /// \brief Looks up the declaration of "struct objc_super" and
  1682. /// saves it for later use in building builtin declaration of
  1683. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1684. /// pre-existing declaration exists no action takes place.
  1685. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1686. IdentifierInfo *II) {
  1687. if (!II->isStr("objc_msgSendSuper"))
  1688. return;
  1689. ASTContext &Context = ThisSema.Context;
  1690. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1691. SourceLocation(), Sema::LookupTagName);
  1692. ThisSema.LookupName(Result, S);
  1693. if (Result.getResultKind() == LookupResult::Found)
  1694. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1695. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1696. }
  1697. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1698. switch (Error) {
  1699. case ASTContext::GE_None:
  1700. return "";
  1701. case ASTContext::GE_Missing_stdio:
  1702. return "stdio.h";
  1703. case ASTContext::GE_Missing_setjmp:
  1704. return "setjmp.h";
  1705. case ASTContext::GE_Missing_ucontext:
  1706. return "ucontext.h";
  1707. }
  1708. llvm_unreachable("unhandled error kind");
  1709. }
  1710. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1711. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1712. /// if we're creating this built-in in anticipation of redeclaring the
  1713. /// built-in.
  1714. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1715. Scope *S, bool ForRedeclaration,
  1716. SourceLocation Loc) {
  1717. LookupPredefedObjCSuperType(*this, S, II);
  1718. ASTContext::GetBuiltinTypeError Error;
  1719. QualType R = Context.GetBuiltinType(ID, Error);
  1720. if (Error) {
  1721. if (ForRedeclaration)
  1722. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1723. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1724. return nullptr;
  1725. }
  1726. if (!ForRedeclaration &&
  1727. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1728. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1729. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1730. << Context.BuiltinInfo.getName(ID) << R;
  1731. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1732. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1733. Diag(Loc, diag::note_include_header_or_declare)
  1734. << Context.BuiltinInfo.getHeaderName(ID)
  1735. << Context.BuiltinInfo.getName(ID);
  1736. }
  1737. if (R.isNull())
  1738. return nullptr;
  1739. DeclContext *Parent = Context.getTranslationUnitDecl();
  1740. if (getLangOpts().CPlusPlus) {
  1741. LinkageSpecDecl *CLinkageDecl =
  1742. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1743. LinkageSpecDecl::lang_c, false);
  1744. CLinkageDecl->setImplicit();
  1745. Parent->addDecl(CLinkageDecl);
  1746. Parent = CLinkageDecl;
  1747. }
  1748. FunctionDecl *New = FunctionDecl::Create(Context,
  1749. Parent,
  1750. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1751. SC_Extern,
  1752. false,
  1753. R->isFunctionProtoType());
  1754. New->setImplicit();
  1755. // Create Decl objects for each parameter, adding them to the
  1756. // FunctionDecl.
  1757. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1758. SmallVector<ParmVarDecl*, 16> Params;
  1759. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1760. ParmVarDecl *parm =
  1761. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1762. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1763. SC_None, nullptr);
  1764. parm->setScopeInfo(0, i);
  1765. Params.push_back(parm);
  1766. }
  1767. New->setParams(Params);
  1768. }
  1769. AddKnownFunctionAttributes(New);
  1770. RegisterLocallyScopedExternCDecl(New, S);
  1771. // TUScope is the translation-unit scope to insert this function into.
  1772. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1773. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1774. // entirely, but we're not there yet.
  1775. DeclContext *SavedContext = CurContext;
  1776. CurContext = Parent;
  1777. PushOnScopeChains(New, TUScope);
  1778. CurContext = SavedContext;
  1779. return New;
  1780. }
  1781. /// Typedef declarations don't have linkage, but they still denote the same
  1782. /// entity if their types are the same.
  1783. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1784. /// isSameEntity.
  1785. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1786. TypedefNameDecl *Decl,
  1787. LookupResult &Previous) {
  1788. // This is only interesting when modules are enabled.
  1789. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1790. return;
  1791. // Empty sets are uninteresting.
  1792. if (Previous.empty())
  1793. return;
  1794. LookupResult::Filter Filter = Previous.makeFilter();
  1795. while (Filter.hasNext()) {
  1796. NamedDecl *Old = Filter.next();
  1797. // Non-hidden declarations are never ignored.
  1798. if (S.isVisible(Old))
  1799. continue;
  1800. // Declarations of the same entity are not ignored, even if they have
  1801. // different linkages.
  1802. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1803. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1804. Decl->getUnderlyingType()))
  1805. continue;
  1806. // If both declarations give a tag declaration a typedef name for linkage
  1807. // purposes, then they declare the same entity.
  1808. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1809. Decl->getAnonDeclWithTypedefName())
  1810. continue;
  1811. }
  1812. Filter.erase();
  1813. }
  1814. Filter.done();
  1815. }
  1816. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1817. QualType OldType;
  1818. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1819. OldType = OldTypedef->getUnderlyingType();
  1820. else
  1821. OldType = Context.getTypeDeclType(Old);
  1822. QualType NewType = New->getUnderlyingType();
  1823. if (NewType->isVariablyModifiedType()) {
  1824. // Must not redefine a typedef with a variably-modified type.
  1825. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1826. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1827. << Kind << NewType;
  1828. if (Old->getLocation().isValid())
  1829. notePreviousDefinition(Old, New->getLocation());
  1830. New->setInvalidDecl();
  1831. return true;
  1832. }
  1833. if (OldType != NewType &&
  1834. !OldType->isDependentType() &&
  1835. !NewType->isDependentType() &&
  1836. !Context.hasSameType(OldType, NewType)) {
  1837. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1838. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1839. << Kind << NewType << OldType;
  1840. if (Old->getLocation().isValid())
  1841. notePreviousDefinition(Old, New->getLocation());
  1842. New->setInvalidDecl();
  1843. return true;
  1844. }
  1845. return false;
  1846. }
  1847. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1848. /// same name and scope as a previous declaration 'Old'. Figure out
  1849. /// how to resolve this situation, merging decls or emitting
  1850. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1851. ///
  1852. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1853. LookupResult &OldDecls) {
  1854. // If the new decl is known invalid already, don't bother doing any
  1855. // merging checks.
  1856. if (New->isInvalidDecl()) return;
  1857. // Allow multiple definitions for ObjC built-in typedefs.
  1858. // FIXME: Verify the underlying types are equivalent!
  1859. if (getLangOpts().ObjC1) {
  1860. const IdentifierInfo *TypeID = New->getIdentifier();
  1861. switch (TypeID->getLength()) {
  1862. default: break;
  1863. case 2:
  1864. {
  1865. if (!TypeID->isStr("id"))
  1866. break;
  1867. QualType T = New->getUnderlyingType();
  1868. if (!T->isPointerType())
  1869. break;
  1870. if (!T->isVoidPointerType()) {
  1871. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1872. if (!PT->isStructureType())
  1873. break;
  1874. }
  1875. Context.setObjCIdRedefinitionType(T);
  1876. // Install the built-in type for 'id', ignoring the current definition.
  1877. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1878. return;
  1879. }
  1880. case 5:
  1881. if (!TypeID->isStr("Class"))
  1882. break;
  1883. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1884. // Install the built-in type for 'Class', ignoring the current definition.
  1885. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1886. return;
  1887. case 3:
  1888. if (!TypeID->isStr("SEL"))
  1889. break;
  1890. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1891. // Install the built-in type for 'SEL', ignoring the current definition.
  1892. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1893. return;
  1894. }
  1895. // Fall through - the typedef name was not a builtin type.
  1896. }
  1897. // Verify the old decl was also a type.
  1898. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1899. if (!Old) {
  1900. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1901. << New->getDeclName();
  1902. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1903. if (OldD->getLocation().isValid())
  1904. notePreviousDefinition(OldD, New->getLocation());
  1905. return New->setInvalidDecl();
  1906. }
  1907. // If the old declaration is invalid, just give up here.
  1908. if (Old->isInvalidDecl())
  1909. return New->setInvalidDecl();
  1910. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1911. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1912. auto *NewTag = New->getAnonDeclWithTypedefName();
  1913. NamedDecl *Hidden = nullptr;
  1914. if (OldTag && NewTag &&
  1915. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1916. !hasVisibleDefinition(OldTag, &Hidden)) {
  1917. // There is a definition of this tag, but it is not visible. Use it
  1918. // instead of our tag.
  1919. New->setTypeForDecl(OldTD->getTypeForDecl());
  1920. if (OldTD->isModed())
  1921. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1922. OldTD->getUnderlyingType());
  1923. else
  1924. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1925. // Make the old tag definition visible.
  1926. makeMergedDefinitionVisible(Hidden);
  1927. // If this was an unscoped enumeration, yank all of its enumerators
  1928. // out of the scope.
  1929. if (isa<EnumDecl>(NewTag)) {
  1930. Scope *EnumScope = getNonFieldDeclScope(S);
  1931. for (auto *D : NewTag->decls()) {
  1932. auto *ED = cast<EnumConstantDecl>(D);
  1933. assert(EnumScope->isDeclScope(ED));
  1934. EnumScope->RemoveDecl(ED);
  1935. IdResolver.RemoveDecl(ED);
  1936. ED->getLexicalDeclContext()->removeDecl(ED);
  1937. }
  1938. }
  1939. }
  1940. }
  1941. // If the typedef types are not identical, reject them in all languages and
  1942. // with any extensions enabled.
  1943. if (isIncompatibleTypedef(Old, New))
  1944. return;
  1945. // The types match. Link up the redeclaration chain and merge attributes if
  1946. // the old declaration was a typedef.
  1947. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1948. New->setPreviousDecl(Typedef);
  1949. mergeDeclAttributes(New, Old);
  1950. }
  1951. if (getLangOpts().MicrosoftExt)
  1952. return;
  1953. if (getLangOpts().CPlusPlus) {
  1954. // C++ [dcl.typedef]p2:
  1955. // In a given non-class scope, a typedef specifier can be used to
  1956. // redefine the name of any type declared in that scope to refer
  1957. // to the type to which it already refers.
  1958. if (!isa<CXXRecordDecl>(CurContext))
  1959. return;
  1960. // C++0x [dcl.typedef]p4:
  1961. // In a given class scope, a typedef specifier can be used to redefine
  1962. // any class-name declared in that scope that is not also a typedef-name
  1963. // to refer to the type to which it already refers.
  1964. //
  1965. // This wording came in via DR424, which was a correction to the
  1966. // wording in DR56, which accidentally banned code like:
  1967. //
  1968. // struct S {
  1969. // typedef struct A { } A;
  1970. // };
  1971. //
  1972. // in the C++03 standard. We implement the C++0x semantics, which
  1973. // allow the above but disallow
  1974. //
  1975. // struct S {
  1976. // typedef int I;
  1977. // typedef int I;
  1978. // };
  1979. //
  1980. // since that was the intent of DR56.
  1981. if (!isa<TypedefNameDecl>(Old))
  1982. return;
  1983. Diag(New->getLocation(), diag::err_redefinition)
  1984. << New->getDeclName();
  1985. notePreviousDefinition(Old, New->getLocation());
  1986. return New->setInvalidDecl();
  1987. }
  1988. // Modules always permit redefinition of typedefs, as does C11.
  1989. if (getLangOpts().Modules || getLangOpts().C11)
  1990. return;
  1991. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1992. // is normally mapped to an error, but can be controlled with
  1993. // -Wtypedef-redefinition. If either the original or the redefinition is
  1994. // in a system header, don't emit this for compatibility with GCC.
  1995. if (getDiagnostics().getSuppressSystemWarnings() &&
  1996. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  1997. (Old->isImplicit() ||
  1998. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1999. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2000. return;
  2001. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2002. << New->getDeclName();
  2003. notePreviousDefinition(Old, New->getLocation());
  2004. }
  2005. /// DeclhasAttr - returns true if decl Declaration already has the target
  2006. /// attribute.
  2007. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2008. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2009. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2010. for (const auto *i : D->attrs())
  2011. if (i->getKind() == A->getKind()) {
  2012. if (Ann) {
  2013. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2014. return true;
  2015. continue;
  2016. }
  2017. // FIXME: Don't hardcode this check
  2018. if (OA && isa<OwnershipAttr>(i))
  2019. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2020. return true;
  2021. }
  2022. return false;
  2023. }
  2024. static bool isAttributeTargetADefinition(Decl *D) {
  2025. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2026. return VD->isThisDeclarationADefinition();
  2027. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2028. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2029. return true;
  2030. }
  2031. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2032. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2033. ///
  2034. /// \return \c true if any attributes were added to \p New.
  2035. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2036. // Look for alignas attributes on Old, and pick out whichever attribute
  2037. // specifies the strictest alignment requirement.
  2038. AlignedAttr *OldAlignasAttr = nullptr;
  2039. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2040. unsigned OldAlign = 0;
  2041. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2042. // FIXME: We have no way of representing inherited dependent alignments
  2043. // in a case like:
  2044. // template<int A, int B> struct alignas(A) X;
  2045. // template<int A, int B> struct alignas(B) X {};
  2046. // For now, we just ignore any alignas attributes which are not on the
  2047. // definition in such a case.
  2048. if (I->isAlignmentDependent())
  2049. return false;
  2050. if (I->isAlignas())
  2051. OldAlignasAttr = I;
  2052. unsigned Align = I->getAlignment(S.Context);
  2053. if (Align > OldAlign) {
  2054. OldAlign = Align;
  2055. OldStrictestAlignAttr = I;
  2056. }
  2057. }
  2058. // Look for alignas attributes on New.
  2059. AlignedAttr *NewAlignasAttr = nullptr;
  2060. unsigned NewAlign = 0;
  2061. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2062. if (I->isAlignmentDependent())
  2063. return false;
  2064. if (I->isAlignas())
  2065. NewAlignasAttr = I;
  2066. unsigned Align = I->getAlignment(S.Context);
  2067. if (Align > NewAlign)
  2068. NewAlign = Align;
  2069. }
  2070. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2071. // Both declarations have 'alignas' attributes. We require them to match.
  2072. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2073. // fall short. (If two declarations both have alignas, they must both match
  2074. // every definition, and so must match each other if there is a definition.)
  2075. // If either declaration only contains 'alignas(0)' specifiers, then it
  2076. // specifies the natural alignment for the type.
  2077. if (OldAlign == 0 || NewAlign == 0) {
  2078. QualType Ty;
  2079. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2080. Ty = VD->getType();
  2081. else
  2082. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2083. if (OldAlign == 0)
  2084. OldAlign = S.Context.getTypeAlign(Ty);
  2085. if (NewAlign == 0)
  2086. NewAlign = S.Context.getTypeAlign(Ty);
  2087. }
  2088. if (OldAlign != NewAlign) {
  2089. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2090. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2091. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2092. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2093. }
  2094. }
  2095. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2096. // C++11 [dcl.align]p6:
  2097. // if any declaration of an entity has an alignment-specifier,
  2098. // every defining declaration of that entity shall specify an
  2099. // equivalent alignment.
  2100. // C11 6.7.5/7:
  2101. // If the definition of an object does not have an alignment
  2102. // specifier, any other declaration of that object shall also
  2103. // have no alignment specifier.
  2104. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2105. << OldAlignasAttr;
  2106. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2107. << OldAlignasAttr;
  2108. }
  2109. bool AnyAdded = false;
  2110. // Ensure we have an attribute representing the strictest alignment.
  2111. if (OldAlign > NewAlign) {
  2112. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2113. Clone->setInherited(true);
  2114. New->addAttr(Clone);
  2115. AnyAdded = true;
  2116. }
  2117. // Ensure we have an alignas attribute if the old declaration had one.
  2118. if (OldAlignasAttr && !NewAlignasAttr &&
  2119. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2120. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2121. Clone->setInherited(true);
  2122. New->addAttr(Clone);
  2123. AnyAdded = true;
  2124. }
  2125. return AnyAdded;
  2126. }
  2127. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2128. const InheritableAttr *Attr,
  2129. Sema::AvailabilityMergeKind AMK) {
  2130. // This function copies an attribute Attr from a previous declaration to the
  2131. // new declaration D if the new declaration doesn't itself have that attribute
  2132. // yet or if that attribute allows duplicates.
  2133. // If you're adding a new attribute that requires logic different from
  2134. // "use explicit attribute on decl if present, else use attribute from
  2135. // previous decl", for example if the attribute needs to be consistent
  2136. // between redeclarations, you need to call a custom merge function here.
  2137. InheritableAttr *NewAttr = nullptr;
  2138. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2139. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2140. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  2141. AA->isImplicit(), AA->getIntroduced(),
  2142. AA->getDeprecated(),
  2143. AA->getObsoleted(), AA->getUnavailable(),
  2144. AA->getMessage(), AA->getStrict(),
  2145. AA->getReplacement(), AMK,
  2146. AttrSpellingListIndex);
  2147. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2148. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2149. AttrSpellingListIndex);
  2150. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2151. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2152. AttrSpellingListIndex);
  2153. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2154. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2155. AttrSpellingListIndex);
  2156. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2157. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2158. AttrSpellingListIndex);
  2159. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2160. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2161. FA->getFormatIdx(), FA->getFirstArg(),
  2162. AttrSpellingListIndex);
  2163. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2164. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2165. AttrSpellingListIndex);
  2166. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2167. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2168. AttrSpellingListIndex,
  2169. IA->getSemanticSpelling());
  2170. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2171. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2172. &S.Context.Idents.get(AA->getSpelling()),
  2173. AttrSpellingListIndex);
  2174. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2175. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2176. isa<CUDAGlobalAttr>(Attr))) {
  2177. // CUDA target attributes are part of function signature for
  2178. // overloading purposes and must not be merged.
  2179. return false;
  2180. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2181. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2182. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2183. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2184. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2185. NewAttr = S.mergeInternalLinkageAttr(
  2186. D, InternalLinkageA->getRange(),
  2187. &S.Context.Idents.get(InternalLinkageA->getSpelling()),
  2188. AttrSpellingListIndex);
  2189. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2190. NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
  2191. &S.Context.Idents.get(CommonA->getSpelling()),
  2192. AttrSpellingListIndex);
  2193. else if (isa<AlignedAttr>(Attr))
  2194. // AlignedAttrs are handled separately, because we need to handle all
  2195. // such attributes on a declaration at the same time.
  2196. NewAttr = nullptr;
  2197. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2198. (AMK == Sema::AMK_Override ||
  2199. AMK == Sema::AMK_ProtocolImplementation))
  2200. NewAttr = nullptr;
  2201. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2202. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2203. UA->getGuid());
  2204. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  2205. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2206. if (NewAttr) {
  2207. NewAttr->setInherited(true);
  2208. D->addAttr(NewAttr);
  2209. if (isa<MSInheritanceAttr>(NewAttr))
  2210. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2211. return true;
  2212. }
  2213. return false;
  2214. }
  2215. static const NamedDecl *getDefinition(const Decl *D) {
  2216. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2217. return TD->getDefinition();
  2218. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2219. const VarDecl *Def = VD->getDefinition();
  2220. if (Def)
  2221. return Def;
  2222. return VD->getActingDefinition();
  2223. }
  2224. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2225. return FD->getDefinition();
  2226. return nullptr;
  2227. }
  2228. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2229. for (const auto *Attribute : D->attrs())
  2230. if (Attribute->getKind() == Kind)
  2231. return true;
  2232. return false;
  2233. }
  2234. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2235. /// there are no new attributes in this declaration.
  2236. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2237. if (!New->hasAttrs())
  2238. return;
  2239. const NamedDecl *Def = getDefinition(Old);
  2240. if (!Def || Def == New)
  2241. return;
  2242. AttrVec &NewAttributes = New->getAttrs();
  2243. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2244. const Attr *NewAttribute = NewAttributes[I];
  2245. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2246. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2247. Sema::SkipBodyInfo SkipBody;
  2248. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2249. // If we're skipping this definition, drop the "alias" attribute.
  2250. if (SkipBody.ShouldSkip) {
  2251. NewAttributes.erase(NewAttributes.begin() + I);
  2252. --E;
  2253. continue;
  2254. }
  2255. } else {
  2256. VarDecl *VD = cast<VarDecl>(New);
  2257. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2258. VarDecl::TentativeDefinition
  2259. ? diag::err_alias_after_tentative
  2260. : diag::err_redefinition;
  2261. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2262. if (Diag == diag::err_redefinition)
  2263. S.notePreviousDefinition(Def, VD->getLocation());
  2264. else
  2265. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2266. VD->setInvalidDecl();
  2267. }
  2268. ++I;
  2269. continue;
  2270. }
  2271. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2272. // Tentative definitions are only interesting for the alias check above.
  2273. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2274. ++I;
  2275. continue;
  2276. }
  2277. }
  2278. if (hasAttribute(Def, NewAttribute->getKind())) {
  2279. ++I;
  2280. continue; // regular attr merging will take care of validating this.
  2281. }
  2282. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2283. // C's _Noreturn is allowed to be added to a function after it is defined.
  2284. ++I;
  2285. continue;
  2286. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2287. if (AA->isAlignas()) {
  2288. // C++11 [dcl.align]p6:
  2289. // if any declaration of an entity has an alignment-specifier,
  2290. // every defining declaration of that entity shall specify an
  2291. // equivalent alignment.
  2292. // C11 6.7.5/7:
  2293. // If the definition of an object does not have an alignment
  2294. // specifier, any other declaration of that object shall also
  2295. // have no alignment specifier.
  2296. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2297. << AA;
  2298. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2299. << AA;
  2300. NewAttributes.erase(NewAttributes.begin() + I);
  2301. --E;
  2302. continue;
  2303. }
  2304. }
  2305. S.Diag(NewAttribute->getLocation(),
  2306. diag::warn_attribute_precede_definition);
  2307. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2308. NewAttributes.erase(NewAttributes.begin() + I);
  2309. --E;
  2310. }
  2311. }
  2312. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2313. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2314. AvailabilityMergeKind AMK) {
  2315. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2316. UsedAttr *NewAttr = OldAttr->clone(Context);
  2317. NewAttr->setInherited(true);
  2318. New->addAttr(NewAttr);
  2319. }
  2320. if (!Old->hasAttrs() && !New->hasAttrs())
  2321. return;
  2322. // Attributes declared post-definition are currently ignored.
  2323. checkNewAttributesAfterDef(*this, New, Old);
  2324. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2325. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2326. if (OldA->getLabel() != NewA->getLabel()) {
  2327. // This redeclaration changes __asm__ label.
  2328. Diag(New->getLocation(), diag::err_different_asm_label);
  2329. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2330. }
  2331. } else if (Old->isUsed()) {
  2332. // This redeclaration adds an __asm__ label to a declaration that has
  2333. // already been ODR-used.
  2334. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2335. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2336. }
  2337. }
  2338. // Re-declaration cannot add abi_tag's.
  2339. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2340. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2341. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2342. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2343. NewTag) == OldAbiTagAttr->tags_end()) {
  2344. Diag(NewAbiTagAttr->getLocation(),
  2345. diag::err_new_abi_tag_on_redeclaration)
  2346. << NewTag;
  2347. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2348. }
  2349. }
  2350. } else {
  2351. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2352. Diag(Old->getLocation(), diag::note_previous_declaration);
  2353. }
  2354. }
  2355. // This redeclaration adds a section attribute.
  2356. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2357. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2358. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2359. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2360. Diag(Old->getLocation(), diag::note_previous_declaration);
  2361. }
  2362. }
  2363. }
  2364. if (!Old->hasAttrs())
  2365. return;
  2366. bool foundAny = New->hasAttrs();
  2367. // Ensure that any moving of objects within the allocated map is done before
  2368. // we process them.
  2369. if (!foundAny) New->setAttrs(AttrVec());
  2370. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2371. // Ignore deprecated/unavailable/availability attributes if requested.
  2372. AvailabilityMergeKind LocalAMK = AMK_None;
  2373. if (isa<DeprecatedAttr>(I) ||
  2374. isa<UnavailableAttr>(I) ||
  2375. isa<AvailabilityAttr>(I)) {
  2376. switch (AMK) {
  2377. case AMK_None:
  2378. continue;
  2379. case AMK_Redeclaration:
  2380. case AMK_Override:
  2381. case AMK_ProtocolImplementation:
  2382. LocalAMK = AMK;
  2383. break;
  2384. }
  2385. }
  2386. // Already handled.
  2387. if (isa<UsedAttr>(I))
  2388. continue;
  2389. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2390. foundAny = true;
  2391. }
  2392. if (mergeAlignedAttrs(*this, New, Old))
  2393. foundAny = true;
  2394. if (!foundAny) New->dropAttrs();
  2395. }
  2396. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2397. /// to the new one.
  2398. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2399. const ParmVarDecl *oldDecl,
  2400. Sema &S) {
  2401. // C++11 [dcl.attr.depend]p2:
  2402. // The first declaration of a function shall specify the
  2403. // carries_dependency attribute for its declarator-id if any declaration
  2404. // of the function specifies the carries_dependency attribute.
  2405. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2406. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2407. S.Diag(CDA->getLocation(),
  2408. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2409. // Find the first declaration of the parameter.
  2410. // FIXME: Should we build redeclaration chains for function parameters?
  2411. const FunctionDecl *FirstFD =
  2412. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2413. const ParmVarDecl *FirstVD =
  2414. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2415. S.Diag(FirstVD->getLocation(),
  2416. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2417. }
  2418. if (!oldDecl->hasAttrs())
  2419. return;
  2420. bool foundAny = newDecl->hasAttrs();
  2421. // Ensure that any moving of objects within the allocated map is
  2422. // done before we process them.
  2423. if (!foundAny) newDecl->setAttrs(AttrVec());
  2424. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2425. if (!DeclHasAttr(newDecl, I)) {
  2426. InheritableAttr *newAttr =
  2427. cast<InheritableParamAttr>(I->clone(S.Context));
  2428. newAttr->setInherited(true);
  2429. newDecl->addAttr(newAttr);
  2430. foundAny = true;
  2431. }
  2432. }
  2433. if (!foundAny) newDecl->dropAttrs();
  2434. }
  2435. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2436. const ParmVarDecl *OldParam,
  2437. Sema &S) {
  2438. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2439. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2440. if (*Oldnullability != *Newnullability) {
  2441. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2442. << DiagNullabilityKind(
  2443. *Newnullability,
  2444. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2445. != 0))
  2446. << DiagNullabilityKind(
  2447. *Oldnullability,
  2448. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2449. != 0));
  2450. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2451. }
  2452. } else {
  2453. QualType NewT = NewParam->getType();
  2454. NewT = S.Context.getAttributedType(
  2455. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2456. NewT, NewT);
  2457. NewParam->setType(NewT);
  2458. }
  2459. }
  2460. }
  2461. namespace {
  2462. /// Used in MergeFunctionDecl to keep track of function parameters in
  2463. /// C.
  2464. struct GNUCompatibleParamWarning {
  2465. ParmVarDecl *OldParm;
  2466. ParmVarDecl *NewParm;
  2467. QualType PromotedType;
  2468. };
  2469. } // end anonymous namespace
  2470. /// getSpecialMember - get the special member enum for a method.
  2471. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2472. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2473. if (Ctor->isDefaultConstructor())
  2474. return Sema::CXXDefaultConstructor;
  2475. if (Ctor->isCopyConstructor())
  2476. return Sema::CXXCopyConstructor;
  2477. if (Ctor->isMoveConstructor())
  2478. return Sema::CXXMoveConstructor;
  2479. } else if (isa<CXXDestructorDecl>(MD)) {
  2480. return Sema::CXXDestructor;
  2481. } else if (MD->isCopyAssignmentOperator()) {
  2482. return Sema::CXXCopyAssignment;
  2483. } else if (MD->isMoveAssignmentOperator()) {
  2484. return Sema::CXXMoveAssignment;
  2485. }
  2486. return Sema::CXXInvalid;
  2487. }
  2488. // Determine whether the previous declaration was a definition, implicit
  2489. // declaration, or a declaration.
  2490. template <typename T>
  2491. static std::pair<diag::kind, SourceLocation>
  2492. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2493. diag::kind PrevDiag;
  2494. SourceLocation OldLocation = Old->getLocation();
  2495. if (Old->isThisDeclarationADefinition())
  2496. PrevDiag = diag::note_previous_definition;
  2497. else if (Old->isImplicit()) {
  2498. PrevDiag = diag::note_previous_implicit_declaration;
  2499. if (OldLocation.isInvalid())
  2500. OldLocation = New->getLocation();
  2501. } else
  2502. PrevDiag = diag::note_previous_declaration;
  2503. return std::make_pair(PrevDiag, OldLocation);
  2504. }
  2505. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2506. /// only extern inline functions can be redefined, and even then only in
  2507. /// GNU89 mode.
  2508. static bool canRedefineFunction(const FunctionDecl *FD,
  2509. const LangOptions& LangOpts) {
  2510. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2511. !LangOpts.CPlusPlus &&
  2512. FD->isInlineSpecified() &&
  2513. FD->getStorageClass() == SC_Extern);
  2514. }
  2515. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2516. const AttributedType *AT = T->getAs<AttributedType>();
  2517. while (AT && !AT->isCallingConv())
  2518. AT = AT->getModifiedType()->getAs<AttributedType>();
  2519. return AT;
  2520. }
  2521. template <typename T>
  2522. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2523. const DeclContext *DC = Old->getDeclContext();
  2524. if (DC->isRecord())
  2525. return false;
  2526. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2527. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2528. return true;
  2529. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2530. return true;
  2531. return false;
  2532. }
  2533. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2534. static bool isExternC(VarTemplateDecl *) { return false; }
  2535. /// \brief Check whether a redeclaration of an entity introduced by a
  2536. /// using-declaration is valid, given that we know it's not an overload
  2537. /// (nor a hidden tag declaration).
  2538. template<typename ExpectedDecl>
  2539. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2540. ExpectedDecl *New) {
  2541. // C++11 [basic.scope.declarative]p4:
  2542. // Given a set of declarations in a single declarative region, each of
  2543. // which specifies the same unqualified name,
  2544. // -- they shall all refer to the same entity, or all refer to functions
  2545. // and function templates; or
  2546. // -- exactly one declaration shall declare a class name or enumeration
  2547. // name that is not a typedef name and the other declarations shall all
  2548. // refer to the same variable or enumerator, or all refer to functions
  2549. // and function templates; in this case the class name or enumeration
  2550. // name is hidden (3.3.10).
  2551. // C++11 [namespace.udecl]p14:
  2552. // If a function declaration in namespace scope or block scope has the
  2553. // same name and the same parameter-type-list as a function introduced
  2554. // by a using-declaration, and the declarations do not declare the same
  2555. // function, the program is ill-formed.
  2556. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2557. if (Old &&
  2558. !Old->getDeclContext()->getRedeclContext()->Equals(
  2559. New->getDeclContext()->getRedeclContext()) &&
  2560. !(isExternC(Old) && isExternC(New)))
  2561. Old = nullptr;
  2562. if (!Old) {
  2563. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2564. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2565. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2566. return true;
  2567. }
  2568. return false;
  2569. }
  2570. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2571. const FunctionDecl *B) {
  2572. assert(A->getNumParams() == B->getNumParams());
  2573. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2574. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2575. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2576. if (AttrA == AttrB)
  2577. return true;
  2578. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2579. };
  2580. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2581. }
  2582. /// MergeFunctionDecl - We just parsed a function 'New' from
  2583. /// declarator D which has the same name and scope as a previous
  2584. /// declaration 'Old'. Figure out how to resolve this situation,
  2585. /// merging decls or emitting diagnostics as appropriate.
  2586. ///
  2587. /// In C++, New and Old must be declarations that are not
  2588. /// overloaded. Use IsOverload to determine whether New and Old are
  2589. /// overloaded, and to select the Old declaration that New should be
  2590. /// merged with.
  2591. ///
  2592. /// Returns true if there was an error, false otherwise.
  2593. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2594. Scope *S, bool MergeTypeWithOld) {
  2595. // Verify the old decl was also a function.
  2596. FunctionDecl *Old = OldD->getAsFunction();
  2597. if (!Old) {
  2598. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2599. if (New->getFriendObjectKind()) {
  2600. Diag(New->getLocation(), diag::err_using_decl_friend);
  2601. Diag(Shadow->getTargetDecl()->getLocation(),
  2602. diag::note_using_decl_target);
  2603. Diag(Shadow->getUsingDecl()->getLocation(),
  2604. diag::note_using_decl) << 0;
  2605. return true;
  2606. }
  2607. // Check whether the two declarations might declare the same function.
  2608. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2609. return true;
  2610. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2611. } else {
  2612. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2613. << New->getDeclName();
  2614. notePreviousDefinition(OldD, New->getLocation());
  2615. return true;
  2616. }
  2617. }
  2618. // If the old declaration is invalid, just give up here.
  2619. if (Old->isInvalidDecl())
  2620. return true;
  2621. diag::kind PrevDiag;
  2622. SourceLocation OldLocation;
  2623. std::tie(PrevDiag, OldLocation) =
  2624. getNoteDiagForInvalidRedeclaration(Old, New);
  2625. // Don't complain about this if we're in GNU89 mode and the old function
  2626. // is an extern inline function.
  2627. // Don't complain about specializations. They are not supposed to have
  2628. // storage classes.
  2629. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2630. New->getStorageClass() == SC_Static &&
  2631. Old->hasExternalFormalLinkage() &&
  2632. !New->getTemplateSpecializationInfo() &&
  2633. !canRedefineFunction(Old, getLangOpts())) {
  2634. if (getLangOpts().MicrosoftExt) {
  2635. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2636. Diag(OldLocation, PrevDiag);
  2637. } else {
  2638. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2639. Diag(OldLocation, PrevDiag);
  2640. return true;
  2641. }
  2642. }
  2643. if (New->hasAttr<InternalLinkageAttr>() &&
  2644. !Old->hasAttr<InternalLinkageAttr>()) {
  2645. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2646. << New->getDeclName();
  2647. notePreviousDefinition(Old, New->getLocation());
  2648. New->dropAttr<InternalLinkageAttr>();
  2649. }
  2650. if (CheckRedeclarationModuleOwnership(New, Old))
  2651. return true;
  2652. if (!getLangOpts().CPlusPlus) {
  2653. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2654. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2655. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2656. << New << OldOvl;
  2657. // Try our best to find a decl that actually has the overloadable
  2658. // attribute for the note. In most cases (e.g. programs with only one
  2659. // broken declaration/definition), this won't matter.
  2660. //
  2661. // FIXME: We could do this if we juggled some extra state in
  2662. // OverloadableAttr, rather than just removing it.
  2663. const Decl *DiagOld = Old;
  2664. if (OldOvl) {
  2665. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2666. const auto *A = D->getAttr<OverloadableAttr>();
  2667. return A && !A->isImplicit();
  2668. });
  2669. // If we've implicitly added *all* of the overloadable attrs to this
  2670. // chain, emitting a "previous redecl" note is pointless.
  2671. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2672. }
  2673. if (DiagOld)
  2674. Diag(DiagOld->getLocation(),
  2675. diag::note_attribute_overloadable_prev_overload)
  2676. << OldOvl;
  2677. if (OldOvl)
  2678. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2679. else
  2680. New->dropAttr<OverloadableAttr>();
  2681. }
  2682. }
  2683. // If a function is first declared with a calling convention, but is later
  2684. // declared or defined without one, all following decls assume the calling
  2685. // convention of the first.
  2686. //
  2687. // It's OK if a function is first declared without a calling convention,
  2688. // but is later declared or defined with the default calling convention.
  2689. //
  2690. // To test if either decl has an explicit calling convention, we look for
  2691. // AttributedType sugar nodes on the type as written. If they are missing or
  2692. // were canonicalized away, we assume the calling convention was implicit.
  2693. //
  2694. // Note also that we DO NOT return at this point, because we still have
  2695. // other tests to run.
  2696. QualType OldQType = Context.getCanonicalType(Old->getType());
  2697. QualType NewQType = Context.getCanonicalType(New->getType());
  2698. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2699. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2700. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2701. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2702. bool RequiresAdjustment = false;
  2703. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2704. FunctionDecl *First = Old->getFirstDecl();
  2705. const FunctionType *FT =
  2706. First->getType().getCanonicalType()->castAs<FunctionType>();
  2707. FunctionType::ExtInfo FI = FT->getExtInfo();
  2708. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2709. if (!NewCCExplicit) {
  2710. // Inherit the CC from the previous declaration if it was specified
  2711. // there but not here.
  2712. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2713. RequiresAdjustment = true;
  2714. } else {
  2715. // Calling conventions aren't compatible, so complain.
  2716. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2717. Diag(New->getLocation(), diag::err_cconv_change)
  2718. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2719. << !FirstCCExplicit
  2720. << (!FirstCCExplicit ? "" :
  2721. FunctionType::getNameForCallConv(FI.getCC()));
  2722. // Put the note on the first decl, since it is the one that matters.
  2723. Diag(First->getLocation(), diag::note_previous_declaration);
  2724. return true;
  2725. }
  2726. }
  2727. // FIXME: diagnose the other way around?
  2728. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2729. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2730. RequiresAdjustment = true;
  2731. }
  2732. // Merge regparm attribute.
  2733. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2734. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2735. if (NewTypeInfo.getHasRegParm()) {
  2736. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2737. << NewType->getRegParmType()
  2738. << OldType->getRegParmType();
  2739. Diag(OldLocation, diag::note_previous_declaration);
  2740. return true;
  2741. }
  2742. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2743. RequiresAdjustment = true;
  2744. }
  2745. // Merge ns_returns_retained attribute.
  2746. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2747. if (NewTypeInfo.getProducesResult()) {
  2748. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2749. << "'ns_returns_retained'";
  2750. Diag(OldLocation, diag::note_previous_declaration);
  2751. return true;
  2752. }
  2753. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2754. RequiresAdjustment = true;
  2755. }
  2756. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2757. NewTypeInfo.getNoCallerSavedRegs()) {
  2758. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2759. AnyX86NoCallerSavedRegistersAttr *Attr =
  2760. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2761. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2762. Diag(OldLocation, diag::note_previous_declaration);
  2763. return true;
  2764. }
  2765. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2766. RequiresAdjustment = true;
  2767. }
  2768. if (RequiresAdjustment) {
  2769. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2770. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2771. New->setType(QualType(AdjustedType, 0));
  2772. NewQType = Context.getCanonicalType(New->getType());
  2773. NewType = cast<FunctionType>(NewQType);
  2774. }
  2775. // If this redeclaration makes the function inline, we may need to add it to
  2776. // UndefinedButUsed.
  2777. if (!Old->isInlined() && New->isInlined() &&
  2778. !New->hasAttr<GNUInlineAttr>() &&
  2779. !getLangOpts().GNUInline &&
  2780. Old->isUsed(false) &&
  2781. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2782. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2783. SourceLocation()));
  2784. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2785. // about it.
  2786. if (New->hasAttr<GNUInlineAttr>() &&
  2787. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2788. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2789. }
  2790. // If pass_object_size params don't match up perfectly, this isn't a valid
  2791. // redeclaration.
  2792. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2793. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2794. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2795. << New->getDeclName();
  2796. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2797. return true;
  2798. }
  2799. if (getLangOpts().CPlusPlus) {
  2800. // C++1z [over.load]p2
  2801. // Certain function declarations cannot be overloaded:
  2802. // -- Function declarations that differ only in the return type,
  2803. // the exception specification, or both cannot be overloaded.
  2804. // Check the exception specifications match. This may recompute the type of
  2805. // both Old and New if it resolved exception specifications, so grab the
  2806. // types again after this. Because this updates the type, we do this before
  2807. // any of the other checks below, which may update the "de facto" NewQType
  2808. // but do not necessarily update the type of New.
  2809. if (CheckEquivalentExceptionSpec(Old, New))
  2810. return true;
  2811. OldQType = Context.getCanonicalType(Old->getType());
  2812. NewQType = Context.getCanonicalType(New->getType());
  2813. // Go back to the type source info to compare the declared return types,
  2814. // per C++1y [dcl.type.auto]p13:
  2815. // Redeclarations or specializations of a function or function template
  2816. // with a declared return type that uses a placeholder type shall also
  2817. // use that placeholder, not a deduced type.
  2818. QualType OldDeclaredReturnType =
  2819. (Old->getTypeSourceInfo()
  2820. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2821. : OldType)->getReturnType();
  2822. QualType NewDeclaredReturnType =
  2823. (New->getTypeSourceInfo()
  2824. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2825. : NewType)->getReturnType();
  2826. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2827. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2828. New->isLocalExternDecl())) {
  2829. QualType ResQT;
  2830. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2831. OldDeclaredReturnType->isObjCObjectPointerType())
  2832. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2833. if (ResQT.isNull()) {
  2834. if (New->isCXXClassMember() && New->isOutOfLine())
  2835. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2836. << New << New->getReturnTypeSourceRange();
  2837. else
  2838. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2839. << New->getReturnTypeSourceRange();
  2840. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2841. << Old->getReturnTypeSourceRange();
  2842. return true;
  2843. }
  2844. else
  2845. NewQType = ResQT;
  2846. }
  2847. QualType OldReturnType = OldType->getReturnType();
  2848. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2849. if (OldReturnType != NewReturnType) {
  2850. // If this function has a deduced return type and has already been
  2851. // defined, copy the deduced value from the old declaration.
  2852. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2853. if (OldAT && OldAT->isDeduced()) {
  2854. New->setType(
  2855. SubstAutoType(New->getType(),
  2856. OldAT->isDependentType() ? Context.DependentTy
  2857. : OldAT->getDeducedType()));
  2858. NewQType = Context.getCanonicalType(
  2859. SubstAutoType(NewQType,
  2860. OldAT->isDependentType() ? Context.DependentTy
  2861. : OldAT->getDeducedType()));
  2862. }
  2863. }
  2864. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2865. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2866. if (OldMethod && NewMethod) {
  2867. // Preserve triviality.
  2868. NewMethod->setTrivial(OldMethod->isTrivial());
  2869. // MSVC allows explicit template specialization at class scope:
  2870. // 2 CXXMethodDecls referring to the same function will be injected.
  2871. // We don't want a redeclaration error.
  2872. bool IsClassScopeExplicitSpecialization =
  2873. OldMethod->isFunctionTemplateSpecialization() &&
  2874. NewMethod->isFunctionTemplateSpecialization();
  2875. bool isFriend = NewMethod->getFriendObjectKind();
  2876. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2877. !IsClassScopeExplicitSpecialization) {
  2878. // -- Member function declarations with the same name and the
  2879. // same parameter types cannot be overloaded if any of them
  2880. // is a static member function declaration.
  2881. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2882. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2883. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2884. return true;
  2885. }
  2886. // C++ [class.mem]p1:
  2887. // [...] A member shall not be declared twice in the
  2888. // member-specification, except that a nested class or member
  2889. // class template can be declared and then later defined.
  2890. if (!inTemplateInstantiation()) {
  2891. unsigned NewDiag;
  2892. if (isa<CXXConstructorDecl>(OldMethod))
  2893. NewDiag = diag::err_constructor_redeclared;
  2894. else if (isa<CXXDestructorDecl>(NewMethod))
  2895. NewDiag = diag::err_destructor_redeclared;
  2896. else if (isa<CXXConversionDecl>(NewMethod))
  2897. NewDiag = diag::err_conv_function_redeclared;
  2898. else
  2899. NewDiag = diag::err_member_redeclared;
  2900. Diag(New->getLocation(), NewDiag);
  2901. } else {
  2902. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2903. << New << New->getType();
  2904. }
  2905. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2906. return true;
  2907. // Complain if this is an explicit declaration of a special
  2908. // member that was initially declared implicitly.
  2909. //
  2910. // As an exception, it's okay to befriend such methods in order
  2911. // to permit the implicit constructor/destructor/operator calls.
  2912. } else if (OldMethod->isImplicit()) {
  2913. if (isFriend) {
  2914. NewMethod->setImplicit();
  2915. } else {
  2916. Diag(NewMethod->getLocation(),
  2917. diag::err_definition_of_implicitly_declared_member)
  2918. << New << getSpecialMember(OldMethod);
  2919. return true;
  2920. }
  2921. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2922. Diag(NewMethod->getLocation(),
  2923. diag::err_definition_of_explicitly_defaulted_member)
  2924. << getSpecialMember(OldMethod);
  2925. return true;
  2926. }
  2927. }
  2928. // C++11 [dcl.attr.noreturn]p1:
  2929. // The first declaration of a function shall specify the noreturn
  2930. // attribute if any declaration of that function specifies the noreturn
  2931. // attribute.
  2932. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2933. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2934. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2935. Diag(Old->getFirstDecl()->getLocation(),
  2936. diag::note_noreturn_missing_first_decl);
  2937. }
  2938. // C++11 [dcl.attr.depend]p2:
  2939. // The first declaration of a function shall specify the
  2940. // carries_dependency attribute for its declarator-id if any declaration
  2941. // of the function specifies the carries_dependency attribute.
  2942. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2943. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2944. Diag(CDA->getLocation(),
  2945. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2946. Diag(Old->getFirstDecl()->getLocation(),
  2947. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2948. }
  2949. // (C++98 8.3.5p3):
  2950. // All declarations for a function shall agree exactly in both the
  2951. // return type and the parameter-type-list.
  2952. // We also want to respect all the extended bits except noreturn.
  2953. // noreturn should now match unless the old type info didn't have it.
  2954. QualType OldQTypeForComparison = OldQType;
  2955. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2956. auto *OldType = OldQType->castAs<FunctionProtoType>();
  2957. const FunctionType *OldTypeForComparison
  2958. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2959. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2960. assert(OldQTypeForComparison.isCanonical());
  2961. }
  2962. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2963. // As a special case, retain the language linkage from previous
  2964. // declarations of a friend function as an extension.
  2965. //
  2966. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2967. // and is useful because there's otherwise no way to specify language
  2968. // linkage within class scope.
  2969. //
  2970. // Check cautiously as the friend object kind isn't yet complete.
  2971. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2972. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2973. Diag(OldLocation, PrevDiag);
  2974. } else {
  2975. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2976. Diag(OldLocation, PrevDiag);
  2977. return true;
  2978. }
  2979. }
  2980. if (OldQTypeForComparison == NewQType)
  2981. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2982. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2983. New->isLocalExternDecl()) {
  2984. // It's OK if we couldn't merge types for a local function declaraton
  2985. // if either the old or new type is dependent. We'll merge the types
  2986. // when we instantiate the function.
  2987. return false;
  2988. }
  2989. // Fall through for conflicting redeclarations and redefinitions.
  2990. }
  2991. // C: Function types need to be compatible, not identical. This handles
  2992. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2993. if (!getLangOpts().CPlusPlus &&
  2994. Context.typesAreCompatible(OldQType, NewQType)) {
  2995. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2996. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2997. const FunctionProtoType *OldProto = nullptr;
  2998. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2999. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3000. // The old declaration provided a function prototype, but the
  3001. // new declaration does not. Merge in the prototype.
  3002. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3003. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3004. NewQType =
  3005. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3006. OldProto->getExtProtoInfo());
  3007. New->setType(NewQType);
  3008. New->setHasInheritedPrototype();
  3009. // Synthesize parameters with the same types.
  3010. SmallVector<ParmVarDecl*, 16> Params;
  3011. for (const auto &ParamType : OldProto->param_types()) {
  3012. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3013. SourceLocation(), nullptr,
  3014. ParamType, /*TInfo=*/nullptr,
  3015. SC_None, nullptr);
  3016. Param->setScopeInfo(0, Params.size());
  3017. Param->setImplicit();
  3018. Params.push_back(Param);
  3019. }
  3020. New->setParams(Params);
  3021. }
  3022. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3023. }
  3024. // GNU C permits a K&R definition to follow a prototype declaration
  3025. // if the declared types of the parameters in the K&R definition
  3026. // match the types in the prototype declaration, even when the
  3027. // promoted types of the parameters from the K&R definition differ
  3028. // from the types in the prototype. GCC then keeps the types from
  3029. // the prototype.
  3030. //
  3031. // If a variadic prototype is followed by a non-variadic K&R definition,
  3032. // the K&R definition becomes variadic. This is sort of an edge case, but
  3033. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3034. // C99 6.9.1p8.
  3035. if (!getLangOpts().CPlusPlus &&
  3036. Old->hasPrototype() && !New->hasPrototype() &&
  3037. New->getType()->getAs<FunctionProtoType>() &&
  3038. Old->getNumParams() == New->getNumParams()) {
  3039. SmallVector<QualType, 16> ArgTypes;
  3040. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3041. const FunctionProtoType *OldProto
  3042. = Old->getType()->getAs<FunctionProtoType>();
  3043. const FunctionProtoType *NewProto
  3044. = New->getType()->getAs<FunctionProtoType>();
  3045. // Determine whether this is the GNU C extension.
  3046. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3047. NewProto->getReturnType());
  3048. bool LooseCompatible = !MergedReturn.isNull();
  3049. for (unsigned Idx = 0, End = Old->getNumParams();
  3050. LooseCompatible && Idx != End; ++Idx) {
  3051. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3052. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3053. if (Context.typesAreCompatible(OldParm->getType(),
  3054. NewProto->getParamType(Idx))) {
  3055. ArgTypes.push_back(NewParm->getType());
  3056. } else if (Context.typesAreCompatible(OldParm->getType(),
  3057. NewParm->getType(),
  3058. /*CompareUnqualified=*/true)) {
  3059. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3060. NewProto->getParamType(Idx) };
  3061. Warnings.push_back(Warn);
  3062. ArgTypes.push_back(NewParm->getType());
  3063. } else
  3064. LooseCompatible = false;
  3065. }
  3066. if (LooseCompatible) {
  3067. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3068. Diag(Warnings[Warn].NewParm->getLocation(),
  3069. diag::ext_param_promoted_not_compatible_with_prototype)
  3070. << Warnings[Warn].PromotedType
  3071. << Warnings[Warn].OldParm->getType();
  3072. if (Warnings[Warn].OldParm->getLocation().isValid())
  3073. Diag(Warnings[Warn].OldParm->getLocation(),
  3074. diag::note_previous_declaration);
  3075. }
  3076. if (MergeTypeWithOld)
  3077. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3078. OldProto->getExtProtoInfo()));
  3079. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3080. }
  3081. // Fall through to diagnose conflicting types.
  3082. }
  3083. // A function that has already been declared has been redeclared or
  3084. // defined with a different type; show an appropriate diagnostic.
  3085. // If the previous declaration was an implicitly-generated builtin
  3086. // declaration, then at the very least we should use a specialized note.
  3087. unsigned BuiltinID;
  3088. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3089. // If it's actually a library-defined builtin function like 'malloc'
  3090. // or 'printf', just warn about the incompatible redeclaration.
  3091. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3092. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3093. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3094. << Old << Old->getType();
  3095. // If this is a global redeclaration, just forget hereafter
  3096. // about the "builtin-ness" of the function.
  3097. //
  3098. // Doing this for local extern declarations is problematic. If
  3099. // the builtin declaration remains visible, a second invalid
  3100. // local declaration will produce a hard error; if it doesn't
  3101. // remain visible, a single bogus local redeclaration (which is
  3102. // actually only a warning) could break all the downstream code.
  3103. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3104. New->getIdentifier()->revertBuiltin();
  3105. return false;
  3106. }
  3107. PrevDiag = diag::note_previous_builtin_declaration;
  3108. }
  3109. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3110. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3111. return true;
  3112. }
  3113. /// \brief Completes the merge of two function declarations that are
  3114. /// known to be compatible.
  3115. ///
  3116. /// This routine handles the merging of attributes and other
  3117. /// properties of function declarations from the old declaration to
  3118. /// the new declaration, once we know that New is in fact a
  3119. /// redeclaration of Old.
  3120. ///
  3121. /// \returns false
  3122. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3123. Scope *S, bool MergeTypeWithOld) {
  3124. // Merge the attributes
  3125. mergeDeclAttributes(New, Old);
  3126. // Merge "pure" flag.
  3127. if (Old->isPure())
  3128. New->setPure();
  3129. // Merge "used" flag.
  3130. if (Old->getMostRecentDecl()->isUsed(false))
  3131. New->setIsUsed();
  3132. // Merge attributes from the parameters. These can mismatch with K&R
  3133. // declarations.
  3134. if (New->getNumParams() == Old->getNumParams())
  3135. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3136. ParmVarDecl *NewParam = New->getParamDecl(i);
  3137. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3138. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3139. mergeParamDeclTypes(NewParam, OldParam, *this);
  3140. }
  3141. if (getLangOpts().CPlusPlus)
  3142. return MergeCXXFunctionDecl(New, Old, S);
  3143. // Merge the function types so the we get the composite types for the return
  3144. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3145. // was visible.
  3146. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3147. if (!Merged.isNull() && MergeTypeWithOld)
  3148. New->setType(Merged);
  3149. return false;
  3150. }
  3151. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3152. ObjCMethodDecl *oldMethod) {
  3153. // Merge the attributes, including deprecated/unavailable
  3154. AvailabilityMergeKind MergeKind =
  3155. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3156. ? AMK_ProtocolImplementation
  3157. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3158. : AMK_Override;
  3159. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3160. // Merge attributes from the parameters.
  3161. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3162. oe = oldMethod->param_end();
  3163. for (ObjCMethodDecl::param_iterator
  3164. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3165. ni != ne && oi != oe; ++ni, ++oi)
  3166. mergeParamDeclAttributes(*ni, *oi, *this);
  3167. }
  3168. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3169. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3170. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3171. ? diag::err_redefinition_different_type
  3172. : diag::err_redeclaration_different_type)
  3173. << New->getDeclName() << New->getType() << Old->getType();
  3174. diag::kind PrevDiag;
  3175. SourceLocation OldLocation;
  3176. std::tie(PrevDiag, OldLocation)
  3177. = getNoteDiagForInvalidRedeclaration(Old, New);
  3178. S.Diag(OldLocation, PrevDiag);
  3179. New->setInvalidDecl();
  3180. }
  3181. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3182. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3183. /// emitting diagnostics as appropriate.
  3184. ///
  3185. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3186. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3187. /// is attached.
  3188. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3189. bool MergeTypeWithOld) {
  3190. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3191. return;
  3192. QualType MergedT;
  3193. if (getLangOpts().CPlusPlus) {
  3194. if (New->getType()->isUndeducedType()) {
  3195. // We don't know what the new type is until the initializer is attached.
  3196. return;
  3197. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3198. // These could still be something that needs exception specs checked.
  3199. return MergeVarDeclExceptionSpecs(New, Old);
  3200. }
  3201. // C++ [basic.link]p10:
  3202. // [...] the types specified by all declarations referring to a given
  3203. // object or function shall be identical, except that declarations for an
  3204. // array object can specify array types that differ by the presence or
  3205. // absence of a major array bound (8.3.4).
  3206. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3207. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3208. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3209. // We are merging a variable declaration New into Old. If it has an array
  3210. // bound, and that bound differs from Old's bound, we should diagnose the
  3211. // mismatch.
  3212. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3213. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3214. PrevVD = PrevVD->getPreviousDecl()) {
  3215. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3216. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3217. continue;
  3218. if (!Context.hasSameType(NewArray, PrevVDTy))
  3219. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3220. }
  3221. }
  3222. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3223. if (Context.hasSameType(OldArray->getElementType(),
  3224. NewArray->getElementType()))
  3225. MergedT = New->getType();
  3226. }
  3227. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3228. // has no array bound, it should not inherit one from Old, if Old is not
  3229. // visible.
  3230. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3231. if (Context.hasSameType(OldArray->getElementType(),
  3232. NewArray->getElementType()))
  3233. MergedT = Old->getType();
  3234. }
  3235. }
  3236. else if (New->getType()->isObjCObjectPointerType() &&
  3237. Old->getType()->isObjCObjectPointerType()) {
  3238. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3239. Old->getType());
  3240. }
  3241. } else {
  3242. // C 6.2.7p2:
  3243. // All declarations that refer to the same object or function shall have
  3244. // compatible type.
  3245. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3246. }
  3247. if (MergedT.isNull()) {
  3248. // It's OK if we couldn't merge types if either type is dependent, for a
  3249. // block-scope variable. In other cases (static data members of class
  3250. // templates, variable templates, ...), we require the types to be
  3251. // equivalent.
  3252. // FIXME: The C++ standard doesn't say anything about this.
  3253. if ((New->getType()->isDependentType() ||
  3254. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3255. // If the old type was dependent, we can't merge with it, so the new type
  3256. // becomes dependent for now. We'll reproduce the original type when we
  3257. // instantiate the TypeSourceInfo for the variable.
  3258. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3259. New->setType(Context.DependentTy);
  3260. return;
  3261. }
  3262. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3263. }
  3264. // Don't actually update the type on the new declaration if the old
  3265. // declaration was an extern declaration in a different scope.
  3266. if (MergeTypeWithOld)
  3267. New->setType(MergedT);
  3268. }
  3269. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3270. LookupResult &Previous) {
  3271. // C11 6.2.7p4:
  3272. // For an identifier with internal or external linkage declared
  3273. // in a scope in which a prior declaration of that identifier is
  3274. // visible, if the prior declaration specifies internal or
  3275. // external linkage, the type of the identifier at the later
  3276. // declaration becomes the composite type.
  3277. //
  3278. // If the variable isn't visible, we do not merge with its type.
  3279. if (Previous.isShadowed())
  3280. return false;
  3281. if (S.getLangOpts().CPlusPlus) {
  3282. // C++11 [dcl.array]p3:
  3283. // If there is a preceding declaration of the entity in the same
  3284. // scope in which the bound was specified, an omitted array bound
  3285. // is taken to be the same as in that earlier declaration.
  3286. return NewVD->isPreviousDeclInSameBlockScope() ||
  3287. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3288. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3289. } else {
  3290. // If the old declaration was function-local, don't merge with its
  3291. // type unless we're in the same function.
  3292. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3293. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3294. }
  3295. }
  3296. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3297. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3298. /// situation, merging decls or emitting diagnostics as appropriate.
  3299. ///
  3300. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3301. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3302. /// definitions here, since the initializer hasn't been attached.
  3303. ///
  3304. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3305. // If the new decl is already invalid, don't do any other checking.
  3306. if (New->isInvalidDecl())
  3307. return;
  3308. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3309. return;
  3310. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3311. // Verify the old decl was also a variable or variable template.
  3312. VarDecl *Old = nullptr;
  3313. VarTemplateDecl *OldTemplate = nullptr;
  3314. if (Previous.isSingleResult()) {
  3315. if (NewTemplate) {
  3316. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3317. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3318. if (auto *Shadow =
  3319. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3320. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3321. return New->setInvalidDecl();
  3322. } else {
  3323. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3324. if (auto *Shadow =
  3325. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3326. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3327. return New->setInvalidDecl();
  3328. }
  3329. }
  3330. if (!Old) {
  3331. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3332. << New->getDeclName();
  3333. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3334. New->getLocation());
  3335. return New->setInvalidDecl();
  3336. }
  3337. // Ensure the template parameters are compatible.
  3338. if (NewTemplate &&
  3339. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3340. OldTemplate->getTemplateParameters(),
  3341. /*Complain=*/true, TPL_TemplateMatch))
  3342. return New->setInvalidDecl();
  3343. // C++ [class.mem]p1:
  3344. // A member shall not be declared twice in the member-specification [...]
  3345. //
  3346. // Here, we need only consider static data members.
  3347. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3348. Diag(New->getLocation(), diag::err_duplicate_member)
  3349. << New->getIdentifier();
  3350. Diag(Old->getLocation(), diag::note_previous_declaration);
  3351. New->setInvalidDecl();
  3352. }
  3353. mergeDeclAttributes(New, Old);
  3354. // Warn if an already-declared variable is made a weak_import in a subsequent
  3355. // declaration
  3356. if (New->hasAttr<WeakImportAttr>() &&
  3357. Old->getStorageClass() == SC_None &&
  3358. !Old->hasAttr<WeakImportAttr>()) {
  3359. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3360. notePreviousDefinition(Old, New->getLocation());
  3361. // Remove weak_import attribute on new declaration.
  3362. New->dropAttr<WeakImportAttr>();
  3363. }
  3364. if (New->hasAttr<InternalLinkageAttr>() &&
  3365. !Old->hasAttr<InternalLinkageAttr>()) {
  3366. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3367. << New->getDeclName();
  3368. notePreviousDefinition(Old, New->getLocation());
  3369. New->dropAttr<InternalLinkageAttr>();
  3370. }
  3371. // Merge the types.
  3372. VarDecl *MostRecent = Old->getMostRecentDecl();
  3373. if (MostRecent != Old) {
  3374. MergeVarDeclTypes(New, MostRecent,
  3375. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3376. if (New->isInvalidDecl())
  3377. return;
  3378. }
  3379. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3380. if (New->isInvalidDecl())
  3381. return;
  3382. diag::kind PrevDiag;
  3383. SourceLocation OldLocation;
  3384. std::tie(PrevDiag, OldLocation) =
  3385. getNoteDiagForInvalidRedeclaration(Old, New);
  3386. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3387. if (New->getStorageClass() == SC_Static &&
  3388. !New->isStaticDataMember() &&
  3389. Old->hasExternalFormalLinkage()) {
  3390. if (getLangOpts().MicrosoftExt) {
  3391. Diag(New->getLocation(), diag::ext_static_non_static)
  3392. << New->getDeclName();
  3393. Diag(OldLocation, PrevDiag);
  3394. } else {
  3395. Diag(New->getLocation(), diag::err_static_non_static)
  3396. << New->getDeclName();
  3397. Diag(OldLocation, PrevDiag);
  3398. return New->setInvalidDecl();
  3399. }
  3400. }
  3401. // C99 6.2.2p4:
  3402. // For an identifier declared with the storage-class specifier
  3403. // extern in a scope in which a prior declaration of that
  3404. // identifier is visible,23) if the prior declaration specifies
  3405. // internal or external linkage, the linkage of the identifier at
  3406. // the later declaration is the same as the linkage specified at
  3407. // the prior declaration. If no prior declaration is visible, or
  3408. // if the prior declaration specifies no linkage, then the
  3409. // identifier has external linkage.
  3410. if (New->hasExternalStorage() && Old->hasLinkage())
  3411. /* Okay */;
  3412. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3413. !New->isStaticDataMember() &&
  3414. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3415. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3416. Diag(OldLocation, PrevDiag);
  3417. return New->setInvalidDecl();
  3418. }
  3419. // Check if extern is followed by non-extern and vice-versa.
  3420. if (New->hasExternalStorage() &&
  3421. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3422. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3423. Diag(OldLocation, PrevDiag);
  3424. return New->setInvalidDecl();
  3425. }
  3426. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3427. !New->hasExternalStorage()) {
  3428. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3429. Diag(OldLocation, PrevDiag);
  3430. return New->setInvalidDecl();
  3431. }
  3432. if (CheckRedeclarationModuleOwnership(New, Old))
  3433. return;
  3434. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3435. // FIXME: The test for external storage here seems wrong? We still
  3436. // need to check for mismatches.
  3437. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3438. // Don't complain about out-of-line definitions of static members.
  3439. !(Old->getLexicalDeclContext()->isRecord() &&
  3440. !New->getLexicalDeclContext()->isRecord())) {
  3441. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3442. Diag(OldLocation, PrevDiag);
  3443. return New->setInvalidDecl();
  3444. }
  3445. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3446. if (VarDecl *Def = Old->getDefinition()) {
  3447. // C++1z [dcl.fcn.spec]p4:
  3448. // If the definition of a variable appears in a translation unit before
  3449. // its first declaration as inline, the program is ill-formed.
  3450. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3451. Diag(Def->getLocation(), diag::note_previous_definition);
  3452. }
  3453. }
  3454. // If this redeclaration makes the variable inline, we may need to add it to
  3455. // UndefinedButUsed.
  3456. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3457. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3458. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3459. SourceLocation()));
  3460. if (New->getTLSKind() != Old->getTLSKind()) {
  3461. if (!Old->getTLSKind()) {
  3462. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3463. Diag(OldLocation, PrevDiag);
  3464. } else if (!New->getTLSKind()) {
  3465. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3466. Diag(OldLocation, PrevDiag);
  3467. } else {
  3468. // Do not allow redeclaration to change the variable between requiring
  3469. // static and dynamic initialization.
  3470. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3471. // declaration to determine the kind. Do we need to be compatible here?
  3472. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3473. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3474. Diag(OldLocation, PrevDiag);
  3475. }
  3476. }
  3477. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3478. if (getLangOpts().CPlusPlus &&
  3479. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3480. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3481. Old->getCanonicalDecl()->isConstexpr()) {
  3482. // This definition won't be a definition any more once it's been merged.
  3483. Diag(New->getLocation(),
  3484. diag::warn_deprecated_redundant_constexpr_static_def);
  3485. } else if (VarDecl *Def = Old->getDefinition()) {
  3486. if (checkVarDeclRedefinition(Def, New))
  3487. return;
  3488. }
  3489. }
  3490. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3491. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3492. Diag(OldLocation, PrevDiag);
  3493. New->setInvalidDecl();
  3494. return;
  3495. }
  3496. // Merge "used" flag.
  3497. if (Old->getMostRecentDecl()->isUsed(false))
  3498. New->setIsUsed();
  3499. // Keep a chain of previous declarations.
  3500. New->setPreviousDecl(Old);
  3501. if (NewTemplate)
  3502. NewTemplate->setPreviousDecl(OldTemplate);
  3503. // Inherit access appropriately.
  3504. New->setAccess(Old->getAccess());
  3505. if (NewTemplate)
  3506. NewTemplate->setAccess(New->getAccess());
  3507. if (Old->isInline())
  3508. New->setImplicitlyInline();
  3509. }
  3510. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3511. SourceManager &SrcMgr = getSourceManager();
  3512. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3513. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3514. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3515. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3516. auto &HSI = PP.getHeaderSearchInfo();
  3517. StringRef HdrFilename =
  3518. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3519. auto noteFromModuleOrInclude = [&](Module *Mod,
  3520. SourceLocation IncLoc) -> bool {
  3521. // Redefinition errors with modules are common with non modular mapped
  3522. // headers, example: a non-modular header H in module A that also gets
  3523. // included directly in a TU. Pointing twice to the same header/definition
  3524. // is confusing, try to get better diagnostics when modules is on.
  3525. if (IncLoc.isValid()) {
  3526. if (Mod) {
  3527. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3528. << HdrFilename.str() << Mod->getFullModuleName();
  3529. if (!Mod->DefinitionLoc.isInvalid())
  3530. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3531. << Mod->getFullModuleName();
  3532. } else {
  3533. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3534. << HdrFilename.str();
  3535. }
  3536. return true;
  3537. }
  3538. return false;
  3539. };
  3540. // Is it the same file and same offset? Provide more information on why
  3541. // this leads to a redefinition error.
  3542. bool EmittedDiag = false;
  3543. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3544. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3545. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3546. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3547. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3548. // If the header has no guards, emit a note suggesting one.
  3549. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3550. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3551. if (EmittedDiag)
  3552. return;
  3553. }
  3554. // Redefinition coming from different files or couldn't do better above.
  3555. Diag(Old->getLocation(), diag::note_previous_definition);
  3556. }
  3557. /// We've just determined that \p Old and \p New both appear to be definitions
  3558. /// of the same variable. Either diagnose or fix the problem.
  3559. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3560. if (!hasVisibleDefinition(Old) &&
  3561. (New->getFormalLinkage() == InternalLinkage ||
  3562. New->isInline() ||
  3563. New->getDescribedVarTemplate() ||
  3564. New->getNumTemplateParameterLists() ||
  3565. New->getDeclContext()->isDependentContext())) {
  3566. // The previous definition is hidden, and multiple definitions are
  3567. // permitted (in separate TUs). Demote this to a declaration.
  3568. New->demoteThisDefinitionToDeclaration();
  3569. // Make the canonical definition visible.
  3570. if (auto *OldTD = Old->getDescribedVarTemplate())
  3571. makeMergedDefinitionVisible(OldTD);
  3572. makeMergedDefinitionVisible(Old);
  3573. return false;
  3574. } else {
  3575. Diag(New->getLocation(), diag::err_redefinition) << New;
  3576. notePreviousDefinition(Old, New->getLocation());
  3577. New->setInvalidDecl();
  3578. return true;
  3579. }
  3580. }
  3581. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3582. /// no declarator (e.g. "struct foo;") is parsed.
  3583. Decl *
  3584. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3585. RecordDecl *&AnonRecord) {
  3586. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3587. AnonRecord);
  3588. }
  3589. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3590. // disambiguate entities defined in different scopes.
  3591. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3592. // compatibility.
  3593. // We will pick our mangling number depending on which version of MSVC is being
  3594. // targeted.
  3595. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3596. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3597. ? S->getMSCurManglingNumber()
  3598. : S->getMSLastManglingNumber();
  3599. }
  3600. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3601. if (!Context.getLangOpts().CPlusPlus)
  3602. return;
  3603. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3604. // If this tag is the direct child of a class, number it if
  3605. // it is anonymous.
  3606. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3607. return;
  3608. MangleNumberingContext &MCtx =
  3609. Context.getManglingNumberContext(Tag->getParent());
  3610. Context.setManglingNumber(
  3611. Tag, MCtx.getManglingNumber(
  3612. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3613. return;
  3614. }
  3615. // If this tag isn't a direct child of a class, number it if it is local.
  3616. Decl *ManglingContextDecl;
  3617. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3618. Tag->getDeclContext(), ManglingContextDecl)) {
  3619. Context.setManglingNumber(
  3620. Tag, MCtx->getManglingNumber(
  3621. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3622. }
  3623. }
  3624. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3625. TypedefNameDecl *NewTD) {
  3626. if (TagFromDeclSpec->isInvalidDecl())
  3627. return;
  3628. // Do nothing if the tag already has a name for linkage purposes.
  3629. if (TagFromDeclSpec->hasNameForLinkage())
  3630. return;
  3631. // A well-formed anonymous tag must always be a TUK_Definition.
  3632. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3633. // The type must match the tag exactly; no qualifiers allowed.
  3634. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3635. Context.getTagDeclType(TagFromDeclSpec))) {
  3636. if (getLangOpts().CPlusPlus)
  3637. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3638. return;
  3639. }
  3640. // If we've already computed linkage for the anonymous tag, then
  3641. // adding a typedef name for the anonymous decl can change that
  3642. // linkage, which might be a serious problem. Diagnose this as
  3643. // unsupported and ignore the typedef name. TODO: we should
  3644. // pursue this as a language defect and establish a formal rule
  3645. // for how to handle it.
  3646. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3647. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3648. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3649. tagLoc = getLocForEndOfToken(tagLoc);
  3650. llvm::SmallString<40> textToInsert;
  3651. textToInsert += ' ';
  3652. textToInsert += NewTD->getIdentifier()->getName();
  3653. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3654. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3655. return;
  3656. }
  3657. // Otherwise, set this is the anon-decl typedef for the tag.
  3658. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3659. }
  3660. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3661. switch (T) {
  3662. case DeclSpec::TST_class:
  3663. return 0;
  3664. case DeclSpec::TST_struct:
  3665. return 1;
  3666. case DeclSpec::TST_interface:
  3667. return 2;
  3668. case DeclSpec::TST_union:
  3669. return 3;
  3670. case DeclSpec::TST_enum:
  3671. return 4;
  3672. default:
  3673. llvm_unreachable("unexpected type specifier");
  3674. }
  3675. }
  3676. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3677. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3678. /// parameters to cope with template friend declarations.
  3679. Decl *
  3680. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3681. MultiTemplateParamsArg TemplateParams,
  3682. bool IsExplicitInstantiation,
  3683. RecordDecl *&AnonRecord) {
  3684. Decl *TagD = nullptr;
  3685. TagDecl *Tag = nullptr;
  3686. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3687. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3688. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3689. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3690. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3691. TagD = DS.getRepAsDecl();
  3692. if (!TagD) // We probably had an error
  3693. return nullptr;
  3694. // Note that the above type specs guarantee that the
  3695. // type rep is a Decl, whereas in many of the others
  3696. // it's a Type.
  3697. if (isa<TagDecl>(TagD))
  3698. Tag = cast<TagDecl>(TagD);
  3699. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3700. Tag = CTD->getTemplatedDecl();
  3701. }
  3702. if (Tag) {
  3703. handleTagNumbering(Tag, S);
  3704. Tag->setFreeStanding();
  3705. if (Tag->isInvalidDecl())
  3706. return Tag;
  3707. }
  3708. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3709. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3710. // or incomplete types shall not be restrict-qualified."
  3711. if (TypeQuals & DeclSpec::TQ_restrict)
  3712. Diag(DS.getRestrictSpecLoc(),
  3713. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3714. << DS.getSourceRange();
  3715. }
  3716. if (DS.isInlineSpecified())
  3717. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3718. << getLangOpts().CPlusPlus1z;
  3719. if (DS.isConstexprSpecified()) {
  3720. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3721. // and definitions of functions and variables.
  3722. if (Tag)
  3723. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3724. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3725. else
  3726. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3727. // Don't emit warnings after this error.
  3728. return TagD;
  3729. }
  3730. if (DS.isConceptSpecified()) {
  3731. // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
  3732. // either a function concept and its definition or a variable concept and
  3733. // its initializer.
  3734. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  3735. return TagD;
  3736. }
  3737. DiagnoseFunctionSpecifiers(DS);
  3738. if (DS.isFriendSpecified()) {
  3739. // If we're dealing with a decl but not a TagDecl, assume that
  3740. // whatever routines created it handled the friendship aspect.
  3741. if (TagD && !Tag)
  3742. return nullptr;
  3743. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3744. }
  3745. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3746. bool IsExplicitSpecialization =
  3747. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3748. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3749. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3750. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3751. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3752. // nested-name-specifier unless it is an explicit instantiation
  3753. // or an explicit specialization.
  3754. //
  3755. // FIXME: We allow class template partial specializations here too, per the
  3756. // obvious intent of DR1819.
  3757. //
  3758. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3759. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3760. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3761. return nullptr;
  3762. }
  3763. // Track whether this decl-specifier declares anything.
  3764. bool DeclaresAnything = true;
  3765. // Handle anonymous struct definitions.
  3766. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3767. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3768. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3769. if (getLangOpts().CPlusPlus ||
  3770. Record->getDeclContext()->isRecord()) {
  3771. // If CurContext is a DeclContext that can contain statements,
  3772. // RecursiveASTVisitor won't visit the decls that
  3773. // BuildAnonymousStructOrUnion() will put into CurContext.
  3774. // Also store them here so that they can be part of the
  3775. // DeclStmt that gets created in this case.
  3776. // FIXME: Also return the IndirectFieldDecls created by
  3777. // BuildAnonymousStructOr union, for the same reason?
  3778. if (CurContext->isFunctionOrMethod())
  3779. AnonRecord = Record;
  3780. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3781. Context.getPrintingPolicy());
  3782. }
  3783. DeclaresAnything = false;
  3784. }
  3785. }
  3786. // C11 6.7.2.1p2:
  3787. // A struct-declaration that does not declare an anonymous structure or
  3788. // anonymous union shall contain a struct-declarator-list.
  3789. //
  3790. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3791. // did not permit a struct-declaration without a struct-declarator-list.
  3792. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3793. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3794. // Check for Microsoft C extension: anonymous struct/union member.
  3795. // Handle 2 kinds of anonymous struct/union:
  3796. // struct STRUCT;
  3797. // union UNION;
  3798. // and
  3799. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3800. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3801. if ((Tag && Tag->getDeclName()) ||
  3802. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3803. RecordDecl *Record = nullptr;
  3804. if (Tag)
  3805. Record = dyn_cast<RecordDecl>(Tag);
  3806. else if (const RecordType *RT =
  3807. DS.getRepAsType().get()->getAsStructureType())
  3808. Record = RT->getDecl();
  3809. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3810. Record = UT->getDecl();
  3811. if (Record && getLangOpts().MicrosoftExt) {
  3812. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3813. << Record->isUnion() << DS.getSourceRange();
  3814. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3815. }
  3816. DeclaresAnything = false;
  3817. }
  3818. }
  3819. // Skip all the checks below if we have a type error.
  3820. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3821. (TagD && TagD->isInvalidDecl()))
  3822. return TagD;
  3823. if (getLangOpts().CPlusPlus &&
  3824. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3825. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3826. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3827. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3828. DeclaresAnything = false;
  3829. if (!DS.isMissingDeclaratorOk()) {
  3830. // Customize diagnostic for a typedef missing a name.
  3831. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3832. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3833. << DS.getSourceRange();
  3834. else
  3835. DeclaresAnything = false;
  3836. }
  3837. if (DS.isModulePrivateSpecified() &&
  3838. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3839. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3840. << Tag->getTagKind()
  3841. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3842. ActOnDocumentableDecl(TagD);
  3843. // C 6.7/2:
  3844. // A declaration [...] shall declare at least a declarator [...], a tag,
  3845. // or the members of an enumeration.
  3846. // C++ [dcl.dcl]p3:
  3847. // [If there are no declarators], and except for the declaration of an
  3848. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3849. // names into the program, or shall redeclare a name introduced by a
  3850. // previous declaration.
  3851. if (!DeclaresAnything) {
  3852. // In C, we allow this as a (popular) extension / bug. Don't bother
  3853. // producing further diagnostics for redundant qualifiers after this.
  3854. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3855. return TagD;
  3856. }
  3857. // C++ [dcl.stc]p1:
  3858. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3859. // init-declarator-list of the declaration shall not be empty.
  3860. // C++ [dcl.fct.spec]p1:
  3861. // If a cv-qualifier appears in a decl-specifier-seq, the
  3862. // init-declarator-list of the declaration shall not be empty.
  3863. //
  3864. // Spurious qualifiers here appear to be valid in C.
  3865. unsigned DiagID = diag::warn_standalone_specifier;
  3866. if (getLangOpts().CPlusPlus)
  3867. DiagID = diag::ext_standalone_specifier;
  3868. // Note that a linkage-specification sets a storage class, but
  3869. // 'extern "C" struct foo;' is actually valid and not theoretically
  3870. // useless.
  3871. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3872. if (SCS == DeclSpec::SCS_mutable)
  3873. // Since mutable is not a viable storage class specifier in C, there is
  3874. // no reason to treat it as an extension. Instead, diagnose as an error.
  3875. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3876. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3877. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3878. << DeclSpec::getSpecifierName(SCS);
  3879. }
  3880. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3881. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3882. << DeclSpec::getSpecifierName(TSCS);
  3883. if (DS.getTypeQualifiers()) {
  3884. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3885. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3886. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3887. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3888. // Restrict is covered above.
  3889. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3890. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3891. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3892. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3893. }
  3894. // Warn about ignored type attributes, for example:
  3895. // __attribute__((aligned)) struct A;
  3896. // Attributes should be placed after tag to apply to type declaration.
  3897. if (!DS.getAttributes().empty()) {
  3898. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3899. if (TypeSpecType == DeclSpec::TST_class ||
  3900. TypeSpecType == DeclSpec::TST_struct ||
  3901. TypeSpecType == DeclSpec::TST_interface ||
  3902. TypeSpecType == DeclSpec::TST_union ||
  3903. TypeSpecType == DeclSpec::TST_enum) {
  3904. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3905. attrs = attrs->getNext())
  3906. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3907. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3908. }
  3909. }
  3910. return TagD;
  3911. }
  3912. /// We are trying to inject an anonymous member into the given scope;
  3913. /// check if there's an existing declaration that can't be overloaded.
  3914. ///
  3915. /// \return true if this is a forbidden redeclaration
  3916. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3917. Scope *S,
  3918. DeclContext *Owner,
  3919. DeclarationName Name,
  3920. SourceLocation NameLoc,
  3921. bool IsUnion) {
  3922. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3923. Sema::ForVisibleRedeclaration);
  3924. if (!SemaRef.LookupName(R, S)) return false;
  3925. // Pick a representative declaration.
  3926. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3927. assert(PrevDecl && "Expected a non-null Decl");
  3928. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3929. return false;
  3930. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3931. << IsUnion << Name;
  3932. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3933. return true;
  3934. }
  3935. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3936. /// anonymous struct or union AnonRecord into the owning context Owner
  3937. /// and scope S. This routine will be invoked just after we realize
  3938. /// that an unnamed union or struct is actually an anonymous union or
  3939. /// struct, e.g.,
  3940. ///
  3941. /// @code
  3942. /// union {
  3943. /// int i;
  3944. /// float f;
  3945. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3946. /// // f into the surrounding scope.x
  3947. /// @endcode
  3948. ///
  3949. /// This routine is recursive, injecting the names of nested anonymous
  3950. /// structs/unions into the owning context and scope as well.
  3951. static bool
  3952. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3953. RecordDecl *AnonRecord, AccessSpecifier AS,
  3954. SmallVectorImpl<NamedDecl *> &Chaining) {
  3955. bool Invalid = false;
  3956. // Look every FieldDecl and IndirectFieldDecl with a name.
  3957. for (auto *D : AnonRecord->decls()) {
  3958. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3959. cast<NamedDecl>(D)->getDeclName()) {
  3960. ValueDecl *VD = cast<ValueDecl>(D);
  3961. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3962. VD->getLocation(),
  3963. AnonRecord->isUnion())) {
  3964. // C++ [class.union]p2:
  3965. // The names of the members of an anonymous union shall be
  3966. // distinct from the names of any other entity in the
  3967. // scope in which the anonymous union is declared.
  3968. Invalid = true;
  3969. } else {
  3970. // C++ [class.union]p2:
  3971. // For the purpose of name lookup, after the anonymous union
  3972. // definition, the members of the anonymous union are
  3973. // considered to have been defined in the scope in which the
  3974. // anonymous union is declared.
  3975. unsigned OldChainingSize = Chaining.size();
  3976. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3977. Chaining.append(IF->chain_begin(), IF->chain_end());
  3978. else
  3979. Chaining.push_back(VD);
  3980. assert(Chaining.size() >= 2);
  3981. NamedDecl **NamedChain =
  3982. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3983. for (unsigned i = 0; i < Chaining.size(); i++)
  3984. NamedChain[i] = Chaining[i];
  3985. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3986. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3987. VD->getType(), {NamedChain, Chaining.size()});
  3988. for (const auto *Attr : VD->attrs())
  3989. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3990. IndirectField->setAccess(AS);
  3991. IndirectField->setImplicit();
  3992. SemaRef.PushOnScopeChains(IndirectField, S);
  3993. // That includes picking up the appropriate access specifier.
  3994. if (AS != AS_none) IndirectField->setAccess(AS);
  3995. Chaining.resize(OldChainingSize);
  3996. }
  3997. }
  3998. }
  3999. return Invalid;
  4000. }
  4001. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4002. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4003. /// illegal input values are mapped to SC_None.
  4004. static StorageClass
  4005. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4006. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4007. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4008. "Parser allowed 'typedef' as storage class VarDecl.");
  4009. switch (StorageClassSpec) {
  4010. case DeclSpec::SCS_unspecified: return SC_None;
  4011. case DeclSpec::SCS_extern:
  4012. if (DS.isExternInLinkageSpec())
  4013. return SC_None;
  4014. return SC_Extern;
  4015. case DeclSpec::SCS_static: return SC_Static;
  4016. case DeclSpec::SCS_auto: return SC_Auto;
  4017. case DeclSpec::SCS_register: return SC_Register;
  4018. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4019. // Illegal SCSs map to None: error reporting is up to the caller.
  4020. case DeclSpec::SCS_mutable: // Fall through.
  4021. case DeclSpec::SCS_typedef: return SC_None;
  4022. }
  4023. llvm_unreachable("unknown storage class specifier");
  4024. }
  4025. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4026. assert(Record->hasInClassInitializer());
  4027. for (const auto *I : Record->decls()) {
  4028. const auto *FD = dyn_cast<FieldDecl>(I);
  4029. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4030. FD = IFD->getAnonField();
  4031. if (FD && FD->hasInClassInitializer())
  4032. return FD->getLocation();
  4033. }
  4034. llvm_unreachable("couldn't find in-class initializer");
  4035. }
  4036. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4037. SourceLocation DefaultInitLoc) {
  4038. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4039. return;
  4040. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4041. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4042. }
  4043. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4044. CXXRecordDecl *AnonUnion) {
  4045. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4046. return;
  4047. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4048. }
  4049. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4050. /// anonymous structure or union. Anonymous unions are a C++ feature
  4051. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4052. /// are a C11 feature and GNU C++ extension.
  4053. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4054. AccessSpecifier AS,
  4055. RecordDecl *Record,
  4056. const PrintingPolicy &Policy) {
  4057. DeclContext *Owner = Record->getDeclContext();
  4058. // Diagnose whether this anonymous struct/union is an extension.
  4059. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4060. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4061. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4062. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4063. else if (!Record->isUnion() && !getLangOpts().C11)
  4064. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4065. // C and C++ require different kinds of checks for anonymous
  4066. // structs/unions.
  4067. bool Invalid = false;
  4068. if (getLangOpts().CPlusPlus) {
  4069. const char *PrevSpec = nullptr;
  4070. unsigned DiagID;
  4071. if (Record->isUnion()) {
  4072. // C++ [class.union]p6:
  4073. // Anonymous unions declared in a named namespace or in the
  4074. // global namespace shall be declared static.
  4075. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4076. (isa<TranslationUnitDecl>(Owner) ||
  4077. (isa<NamespaceDecl>(Owner) &&
  4078. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  4079. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4080. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4081. // Recover by adding 'static'.
  4082. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4083. PrevSpec, DiagID, Policy);
  4084. }
  4085. // C++ [class.union]p6:
  4086. // A storage class is not allowed in a declaration of an
  4087. // anonymous union in a class scope.
  4088. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4089. isa<RecordDecl>(Owner)) {
  4090. Diag(DS.getStorageClassSpecLoc(),
  4091. diag::err_anonymous_union_with_storage_spec)
  4092. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4093. // Recover by removing the storage specifier.
  4094. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4095. SourceLocation(),
  4096. PrevSpec, DiagID, Context.getPrintingPolicy());
  4097. }
  4098. }
  4099. // Ignore const/volatile/restrict qualifiers.
  4100. if (DS.getTypeQualifiers()) {
  4101. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4102. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4103. << Record->isUnion() << "const"
  4104. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4105. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4106. Diag(DS.getVolatileSpecLoc(),
  4107. diag::ext_anonymous_struct_union_qualified)
  4108. << Record->isUnion() << "volatile"
  4109. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4110. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4111. Diag(DS.getRestrictSpecLoc(),
  4112. diag::ext_anonymous_struct_union_qualified)
  4113. << Record->isUnion() << "restrict"
  4114. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4115. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4116. Diag(DS.getAtomicSpecLoc(),
  4117. diag::ext_anonymous_struct_union_qualified)
  4118. << Record->isUnion() << "_Atomic"
  4119. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4120. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4121. Diag(DS.getUnalignedSpecLoc(),
  4122. diag::ext_anonymous_struct_union_qualified)
  4123. << Record->isUnion() << "__unaligned"
  4124. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4125. DS.ClearTypeQualifiers();
  4126. }
  4127. // C++ [class.union]p2:
  4128. // The member-specification of an anonymous union shall only
  4129. // define non-static data members. [Note: nested types and
  4130. // functions cannot be declared within an anonymous union. ]
  4131. for (auto *Mem : Record->decls()) {
  4132. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4133. // C++ [class.union]p3:
  4134. // An anonymous union shall not have private or protected
  4135. // members (clause 11).
  4136. assert(FD->getAccess() != AS_none);
  4137. if (FD->getAccess() != AS_public) {
  4138. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4139. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4140. Invalid = true;
  4141. }
  4142. // C++ [class.union]p1
  4143. // An object of a class with a non-trivial constructor, a non-trivial
  4144. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4145. // assignment operator cannot be a member of a union, nor can an
  4146. // array of such objects.
  4147. if (CheckNontrivialField(FD))
  4148. Invalid = true;
  4149. } else if (Mem->isImplicit()) {
  4150. // Any implicit members are fine.
  4151. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4152. // This is a type that showed up in an
  4153. // elaborated-type-specifier inside the anonymous struct or
  4154. // union, but which actually declares a type outside of the
  4155. // anonymous struct or union. It's okay.
  4156. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4157. if (!MemRecord->isAnonymousStructOrUnion() &&
  4158. MemRecord->getDeclName()) {
  4159. // Visual C++ allows type definition in anonymous struct or union.
  4160. if (getLangOpts().MicrosoftExt)
  4161. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4162. << Record->isUnion();
  4163. else {
  4164. // This is a nested type declaration.
  4165. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4166. << Record->isUnion();
  4167. Invalid = true;
  4168. }
  4169. } else {
  4170. // This is an anonymous type definition within another anonymous type.
  4171. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4172. // not part of standard C++.
  4173. Diag(MemRecord->getLocation(),
  4174. diag::ext_anonymous_record_with_anonymous_type)
  4175. << Record->isUnion();
  4176. }
  4177. } else if (isa<AccessSpecDecl>(Mem)) {
  4178. // Any access specifier is fine.
  4179. } else if (isa<StaticAssertDecl>(Mem)) {
  4180. // In C++1z, static_assert declarations are also fine.
  4181. } else {
  4182. // We have something that isn't a non-static data
  4183. // member. Complain about it.
  4184. unsigned DK = diag::err_anonymous_record_bad_member;
  4185. if (isa<TypeDecl>(Mem))
  4186. DK = diag::err_anonymous_record_with_type;
  4187. else if (isa<FunctionDecl>(Mem))
  4188. DK = diag::err_anonymous_record_with_function;
  4189. else if (isa<VarDecl>(Mem))
  4190. DK = diag::err_anonymous_record_with_static;
  4191. // Visual C++ allows type definition in anonymous struct or union.
  4192. if (getLangOpts().MicrosoftExt &&
  4193. DK == diag::err_anonymous_record_with_type)
  4194. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4195. << Record->isUnion();
  4196. else {
  4197. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4198. Invalid = true;
  4199. }
  4200. }
  4201. }
  4202. // C++11 [class.union]p8 (DR1460):
  4203. // At most one variant member of a union may have a
  4204. // brace-or-equal-initializer.
  4205. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4206. Owner->isRecord())
  4207. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4208. cast<CXXRecordDecl>(Record));
  4209. }
  4210. if (!Record->isUnion() && !Owner->isRecord()) {
  4211. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4212. << getLangOpts().CPlusPlus;
  4213. Invalid = true;
  4214. }
  4215. // Mock up a declarator.
  4216. Declarator Dc(DS, Declarator::MemberContext);
  4217. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4218. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4219. // Create a declaration for this anonymous struct/union.
  4220. NamedDecl *Anon = nullptr;
  4221. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4222. Anon = FieldDecl::Create(Context, OwningClass,
  4223. DS.getLocStart(),
  4224. Record->getLocation(),
  4225. /*IdentifierInfo=*/nullptr,
  4226. Context.getTypeDeclType(Record),
  4227. TInfo,
  4228. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4229. /*InitStyle=*/ICIS_NoInit);
  4230. Anon->setAccess(AS);
  4231. if (getLangOpts().CPlusPlus)
  4232. FieldCollector->Add(cast<FieldDecl>(Anon));
  4233. } else {
  4234. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4235. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4236. if (SCSpec == DeclSpec::SCS_mutable) {
  4237. // mutable can only appear on non-static class members, so it's always
  4238. // an error here
  4239. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4240. Invalid = true;
  4241. SC = SC_None;
  4242. }
  4243. Anon = VarDecl::Create(Context, Owner,
  4244. DS.getLocStart(),
  4245. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4246. Context.getTypeDeclType(Record),
  4247. TInfo, SC);
  4248. // Default-initialize the implicit variable. This initialization will be
  4249. // trivial in almost all cases, except if a union member has an in-class
  4250. // initializer:
  4251. // union { int n = 0; };
  4252. ActOnUninitializedDecl(Anon);
  4253. }
  4254. Anon->setImplicit();
  4255. // Mark this as an anonymous struct/union type.
  4256. Record->setAnonymousStructOrUnion(true);
  4257. // Add the anonymous struct/union object to the current
  4258. // context. We'll be referencing this object when we refer to one of
  4259. // its members.
  4260. Owner->addDecl(Anon);
  4261. // Inject the members of the anonymous struct/union into the owning
  4262. // context and into the identifier resolver chain for name lookup
  4263. // purposes.
  4264. SmallVector<NamedDecl*, 2> Chain;
  4265. Chain.push_back(Anon);
  4266. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4267. Invalid = true;
  4268. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4269. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4270. Decl *ManglingContextDecl;
  4271. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4272. NewVD->getDeclContext(), ManglingContextDecl)) {
  4273. Context.setManglingNumber(
  4274. NewVD, MCtx->getManglingNumber(
  4275. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4276. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4277. }
  4278. }
  4279. }
  4280. if (Invalid)
  4281. Anon->setInvalidDecl();
  4282. return Anon;
  4283. }
  4284. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4285. /// Microsoft C anonymous structure.
  4286. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4287. /// Example:
  4288. ///
  4289. /// struct A { int a; };
  4290. /// struct B { struct A; int b; };
  4291. ///
  4292. /// void foo() {
  4293. /// B var;
  4294. /// var.a = 3;
  4295. /// }
  4296. ///
  4297. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4298. RecordDecl *Record) {
  4299. assert(Record && "expected a record!");
  4300. // Mock up a declarator.
  4301. Declarator Dc(DS, Declarator::TypeNameContext);
  4302. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4303. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4304. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4305. QualType RecTy = Context.getTypeDeclType(Record);
  4306. // Create a declaration for this anonymous struct.
  4307. NamedDecl *Anon = FieldDecl::Create(Context,
  4308. ParentDecl,
  4309. DS.getLocStart(),
  4310. DS.getLocStart(),
  4311. /*IdentifierInfo=*/nullptr,
  4312. RecTy,
  4313. TInfo,
  4314. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4315. /*InitStyle=*/ICIS_NoInit);
  4316. Anon->setImplicit();
  4317. // Add the anonymous struct object to the current context.
  4318. CurContext->addDecl(Anon);
  4319. // Inject the members of the anonymous struct into the current
  4320. // context and into the identifier resolver chain for name lookup
  4321. // purposes.
  4322. SmallVector<NamedDecl*, 2> Chain;
  4323. Chain.push_back(Anon);
  4324. RecordDecl *RecordDef = Record->getDefinition();
  4325. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4326. diag::err_field_incomplete) ||
  4327. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4328. AS_none, Chain)) {
  4329. Anon->setInvalidDecl();
  4330. ParentDecl->setInvalidDecl();
  4331. }
  4332. return Anon;
  4333. }
  4334. /// GetNameForDeclarator - Determine the full declaration name for the
  4335. /// given Declarator.
  4336. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4337. return GetNameFromUnqualifiedId(D.getName());
  4338. }
  4339. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  4340. DeclarationNameInfo
  4341. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4342. DeclarationNameInfo NameInfo;
  4343. NameInfo.setLoc(Name.StartLocation);
  4344. switch (Name.getKind()) {
  4345. case UnqualifiedId::IK_ImplicitSelfParam:
  4346. case UnqualifiedId::IK_Identifier:
  4347. NameInfo.setName(Name.Identifier);
  4348. NameInfo.setLoc(Name.StartLocation);
  4349. return NameInfo;
  4350. case UnqualifiedId::IK_DeductionGuideName: {
  4351. // C++ [temp.deduct.guide]p3:
  4352. // The simple-template-id shall name a class template specialization.
  4353. // The template-name shall be the same identifier as the template-name
  4354. // of the simple-template-id.
  4355. // These together intend to imply that the template-name shall name a
  4356. // class template.
  4357. // FIXME: template<typename T> struct X {};
  4358. // template<typename T> using Y = X<T>;
  4359. // Y(int) -> Y<int>;
  4360. // satisfies these rules but does not name a class template.
  4361. TemplateName TN = Name.TemplateName.get().get();
  4362. auto *Template = TN.getAsTemplateDecl();
  4363. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4364. Diag(Name.StartLocation,
  4365. diag::err_deduction_guide_name_not_class_template)
  4366. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4367. if (Template)
  4368. Diag(Template->getLocation(), diag::note_template_decl_here);
  4369. return DeclarationNameInfo();
  4370. }
  4371. NameInfo.setName(
  4372. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4373. NameInfo.setLoc(Name.StartLocation);
  4374. return NameInfo;
  4375. }
  4376. case UnqualifiedId::IK_OperatorFunctionId:
  4377. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4378. Name.OperatorFunctionId.Operator));
  4379. NameInfo.setLoc(Name.StartLocation);
  4380. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4381. = Name.OperatorFunctionId.SymbolLocations[0];
  4382. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4383. = Name.EndLocation.getRawEncoding();
  4384. return NameInfo;
  4385. case UnqualifiedId::IK_LiteralOperatorId:
  4386. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4387. Name.Identifier));
  4388. NameInfo.setLoc(Name.StartLocation);
  4389. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4390. return NameInfo;
  4391. case UnqualifiedId::IK_ConversionFunctionId: {
  4392. TypeSourceInfo *TInfo;
  4393. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4394. if (Ty.isNull())
  4395. return DeclarationNameInfo();
  4396. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4397. Context.getCanonicalType(Ty)));
  4398. NameInfo.setLoc(Name.StartLocation);
  4399. NameInfo.setNamedTypeInfo(TInfo);
  4400. return NameInfo;
  4401. }
  4402. case UnqualifiedId::IK_ConstructorName: {
  4403. TypeSourceInfo *TInfo;
  4404. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4405. if (Ty.isNull())
  4406. return DeclarationNameInfo();
  4407. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4408. Context.getCanonicalType(Ty)));
  4409. NameInfo.setLoc(Name.StartLocation);
  4410. NameInfo.setNamedTypeInfo(TInfo);
  4411. return NameInfo;
  4412. }
  4413. case UnqualifiedId::IK_ConstructorTemplateId: {
  4414. // In well-formed code, we can only have a constructor
  4415. // template-id that refers to the current context, so go there
  4416. // to find the actual type being constructed.
  4417. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4418. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4419. return DeclarationNameInfo();
  4420. // Determine the type of the class being constructed.
  4421. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4422. // FIXME: Check two things: that the template-id names the same type as
  4423. // CurClassType, and that the template-id does not occur when the name
  4424. // was qualified.
  4425. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4426. Context.getCanonicalType(CurClassType)));
  4427. NameInfo.setLoc(Name.StartLocation);
  4428. // FIXME: should we retrieve TypeSourceInfo?
  4429. NameInfo.setNamedTypeInfo(nullptr);
  4430. return NameInfo;
  4431. }
  4432. case UnqualifiedId::IK_DestructorName: {
  4433. TypeSourceInfo *TInfo;
  4434. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4435. if (Ty.isNull())
  4436. return DeclarationNameInfo();
  4437. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4438. Context.getCanonicalType(Ty)));
  4439. NameInfo.setLoc(Name.StartLocation);
  4440. NameInfo.setNamedTypeInfo(TInfo);
  4441. return NameInfo;
  4442. }
  4443. case UnqualifiedId::IK_TemplateId: {
  4444. TemplateName TName = Name.TemplateId->Template.get();
  4445. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4446. return Context.getNameForTemplate(TName, TNameLoc);
  4447. }
  4448. } // switch (Name.getKind())
  4449. llvm_unreachable("Unknown name kind");
  4450. }
  4451. static QualType getCoreType(QualType Ty) {
  4452. do {
  4453. if (Ty->isPointerType() || Ty->isReferenceType())
  4454. Ty = Ty->getPointeeType();
  4455. else if (Ty->isArrayType())
  4456. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4457. else
  4458. return Ty.withoutLocalFastQualifiers();
  4459. } while (true);
  4460. }
  4461. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4462. /// and Definition have "nearly" matching parameters. This heuristic is
  4463. /// used to improve diagnostics in the case where an out-of-line function
  4464. /// definition doesn't match any declaration within the class or namespace.
  4465. /// Also sets Params to the list of indices to the parameters that differ
  4466. /// between the declaration and the definition. If hasSimilarParameters
  4467. /// returns true and Params is empty, then all of the parameters match.
  4468. static bool hasSimilarParameters(ASTContext &Context,
  4469. FunctionDecl *Declaration,
  4470. FunctionDecl *Definition,
  4471. SmallVectorImpl<unsigned> &Params) {
  4472. Params.clear();
  4473. if (Declaration->param_size() != Definition->param_size())
  4474. return false;
  4475. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4476. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4477. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4478. // The parameter types are identical
  4479. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4480. continue;
  4481. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4482. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4483. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4484. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4485. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4486. (DeclTyName && DeclTyName == DefTyName))
  4487. Params.push_back(Idx);
  4488. else // The two parameters aren't even close
  4489. return false;
  4490. }
  4491. return true;
  4492. }
  4493. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4494. /// declarator needs to be rebuilt in the current instantiation.
  4495. /// Any bits of declarator which appear before the name are valid for
  4496. /// consideration here. That's specifically the type in the decl spec
  4497. /// and the base type in any member-pointer chunks.
  4498. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4499. DeclarationName Name) {
  4500. // The types we specifically need to rebuild are:
  4501. // - typenames, typeofs, and decltypes
  4502. // - types which will become injected class names
  4503. // Of course, we also need to rebuild any type referencing such a
  4504. // type. It's safest to just say "dependent", but we call out a
  4505. // few cases here.
  4506. DeclSpec &DS = D.getMutableDeclSpec();
  4507. switch (DS.getTypeSpecType()) {
  4508. case DeclSpec::TST_typename:
  4509. case DeclSpec::TST_typeofType:
  4510. case DeclSpec::TST_underlyingType:
  4511. case DeclSpec::TST_atomic: {
  4512. // Grab the type from the parser.
  4513. TypeSourceInfo *TSI = nullptr;
  4514. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4515. if (T.isNull() || !T->isDependentType()) break;
  4516. // Make sure there's a type source info. This isn't really much
  4517. // of a waste; most dependent types should have type source info
  4518. // attached already.
  4519. if (!TSI)
  4520. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4521. // Rebuild the type in the current instantiation.
  4522. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4523. if (!TSI) return true;
  4524. // Store the new type back in the decl spec.
  4525. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4526. DS.UpdateTypeRep(LocType);
  4527. break;
  4528. }
  4529. case DeclSpec::TST_decltype:
  4530. case DeclSpec::TST_typeofExpr: {
  4531. Expr *E = DS.getRepAsExpr();
  4532. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4533. if (Result.isInvalid()) return true;
  4534. DS.UpdateExprRep(Result.get());
  4535. break;
  4536. }
  4537. default:
  4538. // Nothing to do for these decl specs.
  4539. break;
  4540. }
  4541. // It doesn't matter what order we do this in.
  4542. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4543. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4544. // The only type information in the declarator which can come
  4545. // before the declaration name is the base type of a member
  4546. // pointer.
  4547. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4548. continue;
  4549. // Rebuild the scope specifier in-place.
  4550. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4551. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4552. return true;
  4553. }
  4554. return false;
  4555. }
  4556. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4557. D.setFunctionDefinitionKind(FDK_Declaration);
  4558. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4559. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4560. Dcl && Dcl->getDeclContext()->isFileContext())
  4561. Dcl->setTopLevelDeclInObjCContainer();
  4562. if (getLangOpts().OpenCL)
  4563. setCurrentOpenCLExtensionForDecl(Dcl);
  4564. return Dcl;
  4565. }
  4566. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4567. /// If T is the name of a class, then each of the following shall have a
  4568. /// name different from T:
  4569. /// - every static data member of class T;
  4570. /// - every member function of class T
  4571. /// - every member of class T that is itself a type;
  4572. /// \returns true if the declaration name violates these rules.
  4573. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4574. DeclarationNameInfo NameInfo) {
  4575. DeclarationName Name = NameInfo.getName();
  4576. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4577. while (Record && Record->isAnonymousStructOrUnion())
  4578. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4579. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4580. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4581. return true;
  4582. }
  4583. return false;
  4584. }
  4585. /// \brief Diagnose a declaration whose declarator-id has the given
  4586. /// nested-name-specifier.
  4587. ///
  4588. /// \param SS The nested-name-specifier of the declarator-id.
  4589. ///
  4590. /// \param DC The declaration context to which the nested-name-specifier
  4591. /// resolves.
  4592. ///
  4593. /// \param Name The name of the entity being declared.
  4594. ///
  4595. /// \param Loc The location of the name of the entity being declared.
  4596. ///
  4597. /// \returns true if we cannot safely recover from this error, false otherwise.
  4598. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4599. DeclarationName Name,
  4600. SourceLocation Loc) {
  4601. DeclContext *Cur = CurContext;
  4602. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4603. Cur = Cur->getParent();
  4604. // If the user provided a superfluous scope specifier that refers back to the
  4605. // class in which the entity is already declared, diagnose and ignore it.
  4606. //
  4607. // class X {
  4608. // void X::f();
  4609. // };
  4610. //
  4611. // Note, it was once ill-formed to give redundant qualification in all
  4612. // contexts, but that rule was removed by DR482.
  4613. if (Cur->Equals(DC)) {
  4614. if (Cur->isRecord()) {
  4615. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4616. : diag::err_member_extra_qualification)
  4617. << Name << FixItHint::CreateRemoval(SS.getRange());
  4618. SS.clear();
  4619. } else {
  4620. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4621. }
  4622. return false;
  4623. }
  4624. // Check whether the qualifying scope encloses the scope of the original
  4625. // declaration.
  4626. if (!Cur->Encloses(DC)) {
  4627. if (Cur->isRecord())
  4628. Diag(Loc, diag::err_member_qualification)
  4629. << Name << SS.getRange();
  4630. else if (isa<TranslationUnitDecl>(DC))
  4631. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4632. << Name << SS.getRange();
  4633. else if (isa<FunctionDecl>(Cur))
  4634. Diag(Loc, diag::err_invalid_declarator_in_function)
  4635. << Name << SS.getRange();
  4636. else if (isa<BlockDecl>(Cur))
  4637. Diag(Loc, diag::err_invalid_declarator_in_block)
  4638. << Name << SS.getRange();
  4639. else
  4640. Diag(Loc, diag::err_invalid_declarator_scope)
  4641. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4642. return true;
  4643. }
  4644. if (Cur->isRecord()) {
  4645. // Cannot qualify members within a class.
  4646. Diag(Loc, diag::err_member_qualification)
  4647. << Name << SS.getRange();
  4648. SS.clear();
  4649. // C++ constructors and destructors with incorrect scopes can break
  4650. // our AST invariants by having the wrong underlying types. If
  4651. // that's the case, then drop this declaration entirely.
  4652. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4653. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4654. !Context.hasSameType(Name.getCXXNameType(),
  4655. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4656. return true;
  4657. return false;
  4658. }
  4659. // C++11 [dcl.meaning]p1:
  4660. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4661. // not begin with a decltype-specifer"
  4662. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4663. while (SpecLoc.getPrefix())
  4664. SpecLoc = SpecLoc.getPrefix();
  4665. if (dyn_cast_or_null<DecltypeType>(
  4666. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4667. Diag(Loc, diag::err_decltype_in_declarator)
  4668. << SpecLoc.getTypeLoc().getSourceRange();
  4669. return false;
  4670. }
  4671. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4672. MultiTemplateParamsArg TemplateParamLists) {
  4673. // TODO: consider using NameInfo for diagnostic.
  4674. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4675. DeclarationName Name = NameInfo.getName();
  4676. // All of these full declarators require an identifier. If it doesn't have
  4677. // one, the ParsedFreeStandingDeclSpec action should be used.
  4678. if (D.isDecompositionDeclarator()) {
  4679. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4680. } else if (!Name) {
  4681. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4682. Diag(D.getDeclSpec().getLocStart(),
  4683. diag::err_declarator_need_ident)
  4684. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4685. return nullptr;
  4686. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4687. return nullptr;
  4688. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4689. // we find one that is.
  4690. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4691. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4692. S = S->getParent();
  4693. DeclContext *DC = CurContext;
  4694. if (D.getCXXScopeSpec().isInvalid())
  4695. D.setInvalidType();
  4696. else if (D.getCXXScopeSpec().isSet()) {
  4697. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4698. UPPC_DeclarationQualifier))
  4699. return nullptr;
  4700. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4701. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4702. if (!DC || isa<EnumDecl>(DC)) {
  4703. // If we could not compute the declaration context, it's because the
  4704. // declaration context is dependent but does not refer to a class,
  4705. // class template, or class template partial specialization. Complain
  4706. // and return early, to avoid the coming semantic disaster.
  4707. Diag(D.getIdentifierLoc(),
  4708. diag::err_template_qualified_declarator_no_match)
  4709. << D.getCXXScopeSpec().getScopeRep()
  4710. << D.getCXXScopeSpec().getRange();
  4711. return nullptr;
  4712. }
  4713. bool IsDependentContext = DC->isDependentContext();
  4714. if (!IsDependentContext &&
  4715. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4716. return nullptr;
  4717. // If a class is incomplete, do not parse entities inside it.
  4718. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4719. Diag(D.getIdentifierLoc(),
  4720. diag::err_member_def_undefined_record)
  4721. << Name << DC << D.getCXXScopeSpec().getRange();
  4722. return nullptr;
  4723. }
  4724. if (!D.getDeclSpec().isFriendSpecified()) {
  4725. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4726. Name, D.getIdentifierLoc())) {
  4727. if (DC->isRecord())
  4728. return nullptr;
  4729. D.setInvalidType();
  4730. }
  4731. }
  4732. // Check whether we need to rebuild the type of the given
  4733. // declaration in the current instantiation.
  4734. if (EnteringContext && IsDependentContext &&
  4735. TemplateParamLists.size() != 0) {
  4736. ContextRAII SavedContext(*this, DC);
  4737. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4738. D.setInvalidType();
  4739. }
  4740. }
  4741. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4742. QualType R = TInfo->getType();
  4743. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4744. UPPC_DeclarationType))
  4745. D.setInvalidType();
  4746. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4747. forRedeclarationInCurContext());
  4748. // See if this is a redefinition of a variable in the same scope.
  4749. if (!D.getCXXScopeSpec().isSet()) {
  4750. bool IsLinkageLookup = false;
  4751. bool CreateBuiltins = false;
  4752. // If the declaration we're planning to build will be a function
  4753. // or object with linkage, then look for another declaration with
  4754. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4755. //
  4756. // If the declaration we're planning to build will be declared with
  4757. // external linkage in the translation unit, create any builtin with
  4758. // the same name.
  4759. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4760. /* Do nothing*/;
  4761. else if (CurContext->isFunctionOrMethod() &&
  4762. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4763. R->isFunctionType())) {
  4764. IsLinkageLookup = true;
  4765. CreateBuiltins =
  4766. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4767. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4768. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4769. CreateBuiltins = true;
  4770. if (IsLinkageLookup) {
  4771. Previous.clear(LookupRedeclarationWithLinkage);
  4772. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4773. }
  4774. LookupName(Previous, S, CreateBuiltins);
  4775. } else { // Something like "int foo::x;"
  4776. LookupQualifiedName(Previous, DC);
  4777. // C++ [dcl.meaning]p1:
  4778. // When the declarator-id is qualified, the declaration shall refer to a
  4779. // previously declared member of the class or namespace to which the
  4780. // qualifier refers (or, in the case of a namespace, of an element of the
  4781. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4782. // thereof; [...]
  4783. //
  4784. // Note that we already checked the context above, and that we do not have
  4785. // enough information to make sure that Previous contains the declaration
  4786. // we want to match. For example, given:
  4787. //
  4788. // class X {
  4789. // void f();
  4790. // void f(float);
  4791. // };
  4792. //
  4793. // void X::f(int) { } // ill-formed
  4794. //
  4795. // In this case, Previous will point to the overload set
  4796. // containing the two f's declared in X, but neither of them
  4797. // matches.
  4798. // C++ [dcl.meaning]p1:
  4799. // [...] the member shall not merely have been introduced by a
  4800. // using-declaration in the scope of the class or namespace nominated by
  4801. // the nested-name-specifier of the declarator-id.
  4802. RemoveUsingDecls(Previous);
  4803. }
  4804. if (Previous.isSingleResult() &&
  4805. Previous.getFoundDecl()->isTemplateParameter()) {
  4806. // Maybe we will complain about the shadowed template parameter.
  4807. if (!D.isInvalidType())
  4808. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4809. Previous.getFoundDecl());
  4810. // Just pretend that we didn't see the previous declaration.
  4811. Previous.clear();
  4812. }
  4813. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4814. // Forget that the previous declaration is the injected-class-name.
  4815. Previous.clear();
  4816. // In C++, the previous declaration we find might be a tag type
  4817. // (class or enum). In this case, the new declaration will hide the
  4818. // tag type. Note that this applies to functions, function templates, and
  4819. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4820. if (Previous.isSingleTagDecl() &&
  4821. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4822. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4823. Previous.clear();
  4824. // Check that there are no default arguments other than in the parameters
  4825. // of a function declaration (C++ only).
  4826. if (getLangOpts().CPlusPlus)
  4827. CheckExtraCXXDefaultArguments(D);
  4828. if (D.getDeclSpec().isConceptSpecified()) {
  4829. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  4830. // applied only to the definition of a function template or variable
  4831. // template, declared in namespace scope
  4832. if (!TemplateParamLists.size()) {
  4833. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4834. diag:: err_concept_wrong_decl_kind);
  4835. return nullptr;
  4836. }
  4837. if (!DC->getRedeclContext()->isFileContext()) {
  4838. Diag(D.getIdentifierLoc(),
  4839. diag::err_concept_decls_may_only_appear_in_namespace_scope);
  4840. return nullptr;
  4841. }
  4842. }
  4843. NamedDecl *New;
  4844. bool AddToScope = true;
  4845. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4846. if (TemplateParamLists.size()) {
  4847. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4848. return nullptr;
  4849. }
  4850. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4851. } else if (R->isFunctionType()) {
  4852. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4853. TemplateParamLists,
  4854. AddToScope);
  4855. } else {
  4856. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4857. AddToScope);
  4858. }
  4859. if (!New)
  4860. return nullptr;
  4861. // If this has an identifier and is not a function template specialization,
  4862. // add it to the scope stack.
  4863. if (New->getDeclName() && AddToScope) {
  4864. // Only make a locally-scoped extern declaration visible if it is the first
  4865. // declaration of this entity. Qualified lookup for such an entity should
  4866. // only find this declaration if there is no visible declaration of it.
  4867. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4868. PushOnScopeChains(New, S, AddToContext);
  4869. if (!AddToContext)
  4870. CurContext->addHiddenDecl(New);
  4871. }
  4872. if (isInOpenMPDeclareTargetContext())
  4873. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4874. return New;
  4875. }
  4876. /// Helper method to turn variable array types into constant array
  4877. /// types in certain situations which would otherwise be errors (for
  4878. /// GCC compatibility).
  4879. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4880. ASTContext &Context,
  4881. bool &SizeIsNegative,
  4882. llvm::APSInt &Oversized) {
  4883. // This method tries to turn a variable array into a constant
  4884. // array even when the size isn't an ICE. This is necessary
  4885. // for compatibility with code that depends on gcc's buggy
  4886. // constant expression folding, like struct {char x[(int)(char*)2];}
  4887. SizeIsNegative = false;
  4888. Oversized = 0;
  4889. if (T->isDependentType())
  4890. return QualType();
  4891. QualifierCollector Qs;
  4892. const Type *Ty = Qs.strip(T);
  4893. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4894. QualType Pointee = PTy->getPointeeType();
  4895. QualType FixedType =
  4896. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4897. Oversized);
  4898. if (FixedType.isNull()) return FixedType;
  4899. FixedType = Context.getPointerType(FixedType);
  4900. return Qs.apply(Context, FixedType);
  4901. }
  4902. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4903. QualType Inner = PTy->getInnerType();
  4904. QualType FixedType =
  4905. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4906. Oversized);
  4907. if (FixedType.isNull()) return FixedType;
  4908. FixedType = Context.getParenType(FixedType);
  4909. return Qs.apply(Context, FixedType);
  4910. }
  4911. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4912. if (!VLATy)
  4913. return QualType();
  4914. // FIXME: We should probably handle this case
  4915. if (VLATy->getElementType()->isVariablyModifiedType())
  4916. return QualType();
  4917. llvm::APSInt Res;
  4918. if (!VLATy->getSizeExpr() ||
  4919. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4920. return QualType();
  4921. // Check whether the array size is negative.
  4922. if (Res.isSigned() && Res.isNegative()) {
  4923. SizeIsNegative = true;
  4924. return QualType();
  4925. }
  4926. // Check whether the array is too large to be addressed.
  4927. unsigned ActiveSizeBits
  4928. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4929. Res);
  4930. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4931. Oversized = Res;
  4932. return QualType();
  4933. }
  4934. return Context.getConstantArrayType(VLATy->getElementType(),
  4935. Res, ArrayType::Normal, 0);
  4936. }
  4937. static void
  4938. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4939. SrcTL = SrcTL.getUnqualifiedLoc();
  4940. DstTL = DstTL.getUnqualifiedLoc();
  4941. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4942. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4943. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4944. DstPTL.getPointeeLoc());
  4945. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4946. return;
  4947. }
  4948. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4949. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4950. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4951. DstPTL.getInnerLoc());
  4952. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4953. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4954. return;
  4955. }
  4956. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4957. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4958. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4959. TypeLoc DstElemTL = DstATL.getElementLoc();
  4960. DstElemTL.initializeFullCopy(SrcElemTL);
  4961. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4962. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4963. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4964. }
  4965. /// Helper method to turn variable array types into constant array
  4966. /// types in certain situations which would otherwise be errors (for
  4967. /// GCC compatibility).
  4968. static TypeSourceInfo*
  4969. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4970. ASTContext &Context,
  4971. bool &SizeIsNegative,
  4972. llvm::APSInt &Oversized) {
  4973. QualType FixedTy
  4974. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4975. SizeIsNegative, Oversized);
  4976. if (FixedTy.isNull())
  4977. return nullptr;
  4978. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4979. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4980. FixedTInfo->getTypeLoc());
  4981. return FixedTInfo;
  4982. }
  4983. /// \brief Register the given locally-scoped extern "C" declaration so
  4984. /// that it can be found later for redeclarations. We include any extern "C"
  4985. /// declaration that is not visible in the translation unit here, not just
  4986. /// function-scope declarations.
  4987. void
  4988. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4989. if (!getLangOpts().CPlusPlus &&
  4990. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4991. // Don't need to track declarations in the TU in C.
  4992. return;
  4993. // Note that we have a locally-scoped external with this name.
  4994. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4995. }
  4996. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4997. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4998. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4999. return Result.empty() ? nullptr : *Result.begin();
  5000. }
  5001. /// \brief Diagnose function specifiers on a declaration of an identifier that
  5002. /// does not identify a function.
  5003. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5004. // FIXME: We should probably indicate the identifier in question to avoid
  5005. // confusion for constructs like "virtual int a(), b;"
  5006. if (DS.isVirtualSpecified())
  5007. Diag(DS.getVirtualSpecLoc(),
  5008. diag::err_virtual_non_function);
  5009. if (DS.isExplicitSpecified())
  5010. Diag(DS.getExplicitSpecLoc(),
  5011. diag::err_explicit_non_function);
  5012. if (DS.isNoreturnSpecified())
  5013. Diag(DS.getNoreturnSpecLoc(),
  5014. diag::err_noreturn_non_function);
  5015. }
  5016. NamedDecl*
  5017. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5018. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5019. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5020. if (D.getCXXScopeSpec().isSet()) {
  5021. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5022. << D.getCXXScopeSpec().getRange();
  5023. D.setInvalidType();
  5024. // Pretend we didn't see the scope specifier.
  5025. DC = CurContext;
  5026. Previous.clear();
  5027. }
  5028. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5029. if (D.getDeclSpec().isInlineSpecified())
  5030. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5031. << getLangOpts().CPlusPlus1z;
  5032. if (D.getDeclSpec().isConstexprSpecified())
  5033. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5034. << 1;
  5035. if (D.getDeclSpec().isConceptSpecified())
  5036. Diag(D.getDeclSpec().getConceptSpecLoc(),
  5037. diag::err_concept_wrong_decl_kind);
  5038. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  5039. if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
  5040. Diag(D.getName().StartLocation,
  5041. diag::err_deduction_guide_invalid_specifier)
  5042. << "typedef";
  5043. else
  5044. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5045. << D.getName().getSourceRange();
  5046. return nullptr;
  5047. }
  5048. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5049. if (!NewTD) return nullptr;
  5050. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5051. ProcessDeclAttributes(S, NewTD, D);
  5052. CheckTypedefForVariablyModifiedType(S, NewTD);
  5053. bool Redeclaration = D.isRedeclaration();
  5054. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5055. D.setRedeclaration(Redeclaration);
  5056. return ND;
  5057. }
  5058. void
  5059. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5060. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5061. // then it shall have block scope.
  5062. // Note that variably modified types must be fixed before merging the decl so
  5063. // that redeclarations will match.
  5064. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5065. QualType T = TInfo->getType();
  5066. if (T->isVariablyModifiedType()) {
  5067. getCurFunction()->setHasBranchProtectedScope();
  5068. if (S->getFnParent() == nullptr) {
  5069. bool SizeIsNegative;
  5070. llvm::APSInt Oversized;
  5071. TypeSourceInfo *FixedTInfo =
  5072. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5073. SizeIsNegative,
  5074. Oversized);
  5075. if (FixedTInfo) {
  5076. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5077. NewTD->setTypeSourceInfo(FixedTInfo);
  5078. } else {
  5079. if (SizeIsNegative)
  5080. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5081. else if (T->isVariableArrayType())
  5082. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5083. else if (Oversized.getBoolValue())
  5084. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5085. << Oversized.toString(10);
  5086. else
  5087. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5088. NewTD->setInvalidDecl();
  5089. }
  5090. }
  5091. }
  5092. }
  5093. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5094. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5095. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5096. NamedDecl*
  5097. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5098. LookupResult &Previous, bool &Redeclaration) {
  5099. // Find the shadowed declaration before filtering for scope.
  5100. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5101. // Merge the decl with the existing one if appropriate. If the decl is
  5102. // in an outer scope, it isn't the same thing.
  5103. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5104. /*AllowInlineNamespace*/false);
  5105. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5106. if (!Previous.empty()) {
  5107. Redeclaration = true;
  5108. MergeTypedefNameDecl(S, NewTD, Previous);
  5109. }
  5110. if (ShadowedDecl && !Redeclaration)
  5111. CheckShadow(NewTD, ShadowedDecl, Previous);
  5112. // If this is the C FILE type, notify the AST context.
  5113. if (IdentifierInfo *II = NewTD->getIdentifier())
  5114. if (!NewTD->isInvalidDecl() &&
  5115. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5116. if (II->isStr("FILE"))
  5117. Context.setFILEDecl(NewTD);
  5118. else if (II->isStr("jmp_buf"))
  5119. Context.setjmp_bufDecl(NewTD);
  5120. else if (II->isStr("sigjmp_buf"))
  5121. Context.setsigjmp_bufDecl(NewTD);
  5122. else if (II->isStr("ucontext_t"))
  5123. Context.setucontext_tDecl(NewTD);
  5124. }
  5125. return NewTD;
  5126. }
  5127. /// \brief Determines whether the given declaration is an out-of-scope
  5128. /// previous declaration.
  5129. ///
  5130. /// This routine should be invoked when name lookup has found a
  5131. /// previous declaration (PrevDecl) that is not in the scope where a
  5132. /// new declaration by the same name is being introduced. If the new
  5133. /// declaration occurs in a local scope, previous declarations with
  5134. /// linkage may still be considered previous declarations (C99
  5135. /// 6.2.2p4-5, C++ [basic.link]p6).
  5136. ///
  5137. /// \param PrevDecl the previous declaration found by name
  5138. /// lookup
  5139. ///
  5140. /// \param DC the context in which the new declaration is being
  5141. /// declared.
  5142. ///
  5143. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5144. /// for a new delcaration with the same name.
  5145. static bool
  5146. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5147. ASTContext &Context) {
  5148. if (!PrevDecl)
  5149. return false;
  5150. if (!PrevDecl->hasLinkage())
  5151. return false;
  5152. if (Context.getLangOpts().CPlusPlus) {
  5153. // C++ [basic.link]p6:
  5154. // If there is a visible declaration of an entity with linkage
  5155. // having the same name and type, ignoring entities declared
  5156. // outside the innermost enclosing namespace scope, the block
  5157. // scope declaration declares that same entity and receives the
  5158. // linkage of the previous declaration.
  5159. DeclContext *OuterContext = DC->getRedeclContext();
  5160. if (!OuterContext->isFunctionOrMethod())
  5161. // This rule only applies to block-scope declarations.
  5162. return false;
  5163. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5164. if (PrevOuterContext->isRecord())
  5165. // We found a member function: ignore it.
  5166. return false;
  5167. // Find the innermost enclosing namespace for the new and
  5168. // previous declarations.
  5169. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5170. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5171. // The previous declaration is in a different namespace, so it
  5172. // isn't the same function.
  5173. if (!OuterContext->Equals(PrevOuterContext))
  5174. return false;
  5175. }
  5176. return true;
  5177. }
  5178. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  5179. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5180. if (!SS.isSet()) return;
  5181. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  5182. }
  5183. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5184. QualType type = decl->getType();
  5185. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5186. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5187. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5188. unsigned kind = -1U;
  5189. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5190. if (var->hasAttr<BlocksAttr>())
  5191. kind = 0; // __block
  5192. else if (!var->hasLocalStorage())
  5193. kind = 1; // global
  5194. } else if (isa<ObjCIvarDecl>(decl)) {
  5195. kind = 3; // ivar
  5196. } else if (isa<FieldDecl>(decl)) {
  5197. kind = 2; // field
  5198. }
  5199. if (kind != -1U) {
  5200. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5201. << kind;
  5202. }
  5203. } else if (lifetime == Qualifiers::OCL_None) {
  5204. // Try to infer lifetime.
  5205. if (!type->isObjCLifetimeType())
  5206. return false;
  5207. lifetime = type->getObjCARCImplicitLifetime();
  5208. type = Context.getLifetimeQualifiedType(type, lifetime);
  5209. decl->setType(type);
  5210. }
  5211. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5212. // Thread-local variables cannot have lifetime.
  5213. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5214. var->getTLSKind()) {
  5215. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5216. << var->getType();
  5217. return true;
  5218. }
  5219. }
  5220. return false;
  5221. }
  5222. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5223. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5224. // the wrong linkage.
  5225. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5226. // 'weak' only applies to declarations with external linkage.
  5227. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5228. if (!ND.isExternallyVisible()) {
  5229. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5230. ND.dropAttr<WeakAttr>();
  5231. }
  5232. }
  5233. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5234. if (ND.isExternallyVisible()) {
  5235. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5236. ND.dropAttr<WeakRefAttr>();
  5237. ND.dropAttr<AliasAttr>();
  5238. }
  5239. }
  5240. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5241. if (VD->hasInit()) {
  5242. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5243. assert(VD->isThisDeclarationADefinition() &&
  5244. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5245. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5246. VD->dropAttr<AliasAttr>();
  5247. }
  5248. }
  5249. }
  5250. // 'selectany' only applies to externally visible variable declarations.
  5251. // It does not apply to functions.
  5252. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5253. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5254. S.Diag(Attr->getLocation(),
  5255. diag::err_attribute_selectany_non_extern_data);
  5256. ND.dropAttr<SelectAnyAttr>();
  5257. }
  5258. }
  5259. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5260. // dll attributes require external linkage. Static locals may have external
  5261. // linkage but still cannot be explicitly imported or exported.
  5262. auto *VD = dyn_cast<VarDecl>(&ND);
  5263. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  5264. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5265. << &ND << Attr;
  5266. ND.setInvalidDecl();
  5267. }
  5268. }
  5269. // Virtual functions cannot be marked as 'notail'.
  5270. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5271. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5272. if (MD->isVirtual()) {
  5273. S.Diag(ND.getLocation(),
  5274. diag::err_invalid_attribute_on_virtual_function)
  5275. << Attr;
  5276. ND.dropAttr<NotTailCalledAttr>();
  5277. }
  5278. }
  5279. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5280. NamedDecl *NewDecl,
  5281. bool IsSpecialization,
  5282. bool IsDefinition) {
  5283. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5284. return;
  5285. bool IsTemplate = false;
  5286. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5287. OldDecl = OldTD->getTemplatedDecl();
  5288. IsTemplate = true;
  5289. if (!IsSpecialization)
  5290. IsDefinition = false;
  5291. }
  5292. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5293. NewDecl = NewTD->getTemplatedDecl();
  5294. IsTemplate = true;
  5295. }
  5296. if (!OldDecl || !NewDecl)
  5297. return;
  5298. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5299. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5300. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5301. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5302. // dllimport and dllexport are inheritable attributes so we have to exclude
  5303. // inherited attribute instances.
  5304. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5305. (NewExportAttr && !NewExportAttr->isInherited());
  5306. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5307. // the only exception being explicit specializations.
  5308. // Implicitly generated declarations are also excluded for now because there
  5309. // is no other way to switch these to use dllimport or dllexport.
  5310. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5311. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5312. // Allow with a warning for free functions and global variables.
  5313. bool JustWarn = false;
  5314. if (!OldDecl->isCXXClassMember()) {
  5315. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5316. if (VD && !VD->getDescribedVarTemplate())
  5317. JustWarn = true;
  5318. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5319. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5320. JustWarn = true;
  5321. }
  5322. // We cannot change a declaration that's been used because IR has already
  5323. // been emitted. Dllimported functions will still work though (modulo
  5324. // address equality) as they can use the thunk.
  5325. if (OldDecl->isUsed())
  5326. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5327. JustWarn = false;
  5328. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5329. : diag::err_attribute_dll_redeclaration;
  5330. S.Diag(NewDecl->getLocation(), DiagID)
  5331. << NewDecl
  5332. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5333. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5334. if (!JustWarn) {
  5335. NewDecl->setInvalidDecl();
  5336. return;
  5337. }
  5338. }
  5339. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5340. // exceptions being inline function definitions (except for function
  5341. // templates), local extern declarations, qualified friend declarations or
  5342. // special MSVC extension: in the last case, the declaration is treated as if
  5343. // it were marked dllexport.
  5344. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5345. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5346. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5347. // Ignore static data because out-of-line definitions are diagnosed
  5348. // separately.
  5349. IsStaticDataMember = VD->isStaticDataMember();
  5350. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5351. VarDecl::DeclarationOnly;
  5352. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5353. IsInline = FD->isInlined();
  5354. IsQualifiedFriend = FD->getQualifier() &&
  5355. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5356. }
  5357. if (OldImportAttr && !HasNewAttr &&
  5358. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5359. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5360. if (IsMicrosoft && IsDefinition) {
  5361. S.Diag(NewDecl->getLocation(),
  5362. diag::warn_redeclaration_without_import_attribute)
  5363. << NewDecl;
  5364. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5365. NewDecl->dropAttr<DLLImportAttr>();
  5366. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5367. NewImportAttr->getRange(), S.Context,
  5368. NewImportAttr->getSpellingListIndex()));
  5369. } else {
  5370. S.Diag(NewDecl->getLocation(),
  5371. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5372. << NewDecl << OldImportAttr;
  5373. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5374. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5375. OldDecl->dropAttr<DLLImportAttr>();
  5376. NewDecl->dropAttr<DLLImportAttr>();
  5377. }
  5378. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5379. // In MinGW, seeing a function declared inline drops the dllimport
  5380. // attribute.
  5381. OldDecl->dropAttr<DLLImportAttr>();
  5382. NewDecl->dropAttr<DLLImportAttr>();
  5383. S.Diag(NewDecl->getLocation(),
  5384. diag::warn_dllimport_dropped_from_inline_function)
  5385. << NewDecl << OldImportAttr;
  5386. }
  5387. // A specialization of a class template member function is processed here
  5388. // since it's a redeclaration. If the parent class is dllexport, the
  5389. // specialization inherits that attribute. This doesn't happen automatically
  5390. // since the parent class isn't instantiated until later.
  5391. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5392. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5393. !NewImportAttr && !NewExportAttr) {
  5394. if (const DLLExportAttr *ParentExportAttr =
  5395. MD->getParent()->getAttr<DLLExportAttr>()) {
  5396. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5397. NewAttr->setInherited(true);
  5398. NewDecl->addAttr(NewAttr);
  5399. }
  5400. }
  5401. }
  5402. }
  5403. /// Given that we are within the definition of the given function,
  5404. /// will that definition behave like C99's 'inline', where the
  5405. /// definition is discarded except for optimization purposes?
  5406. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5407. // Try to avoid calling GetGVALinkageForFunction.
  5408. // All cases of this require the 'inline' keyword.
  5409. if (!FD->isInlined()) return false;
  5410. // This is only possible in C++ with the gnu_inline attribute.
  5411. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5412. return false;
  5413. // Okay, go ahead and call the relatively-more-expensive function.
  5414. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5415. }
  5416. /// Determine whether a variable is extern "C" prior to attaching
  5417. /// an initializer. We can't just call isExternC() here, because that
  5418. /// will also compute and cache whether the declaration is externally
  5419. /// visible, which might change when we attach the initializer.
  5420. ///
  5421. /// This can only be used if the declaration is known to not be a
  5422. /// redeclaration of an internal linkage declaration.
  5423. ///
  5424. /// For instance:
  5425. ///
  5426. /// auto x = []{};
  5427. ///
  5428. /// Attaching the initializer here makes this declaration not externally
  5429. /// visible, because its type has internal linkage.
  5430. ///
  5431. /// FIXME: This is a hack.
  5432. template<typename T>
  5433. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5434. if (S.getLangOpts().CPlusPlus) {
  5435. // In C++, the overloadable attribute negates the effects of extern "C".
  5436. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5437. return false;
  5438. // So do CUDA's host/device attributes.
  5439. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5440. D->template hasAttr<CUDAHostAttr>()))
  5441. return false;
  5442. }
  5443. return D->isExternC();
  5444. }
  5445. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5446. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5447. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
  5448. return VD->hasExternalStorage();
  5449. if (DC->isFileContext())
  5450. return true;
  5451. if (DC->isRecord())
  5452. return false;
  5453. llvm_unreachable("Unexpected context");
  5454. }
  5455. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5456. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5457. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5458. isa<OMPDeclareReductionDecl>(DC))
  5459. return true;
  5460. if (DC->isRecord())
  5461. return false;
  5462. llvm_unreachable("Unexpected context");
  5463. }
  5464. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  5465. AttributeList::Kind Kind) {
  5466. for (const AttributeList *L = AttrList; L; L = L->getNext())
  5467. if (L->getKind() == Kind)
  5468. return true;
  5469. return false;
  5470. }
  5471. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5472. AttributeList::Kind Kind) {
  5473. // Check decl attributes on the DeclSpec.
  5474. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  5475. return true;
  5476. // Walk the declarator structure, checking decl attributes that were in a type
  5477. // position to the decl itself.
  5478. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5479. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  5480. return true;
  5481. }
  5482. // Finally, check attributes on the decl itself.
  5483. return hasParsedAttr(S, PD.getAttributes(), Kind);
  5484. }
  5485. /// Adjust the \c DeclContext for a function or variable that might be a
  5486. /// function-local external declaration.
  5487. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5488. if (!DC->isFunctionOrMethod())
  5489. return false;
  5490. // If this is a local extern function or variable declared within a function
  5491. // template, don't add it into the enclosing namespace scope until it is
  5492. // instantiated; it might have a dependent type right now.
  5493. if (DC->isDependentContext())
  5494. return true;
  5495. // C++11 [basic.link]p7:
  5496. // When a block scope declaration of an entity with linkage is not found to
  5497. // refer to some other declaration, then that entity is a member of the
  5498. // innermost enclosing namespace.
  5499. //
  5500. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5501. // semantically-enclosing namespace, not a lexically-enclosing one.
  5502. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5503. DC = DC->getParent();
  5504. return true;
  5505. }
  5506. /// \brief Returns true if given declaration has external C language linkage.
  5507. static bool isDeclExternC(const Decl *D) {
  5508. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5509. return FD->isExternC();
  5510. if (const auto *VD = dyn_cast<VarDecl>(D))
  5511. return VD->isExternC();
  5512. llvm_unreachable("Unknown type of decl!");
  5513. }
  5514. NamedDecl *Sema::ActOnVariableDeclarator(
  5515. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5516. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5517. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5518. QualType R = TInfo->getType();
  5519. DeclarationName Name = GetNameForDeclarator(D).getName();
  5520. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5521. if (D.isDecompositionDeclarator()) {
  5522. // Take the name of the first declarator as our name for diagnostic
  5523. // purposes.
  5524. auto &Decomp = D.getDecompositionDeclarator();
  5525. if (!Decomp.bindings().empty()) {
  5526. II = Decomp.bindings()[0].Name;
  5527. Name = II;
  5528. }
  5529. } else if (!II) {
  5530. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5531. return nullptr;
  5532. }
  5533. if (getLangOpts().OpenCL) {
  5534. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5535. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5536. // argument.
  5537. if (R->isImageType() || R->isPipeType()) {
  5538. Diag(D.getIdentifierLoc(),
  5539. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5540. << R;
  5541. D.setInvalidType();
  5542. return nullptr;
  5543. }
  5544. // OpenCL v1.2 s6.9.r:
  5545. // The event type cannot be used to declare a program scope variable.
  5546. // OpenCL v2.0 s6.9.q:
  5547. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5548. if (NULL == S->getParent()) {
  5549. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5550. Diag(D.getIdentifierLoc(),
  5551. diag::err_invalid_type_for_program_scope_var) << R;
  5552. D.setInvalidType();
  5553. return nullptr;
  5554. }
  5555. }
  5556. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5557. QualType NR = R;
  5558. while (NR->isPointerType()) {
  5559. if (NR->isFunctionPointerType()) {
  5560. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5561. D.setInvalidType();
  5562. break;
  5563. }
  5564. NR = NR->getPointeeType();
  5565. }
  5566. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5567. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5568. // half array type (unless the cl_khr_fp16 extension is enabled).
  5569. if (Context.getBaseElementType(R)->isHalfType()) {
  5570. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5571. D.setInvalidType();
  5572. }
  5573. }
  5574. if (R->isSamplerT()) {
  5575. // OpenCL v1.2 s6.9.b p4:
  5576. // The sampler type cannot be used with the __local and __global address
  5577. // space qualifiers.
  5578. if (R.getAddressSpace() == LangAS::opencl_local ||
  5579. R.getAddressSpace() == LangAS::opencl_global) {
  5580. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5581. }
  5582. // OpenCL v1.2 s6.12.14.1:
  5583. // A global sampler must be declared with either the constant address
  5584. // space qualifier or with the const qualifier.
  5585. if (DC->isTranslationUnit() &&
  5586. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5587. R.isConstQualified())) {
  5588. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5589. D.setInvalidType();
  5590. }
  5591. }
  5592. // OpenCL v1.2 s6.9.r:
  5593. // The event type cannot be used with the __local, __constant and __global
  5594. // address space qualifiers.
  5595. if (R->isEventT()) {
  5596. if (R.getAddressSpace() != LangAS::opencl_private) {
  5597. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5598. D.setInvalidType();
  5599. }
  5600. }
  5601. }
  5602. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5603. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5604. // dllimport globals without explicit storage class are treated as extern. We
  5605. // have to change the storage class this early to get the right DeclContext.
  5606. if (SC == SC_None && !DC->isRecord() &&
  5607. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  5608. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  5609. SC = SC_Extern;
  5610. DeclContext *OriginalDC = DC;
  5611. bool IsLocalExternDecl = SC == SC_Extern &&
  5612. adjustContextForLocalExternDecl(DC);
  5613. if (SCSpec == DeclSpec::SCS_mutable) {
  5614. // mutable can only appear on non-static class members, so it's always
  5615. // an error here
  5616. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5617. D.setInvalidType();
  5618. SC = SC_None;
  5619. }
  5620. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5621. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5622. D.getDeclSpec().getStorageClassSpecLoc())) {
  5623. // In C++11, the 'register' storage class specifier is deprecated.
  5624. // Suppress the warning in system macros, it's used in macros in some
  5625. // popular C system headers, such as in glibc's htonl() macro.
  5626. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5627. getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
  5628. : diag::warn_deprecated_register)
  5629. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5630. }
  5631. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5632. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5633. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5634. // appear in the declaration specifiers in an external declaration.
  5635. // Global Register+Asm is a GNU extension we support.
  5636. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5637. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5638. D.setInvalidType();
  5639. }
  5640. }
  5641. bool IsMemberSpecialization = false;
  5642. bool IsVariableTemplateSpecialization = false;
  5643. bool IsPartialSpecialization = false;
  5644. bool IsVariableTemplate = false;
  5645. VarDecl *NewVD = nullptr;
  5646. VarTemplateDecl *NewTemplate = nullptr;
  5647. TemplateParameterList *TemplateParams = nullptr;
  5648. if (!getLangOpts().CPlusPlus) {
  5649. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5650. D.getIdentifierLoc(), II,
  5651. R, TInfo, SC);
  5652. if (R->getContainedDeducedType())
  5653. ParsingInitForAutoVars.insert(NewVD);
  5654. if (D.isInvalidType())
  5655. NewVD->setInvalidDecl();
  5656. } else {
  5657. bool Invalid = false;
  5658. if (DC->isRecord() && !CurContext->isRecord()) {
  5659. // This is an out-of-line definition of a static data member.
  5660. switch (SC) {
  5661. case SC_None:
  5662. break;
  5663. case SC_Static:
  5664. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5665. diag::err_static_out_of_line)
  5666. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5667. break;
  5668. case SC_Auto:
  5669. case SC_Register:
  5670. case SC_Extern:
  5671. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5672. // to names of variables declared in a block or to function parameters.
  5673. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5674. // of class members
  5675. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5676. diag::err_storage_class_for_static_member)
  5677. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5678. break;
  5679. case SC_PrivateExtern:
  5680. llvm_unreachable("C storage class in c++!");
  5681. }
  5682. }
  5683. if (SC == SC_Static && CurContext->isRecord()) {
  5684. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5685. if (RD->isLocalClass())
  5686. Diag(D.getIdentifierLoc(),
  5687. diag::err_static_data_member_not_allowed_in_local_class)
  5688. << Name << RD->getDeclName();
  5689. // C++98 [class.union]p1: If a union contains a static data member,
  5690. // the program is ill-formed. C++11 drops this restriction.
  5691. if (RD->isUnion())
  5692. Diag(D.getIdentifierLoc(),
  5693. getLangOpts().CPlusPlus11
  5694. ? diag::warn_cxx98_compat_static_data_member_in_union
  5695. : diag::ext_static_data_member_in_union) << Name;
  5696. // We conservatively disallow static data members in anonymous structs.
  5697. else if (!RD->getDeclName())
  5698. Diag(D.getIdentifierLoc(),
  5699. diag::err_static_data_member_not_allowed_in_anon_struct)
  5700. << Name << RD->isUnion();
  5701. }
  5702. }
  5703. // Match up the template parameter lists with the scope specifier, then
  5704. // determine whether we have a template or a template specialization.
  5705. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5706. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5707. D.getCXXScopeSpec(),
  5708. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5709. ? D.getName().TemplateId
  5710. : nullptr,
  5711. TemplateParamLists,
  5712. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5713. if (TemplateParams) {
  5714. if (!TemplateParams->size() &&
  5715. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5716. // There is an extraneous 'template<>' for this variable. Complain
  5717. // about it, but allow the declaration of the variable.
  5718. Diag(TemplateParams->getTemplateLoc(),
  5719. diag::err_template_variable_noparams)
  5720. << II
  5721. << SourceRange(TemplateParams->getTemplateLoc(),
  5722. TemplateParams->getRAngleLoc());
  5723. TemplateParams = nullptr;
  5724. } else {
  5725. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5726. // This is an explicit specialization or a partial specialization.
  5727. // FIXME: Check that we can declare a specialization here.
  5728. IsVariableTemplateSpecialization = true;
  5729. IsPartialSpecialization = TemplateParams->size() > 0;
  5730. } else { // if (TemplateParams->size() > 0)
  5731. // This is a template declaration.
  5732. IsVariableTemplate = true;
  5733. // Check that we can declare a template here.
  5734. if (CheckTemplateDeclScope(S, TemplateParams))
  5735. return nullptr;
  5736. // Only C++1y supports variable templates (N3651).
  5737. Diag(D.getIdentifierLoc(),
  5738. getLangOpts().CPlusPlus14
  5739. ? diag::warn_cxx11_compat_variable_template
  5740. : diag::ext_variable_template);
  5741. }
  5742. }
  5743. } else {
  5744. assert(
  5745. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5746. "should have a 'template<>' for this decl");
  5747. }
  5748. if (IsVariableTemplateSpecialization) {
  5749. SourceLocation TemplateKWLoc =
  5750. TemplateParamLists.size() > 0
  5751. ? TemplateParamLists[0]->getTemplateLoc()
  5752. : SourceLocation();
  5753. DeclResult Res = ActOnVarTemplateSpecialization(
  5754. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5755. IsPartialSpecialization);
  5756. if (Res.isInvalid())
  5757. return nullptr;
  5758. NewVD = cast<VarDecl>(Res.get());
  5759. AddToScope = false;
  5760. } else if (D.isDecompositionDeclarator()) {
  5761. NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
  5762. D.getIdentifierLoc(), R, TInfo, SC,
  5763. Bindings);
  5764. } else
  5765. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5766. D.getIdentifierLoc(), II, R, TInfo, SC);
  5767. // If this is supposed to be a variable template, create it as such.
  5768. if (IsVariableTemplate) {
  5769. NewTemplate =
  5770. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5771. TemplateParams, NewVD);
  5772. NewVD->setDescribedVarTemplate(NewTemplate);
  5773. }
  5774. // If this decl has an auto type in need of deduction, make a note of the
  5775. // Decl so we can diagnose uses of it in its own initializer.
  5776. if (R->getContainedDeducedType())
  5777. ParsingInitForAutoVars.insert(NewVD);
  5778. if (D.isInvalidType() || Invalid) {
  5779. NewVD->setInvalidDecl();
  5780. if (NewTemplate)
  5781. NewTemplate->setInvalidDecl();
  5782. }
  5783. SetNestedNameSpecifier(NewVD, D);
  5784. // If we have any template parameter lists that don't directly belong to
  5785. // the variable (matching the scope specifier), store them.
  5786. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5787. if (TemplateParamLists.size() > VDTemplateParamLists)
  5788. NewVD->setTemplateParameterListsInfo(
  5789. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5790. if (D.getDeclSpec().isConstexprSpecified()) {
  5791. NewVD->setConstexpr(true);
  5792. // C++1z [dcl.spec.constexpr]p1:
  5793. // A static data member declared with the constexpr specifier is
  5794. // implicitly an inline variable.
  5795. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
  5796. NewVD->setImplicitlyInline();
  5797. }
  5798. if (D.getDeclSpec().isConceptSpecified()) {
  5799. if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
  5800. VTD->setConcept();
  5801. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  5802. // be declared with the thread_local, inline, friend, or constexpr
  5803. // specifiers, [...]
  5804. if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
  5805. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5806. diag::err_concept_decl_invalid_specifiers)
  5807. << 0 << 0;
  5808. NewVD->setInvalidDecl(true);
  5809. }
  5810. if (D.getDeclSpec().isConstexprSpecified()) {
  5811. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5812. diag::err_concept_decl_invalid_specifiers)
  5813. << 0 << 3;
  5814. NewVD->setInvalidDecl(true);
  5815. }
  5816. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  5817. // applied only to the definition of a function template or variable
  5818. // template, declared in namespace scope.
  5819. if (IsVariableTemplateSpecialization) {
  5820. Diag(D.getDeclSpec().getConceptSpecLoc(),
  5821. diag::err_concept_specified_specialization)
  5822. << (IsPartialSpecialization ? 2 : 1);
  5823. }
  5824. // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
  5825. // following restrictions:
  5826. // - The declared type shall have the type bool.
  5827. if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
  5828. !NewVD->isInvalidDecl()) {
  5829. Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
  5830. NewVD->setInvalidDecl(true);
  5831. }
  5832. }
  5833. }
  5834. if (D.getDeclSpec().isInlineSpecified()) {
  5835. if (!getLangOpts().CPlusPlus) {
  5836. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5837. << 0;
  5838. } else if (CurContext->isFunctionOrMethod()) {
  5839. // 'inline' is not allowed on block scope variable declaration.
  5840. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5841. diag::err_inline_declaration_block_scope) << Name
  5842. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5843. } else {
  5844. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5845. getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
  5846. : diag::ext_inline_variable);
  5847. NewVD->setInlineSpecified();
  5848. }
  5849. }
  5850. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5851. // lexical context will be different from the semantic context.
  5852. NewVD->setLexicalDeclContext(CurContext);
  5853. if (NewTemplate)
  5854. NewTemplate->setLexicalDeclContext(CurContext);
  5855. if (IsLocalExternDecl) {
  5856. if (D.isDecompositionDeclarator())
  5857. for (auto *B : Bindings)
  5858. B->setLocalExternDecl();
  5859. else
  5860. NewVD->setLocalExternDecl();
  5861. }
  5862. bool EmitTLSUnsupportedError = false;
  5863. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5864. // C++11 [dcl.stc]p4:
  5865. // When thread_local is applied to a variable of block scope the
  5866. // storage-class-specifier static is implied if it does not appear
  5867. // explicitly.
  5868. // Core issue: 'static' is not implied if the variable is declared
  5869. // 'extern'.
  5870. if (NewVD->hasLocalStorage() &&
  5871. (SCSpec != DeclSpec::SCS_unspecified ||
  5872. TSCS != DeclSpec::TSCS_thread_local ||
  5873. !DC->isFunctionOrMethod()))
  5874. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5875. diag::err_thread_non_global)
  5876. << DeclSpec::getSpecifierName(TSCS);
  5877. else if (!Context.getTargetInfo().isTLSSupported()) {
  5878. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5879. // Postpone error emission until we've collected attributes required to
  5880. // figure out whether it's a host or device variable and whether the
  5881. // error should be ignored.
  5882. EmitTLSUnsupportedError = true;
  5883. // We still need to mark the variable as TLS so it shows up in AST with
  5884. // proper storage class for other tools to use even if we're not going
  5885. // to emit any code for it.
  5886. NewVD->setTSCSpec(TSCS);
  5887. } else
  5888. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5889. diag::err_thread_unsupported);
  5890. } else
  5891. NewVD->setTSCSpec(TSCS);
  5892. }
  5893. // C99 6.7.4p3
  5894. // An inline definition of a function with external linkage shall
  5895. // not contain a definition of a modifiable object with static or
  5896. // thread storage duration...
  5897. // We only apply this when the function is required to be defined
  5898. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5899. // that a local variable with thread storage duration still has to
  5900. // be marked 'static'. Also note that it's possible to get these
  5901. // semantics in C++ using __attribute__((gnu_inline)).
  5902. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5903. !NewVD->getType().isConstQualified()) {
  5904. FunctionDecl *CurFD = getCurFunctionDecl();
  5905. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5906. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5907. diag::warn_static_local_in_extern_inline);
  5908. MaybeSuggestAddingStaticToDecl(CurFD);
  5909. }
  5910. }
  5911. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5912. if (IsVariableTemplateSpecialization)
  5913. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5914. << (IsPartialSpecialization ? 1 : 0)
  5915. << FixItHint::CreateRemoval(
  5916. D.getDeclSpec().getModulePrivateSpecLoc());
  5917. else if (IsMemberSpecialization)
  5918. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5919. << 2
  5920. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5921. else if (NewVD->hasLocalStorage())
  5922. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5923. << 0 << NewVD->getDeclName()
  5924. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5925. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5926. else {
  5927. NewVD->setModulePrivate();
  5928. if (NewTemplate)
  5929. NewTemplate->setModulePrivate();
  5930. for (auto *B : Bindings)
  5931. B->setModulePrivate();
  5932. }
  5933. }
  5934. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5935. ProcessDeclAttributes(S, NewVD, D);
  5936. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5937. if (EmitTLSUnsupportedError &&
  5938. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  5939. (getLangOpts().OpenMPIsDevice &&
  5940. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  5941. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5942. diag::err_thread_unsupported);
  5943. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5944. // storage [duration]."
  5945. if (SC == SC_None && S->getFnParent() != nullptr &&
  5946. (NewVD->hasAttr<CUDASharedAttr>() ||
  5947. NewVD->hasAttr<CUDAConstantAttr>())) {
  5948. NewVD->setStorageClass(SC_Static);
  5949. }
  5950. }
  5951. // Ensure that dllimport globals without explicit storage class are treated as
  5952. // extern. The storage class is set above using parsed attributes. Now we can
  5953. // check the VarDecl itself.
  5954. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5955. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5956. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5957. // In auto-retain/release, infer strong retension for variables of
  5958. // retainable type.
  5959. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5960. NewVD->setInvalidDecl();
  5961. // Handle GNU asm-label extension (encoded as an attribute).
  5962. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5963. // The parser guarantees this is a string.
  5964. StringLiteral *SE = cast<StringLiteral>(E);
  5965. StringRef Label = SE->getString();
  5966. if (S->getFnParent() != nullptr) {
  5967. switch (SC) {
  5968. case SC_None:
  5969. case SC_Auto:
  5970. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5971. break;
  5972. case SC_Register:
  5973. // Local Named register
  5974. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5975. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5976. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5977. break;
  5978. case SC_Static:
  5979. case SC_Extern:
  5980. case SC_PrivateExtern:
  5981. break;
  5982. }
  5983. } else if (SC == SC_Register) {
  5984. // Global Named register
  5985. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5986. const auto &TI = Context.getTargetInfo();
  5987. bool HasSizeMismatch;
  5988. if (!TI.isValidGCCRegisterName(Label))
  5989. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5990. else if (!TI.validateGlobalRegisterVariable(Label,
  5991. Context.getTypeSize(R),
  5992. HasSizeMismatch))
  5993. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5994. else if (HasSizeMismatch)
  5995. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5996. }
  5997. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5998. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5999. NewVD->setInvalidDecl(true);
  6000. }
  6001. }
  6002. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6003. Context, Label, 0));
  6004. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6005. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6006. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6007. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6008. if (isDeclExternC(NewVD)) {
  6009. NewVD->addAttr(I->second);
  6010. ExtnameUndeclaredIdentifiers.erase(I);
  6011. } else
  6012. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6013. << /*Variable*/1 << NewVD;
  6014. }
  6015. }
  6016. // Find the shadowed declaration before filtering for scope.
  6017. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6018. ? getShadowedDeclaration(NewVD, Previous)
  6019. : nullptr;
  6020. // Don't consider existing declarations that are in a different
  6021. // scope and are out-of-semantic-context declarations (if the new
  6022. // declaration has linkage).
  6023. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6024. D.getCXXScopeSpec().isNotEmpty() ||
  6025. IsMemberSpecialization ||
  6026. IsVariableTemplateSpecialization);
  6027. // Check whether the previous declaration is in the same block scope. This
  6028. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6029. if (getLangOpts().CPlusPlus &&
  6030. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6031. NewVD->setPreviousDeclInSameBlockScope(
  6032. Previous.isSingleResult() && !Previous.isShadowed() &&
  6033. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6034. if (!getLangOpts().CPlusPlus) {
  6035. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6036. } else {
  6037. // If this is an explicit specialization of a static data member, check it.
  6038. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6039. CheckMemberSpecialization(NewVD, Previous))
  6040. NewVD->setInvalidDecl();
  6041. // Merge the decl with the existing one if appropriate.
  6042. if (!Previous.empty()) {
  6043. if (Previous.isSingleResult() &&
  6044. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6045. D.getCXXScopeSpec().isSet()) {
  6046. // The user tried to define a non-static data member
  6047. // out-of-line (C++ [dcl.meaning]p1).
  6048. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6049. << D.getCXXScopeSpec().getRange();
  6050. Previous.clear();
  6051. NewVD->setInvalidDecl();
  6052. }
  6053. } else if (D.getCXXScopeSpec().isSet()) {
  6054. // No previous declaration in the qualifying scope.
  6055. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6056. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6057. << D.getCXXScopeSpec().getRange();
  6058. NewVD->setInvalidDecl();
  6059. }
  6060. if (!IsVariableTemplateSpecialization)
  6061. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6062. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
  6063. // an explicit specialization (14.8.3) or a partial specialization of a
  6064. // concept definition.
  6065. if (IsVariableTemplateSpecialization &&
  6066. !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
  6067. Previous.isSingleResult()) {
  6068. NamedDecl *PreviousDecl = Previous.getFoundDecl();
  6069. if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
  6070. if (VarTmpl->isConcept()) {
  6071. Diag(NewVD->getLocation(), diag::err_concept_specialized)
  6072. << 1 /*variable*/
  6073. << (IsPartialSpecialization ? 2 /*partially specialized*/
  6074. : 1 /*explicitly specialized*/);
  6075. Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
  6076. NewVD->setInvalidDecl();
  6077. }
  6078. }
  6079. }
  6080. if (NewTemplate) {
  6081. VarTemplateDecl *PrevVarTemplate =
  6082. NewVD->getPreviousDecl()
  6083. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6084. : nullptr;
  6085. // Check the template parameter list of this declaration, possibly
  6086. // merging in the template parameter list from the previous variable
  6087. // template declaration.
  6088. if (CheckTemplateParameterList(
  6089. TemplateParams,
  6090. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6091. : nullptr,
  6092. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6093. DC->isDependentContext())
  6094. ? TPC_ClassTemplateMember
  6095. : TPC_VarTemplate))
  6096. NewVD->setInvalidDecl();
  6097. // If we are providing an explicit specialization of a static variable
  6098. // template, make a note of that.
  6099. if (PrevVarTemplate &&
  6100. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6101. PrevVarTemplate->setMemberSpecialization();
  6102. }
  6103. }
  6104. // Diagnose shadowed variables iff this isn't a redeclaration.
  6105. if (ShadowedDecl && !D.isRedeclaration())
  6106. CheckShadow(NewVD, ShadowedDecl, Previous);
  6107. ProcessPragmaWeak(S, NewVD);
  6108. // If this is the first declaration of an extern C variable, update
  6109. // the map of such variables.
  6110. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6111. isIncompleteDeclExternC(*this, NewVD))
  6112. RegisterLocallyScopedExternCDecl(NewVD, S);
  6113. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6114. Decl *ManglingContextDecl;
  6115. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6116. NewVD->getDeclContext(), ManglingContextDecl)) {
  6117. Context.setManglingNumber(
  6118. NewVD, MCtx->getManglingNumber(
  6119. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6120. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6121. }
  6122. }
  6123. // Special handling of variable named 'main'.
  6124. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6125. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6126. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6127. // C++ [basic.start.main]p3
  6128. // A program that declares a variable main at global scope is ill-formed.
  6129. if (getLangOpts().CPlusPlus)
  6130. Diag(D.getLocStart(), diag::err_main_global_variable);
  6131. // In C, and external-linkage variable named main results in undefined
  6132. // behavior.
  6133. else if (NewVD->hasExternalFormalLinkage())
  6134. Diag(D.getLocStart(), diag::warn_main_redefined);
  6135. }
  6136. if (D.isRedeclaration() && !Previous.empty()) {
  6137. checkDLLAttributeRedeclaration(
  6138. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  6139. IsMemberSpecialization, D.isFunctionDefinition());
  6140. }
  6141. if (NewTemplate) {
  6142. if (NewVD->isInvalidDecl())
  6143. NewTemplate->setInvalidDecl();
  6144. ActOnDocumentableDecl(NewTemplate);
  6145. return NewTemplate;
  6146. }
  6147. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6148. CompleteMemberSpecialization(NewVD, Previous);
  6149. return NewVD;
  6150. }
  6151. /// Enum describing the %select options in diag::warn_decl_shadow.
  6152. enum ShadowedDeclKind {
  6153. SDK_Local,
  6154. SDK_Global,
  6155. SDK_StaticMember,
  6156. SDK_Field,
  6157. SDK_Typedef,
  6158. SDK_Using
  6159. };
  6160. /// Determine what kind of declaration we're shadowing.
  6161. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6162. const DeclContext *OldDC) {
  6163. if (isa<TypeAliasDecl>(ShadowedDecl))
  6164. return SDK_Using;
  6165. else if (isa<TypedefDecl>(ShadowedDecl))
  6166. return SDK_Typedef;
  6167. else if (isa<RecordDecl>(OldDC))
  6168. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6169. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6170. }
  6171. /// Return the location of the capture if the given lambda captures the given
  6172. /// variable \p VD, or an invalid source location otherwise.
  6173. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6174. const VarDecl *VD) {
  6175. for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
  6176. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6177. return Capture.getLocation();
  6178. }
  6179. return SourceLocation();
  6180. }
  6181. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6182. const LookupResult &R) {
  6183. // Only diagnose if we're shadowing an unambiguous field or variable.
  6184. if (R.getResultKind() != LookupResult::Found)
  6185. return false;
  6186. // Return false if warning is ignored.
  6187. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6188. }
  6189. /// \brief Return the declaration shadowed by the given variable \p D, or null
  6190. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6191. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6192. const LookupResult &R) {
  6193. if (!shouldWarnIfShadowedDecl(Diags, R))
  6194. return nullptr;
  6195. // Don't diagnose declarations at file scope.
  6196. if (D->hasGlobalStorage())
  6197. return nullptr;
  6198. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6199. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6200. ? ShadowedDecl
  6201. : nullptr;
  6202. }
  6203. /// \brief Return the declaration shadowed by the given typedef \p D, or null
  6204. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6205. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6206. const LookupResult &R) {
  6207. // Don't warn if typedef declaration is part of a class
  6208. if (D->getDeclContext()->isRecord())
  6209. return nullptr;
  6210. if (!shouldWarnIfShadowedDecl(Diags, R))
  6211. return nullptr;
  6212. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6213. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6214. }
  6215. /// \brief Diagnose variable or built-in function shadowing. Implements
  6216. /// -Wshadow.
  6217. ///
  6218. /// This method is called whenever a VarDecl is added to a "useful"
  6219. /// scope.
  6220. ///
  6221. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6222. /// \param R the lookup of the name
  6223. ///
  6224. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6225. const LookupResult &R) {
  6226. DeclContext *NewDC = D->getDeclContext();
  6227. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6228. // Fields are not shadowed by variables in C++ static methods.
  6229. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6230. if (MD->isStatic())
  6231. return;
  6232. // Fields shadowed by constructor parameters are a special case. Usually
  6233. // the constructor initializes the field with the parameter.
  6234. if (isa<CXXConstructorDecl>(NewDC))
  6235. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6236. // Remember that this was shadowed so we can either warn about its
  6237. // modification or its existence depending on warning settings.
  6238. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6239. return;
  6240. }
  6241. }
  6242. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6243. if (shadowedVar->isExternC()) {
  6244. // For shadowing external vars, make sure that we point to the global
  6245. // declaration, not a locally scoped extern declaration.
  6246. for (auto I : shadowedVar->redecls())
  6247. if (I->isFileVarDecl()) {
  6248. ShadowedDecl = I;
  6249. break;
  6250. }
  6251. }
  6252. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6253. unsigned WarningDiag = diag::warn_decl_shadow;
  6254. SourceLocation CaptureLoc;
  6255. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6256. isa<CXXMethodDecl>(NewDC)) {
  6257. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6258. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6259. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6260. // Try to avoid warnings for lambdas with an explicit capture list.
  6261. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6262. // Warn only when the lambda captures the shadowed decl explicitly.
  6263. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6264. if (CaptureLoc.isInvalid())
  6265. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6266. } else {
  6267. // Remember that this was shadowed so we can avoid the warning if the
  6268. // shadowed decl isn't captured and the warning settings allow it.
  6269. cast<LambdaScopeInfo>(getCurFunction())
  6270. ->ShadowingDecls.push_back(
  6271. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6272. return;
  6273. }
  6274. }
  6275. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6276. // A variable can't shadow a local variable in an enclosing scope, if
  6277. // they are separated by a non-capturing declaration context.
  6278. for (DeclContext *ParentDC = NewDC;
  6279. ParentDC && !ParentDC->Equals(OldDC);
  6280. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6281. // Only block literals, captured statements, and lambda expressions
  6282. // can capture; other scopes don't.
  6283. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6284. !isLambdaCallOperator(ParentDC)) {
  6285. return;
  6286. }
  6287. }
  6288. }
  6289. }
  6290. }
  6291. // Only warn about certain kinds of shadowing for class members.
  6292. if (NewDC && NewDC->isRecord()) {
  6293. // In particular, don't warn about shadowing non-class members.
  6294. if (!OldDC->isRecord())
  6295. return;
  6296. // TODO: should we warn about static data members shadowing
  6297. // static data members from base classes?
  6298. // TODO: don't diagnose for inaccessible shadowed members.
  6299. // This is hard to do perfectly because we might friend the
  6300. // shadowing context, but that's just a false negative.
  6301. }
  6302. DeclarationName Name = R.getLookupName();
  6303. // Emit warning and note.
  6304. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6305. return;
  6306. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6307. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6308. if (!CaptureLoc.isInvalid())
  6309. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6310. << Name << /*explicitly*/ 1;
  6311. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6312. }
  6313. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6314. /// when these variables are captured by the lambda.
  6315. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6316. for (const auto &Shadow : LSI->ShadowingDecls) {
  6317. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6318. // Try to avoid the warning when the shadowed decl isn't captured.
  6319. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6320. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6321. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6322. ? diag::warn_decl_shadow_uncaptured_local
  6323. : diag::warn_decl_shadow)
  6324. << Shadow.VD->getDeclName()
  6325. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6326. if (!CaptureLoc.isInvalid())
  6327. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6328. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6329. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6330. }
  6331. }
  6332. /// \brief Check -Wshadow without the advantage of a previous lookup.
  6333. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6334. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6335. return;
  6336. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6337. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6338. LookupName(R, S);
  6339. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6340. CheckShadow(D, ShadowedDecl, R);
  6341. }
  6342. /// Check if 'E', which is an expression that is about to be modified, refers
  6343. /// to a constructor parameter that shadows a field.
  6344. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6345. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6346. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6347. return;
  6348. E = E->IgnoreParenImpCasts();
  6349. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6350. if (!DRE)
  6351. return;
  6352. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6353. auto I = ShadowingDecls.find(D);
  6354. if (I == ShadowingDecls.end())
  6355. return;
  6356. const NamedDecl *ShadowedDecl = I->second;
  6357. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6358. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6359. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6360. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6361. // Avoid issuing multiple warnings about the same decl.
  6362. ShadowingDecls.erase(I);
  6363. }
  6364. /// Check for conflict between this global or extern "C" declaration and
  6365. /// previous global or extern "C" declarations. This is only used in C++.
  6366. template<typename T>
  6367. static bool checkGlobalOrExternCConflict(
  6368. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6369. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6370. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6371. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6372. // The common case: this global doesn't conflict with any extern "C"
  6373. // declaration.
  6374. return false;
  6375. }
  6376. if (Prev) {
  6377. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6378. // Both the old and new declarations have C language linkage. This is a
  6379. // redeclaration.
  6380. Previous.clear();
  6381. Previous.addDecl(Prev);
  6382. return true;
  6383. }
  6384. // This is a global, non-extern "C" declaration, and there is a previous
  6385. // non-global extern "C" declaration. Diagnose if this is a variable
  6386. // declaration.
  6387. if (!isa<VarDecl>(ND))
  6388. return false;
  6389. } else {
  6390. // The declaration is extern "C". Check for any declaration in the
  6391. // translation unit which might conflict.
  6392. if (IsGlobal) {
  6393. // We have already performed the lookup into the translation unit.
  6394. IsGlobal = false;
  6395. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6396. I != E; ++I) {
  6397. if (isa<VarDecl>(*I)) {
  6398. Prev = *I;
  6399. break;
  6400. }
  6401. }
  6402. } else {
  6403. DeclContext::lookup_result R =
  6404. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6405. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6406. I != E; ++I) {
  6407. if (isa<VarDecl>(*I)) {
  6408. Prev = *I;
  6409. break;
  6410. }
  6411. // FIXME: If we have any other entity with this name in global scope,
  6412. // the declaration is ill-formed, but that is a defect: it breaks the
  6413. // 'stat' hack, for instance. Only variables can have mangled name
  6414. // clashes with extern "C" declarations, so only they deserve a
  6415. // diagnostic.
  6416. }
  6417. }
  6418. if (!Prev)
  6419. return false;
  6420. }
  6421. // Use the first declaration's location to ensure we point at something which
  6422. // is lexically inside an extern "C" linkage-spec.
  6423. assert(Prev && "should have found a previous declaration to diagnose");
  6424. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6425. Prev = FD->getFirstDecl();
  6426. else
  6427. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6428. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6429. << IsGlobal << ND;
  6430. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6431. << IsGlobal;
  6432. return false;
  6433. }
  6434. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6435. /// if we have found that this is a redeclaration of some prior entity.
  6436. ///
  6437. /// Per C++ [dcl.link]p6:
  6438. /// Two declarations [for a function or variable] with C language linkage
  6439. /// with the same name that appear in different scopes refer to the same
  6440. /// [entity]. An entity with C language linkage shall not be declared with
  6441. /// the same name as an entity in global scope.
  6442. template<typename T>
  6443. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6444. LookupResult &Previous) {
  6445. if (!S.getLangOpts().CPlusPlus) {
  6446. // In C, when declaring a global variable, look for a corresponding 'extern'
  6447. // variable declared in function scope. We don't need this in C++, because
  6448. // we find local extern decls in the surrounding file-scope DeclContext.
  6449. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6450. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6451. Previous.clear();
  6452. Previous.addDecl(Prev);
  6453. return true;
  6454. }
  6455. }
  6456. return false;
  6457. }
  6458. // A declaration in the translation unit can conflict with an extern "C"
  6459. // declaration.
  6460. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6461. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6462. // An extern "C" declaration can conflict with a declaration in the
  6463. // translation unit or can be a redeclaration of an extern "C" declaration
  6464. // in another scope.
  6465. if (isIncompleteDeclExternC(S,ND))
  6466. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6467. // Neither global nor extern "C": nothing to do.
  6468. return false;
  6469. }
  6470. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6471. // If the decl is already known invalid, don't check it.
  6472. if (NewVD->isInvalidDecl())
  6473. return;
  6474. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  6475. QualType T = TInfo->getType();
  6476. // Defer checking an 'auto' type until its initializer is attached.
  6477. if (T->isUndeducedType())
  6478. return;
  6479. if (NewVD->hasAttrs())
  6480. CheckAlignasUnderalignment(NewVD);
  6481. if (T->isObjCObjectType()) {
  6482. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6483. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6484. T = Context.getObjCObjectPointerType(T);
  6485. NewVD->setType(T);
  6486. }
  6487. // Emit an error if an address space was applied to decl with local storage.
  6488. // This includes arrays of objects with address space qualifiers, but not
  6489. // automatic variables that point to other address spaces.
  6490. // ISO/IEC TR 18037 S5.1.2
  6491. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6492. T.getAddressSpace() != LangAS::Default) {
  6493. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6494. NewVD->setInvalidDecl();
  6495. return;
  6496. }
  6497. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6498. // scope.
  6499. if (getLangOpts().OpenCLVersion == 120 &&
  6500. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6501. NewVD->isStaticLocal()) {
  6502. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6503. NewVD->setInvalidDecl();
  6504. return;
  6505. }
  6506. if (getLangOpts().OpenCL) {
  6507. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6508. if (NewVD->hasAttr<BlocksAttr>()) {
  6509. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6510. return;
  6511. }
  6512. if (T->isBlockPointerType()) {
  6513. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6514. // can't use 'extern' storage class.
  6515. if (!T.isConstQualified()) {
  6516. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6517. << 0 /*const*/;
  6518. NewVD->setInvalidDecl();
  6519. return;
  6520. }
  6521. if (NewVD->hasExternalStorage()) {
  6522. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6523. NewVD->setInvalidDecl();
  6524. return;
  6525. }
  6526. }
  6527. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  6528. // __constant address space.
  6529. // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
  6530. // variables inside a function can also be declared in the global
  6531. // address space.
  6532. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6533. NewVD->hasExternalStorage()) {
  6534. if (!T->isSamplerT() &&
  6535. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6536. (T.getAddressSpace() == LangAS::opencl_global &&
  6537. getLangOpts().OpenCLVersion == 200))) {
  6538. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6539. if (getLangOpts().OpenCLVersion == 200)
  6540. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6541. << Scope << "global or constant";
  6542. else
  6543. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6544. << Scope << "constant";
  6545. NewVD->setInvalidDecl();
  6546. return;
  6547. }
  6548. } else {
  6549. if (T.getAddressSpace() == LangAS::opencl_global) {
  6550. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6551. << 1 /*is any function*/ << "global";
  6552. NewVD->setInvalidDecl();
  6553. return;
  6554. }
  6555. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6556. T.getAddressSpace() == LangAS::opencl_local) {
  6557. FunctionDecl *FD = getCurFunctionDecl();
  6558. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6559. // in functions.
  6560. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6561. if (T.getAddressSpace() == LangAS::opencl_constant)
  6562. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6563. << 0 /*non-kernel only*/ << "constant";
  6564. else
  6565. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6566. << 0 /*non-kernel only*/ << "local";
  6567. NewVD->setInvalidDecl();
  6568. return;
  6569. }
  6570. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6571. // in the outermost scope of a kernel function.
  6572. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6573. if (!getCurScope()->isFunctionScope()) {
  6574. if (T.getAddressSpace() == LangAS::opencl_constant)
  6575. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6576. << "constant";
  6577. else
  6578. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6579. << "local";
  6580. NewVD->setInvalidDecl();
  6581. return;
  6582. }
  6583. }
  6584. } else if (T.getAddressSpace() != LangAS::opencl_private) {
  6585. // Do not allow other address spaces on automatic variable.
  6586. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6587. NewVD->setInvalidDecl();
  6588. return;
  6589. }
  6590. }
  6591. }
  6592. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6593. && !NewVD->hasAttr<BlocksAttr>()) {
  6594. if (getLangOpts().getGC() != LangOptions::NonGC)
  6595. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6596. else {
  6597. assert(!getLangOpts().ObjCAutoRefCount);
  6598. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6599. }
  6600. }
  6601. bool isVM = T->isVariablyModifiedType();
  6602. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6603. NewVD->hasAttr<BlocksAttr>())
  6604. getCurFunction()->setHasBranchProtectedScope();
  6605. if ((isVM && NewVD->hasLinkage()) ||
  6606. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6607. bool SizeIsNegative;
  6608. llvm::APSInt Oversized;
  6609. TypeSourceInfo *FixedTInfo =
  6610. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  6611. SizeIsNegative, Oversized);
  6612. if (!FixedTInfo && T->isVariableArrayType()) {
  6613. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6614. // FIXME: This won't give the correct result for
  6615. // int a[10][n];
  6616. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6617. if (NewVD->isFileVarDecl())
  6618. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6619. << SizeRange;
  6620. else if (NewVD->isStaticLocal())
  6621. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6622. << SizeRange;
  6623. else
  6624. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6625. << SizeRange;
  6626. NewVD->setInvalidDecl();
  6627. return;
  6628. }
  6629. if (!FixedTInfo) {
  6630. if (NewVD->isFileVarDecl())
  6631. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6632. else
  6633. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6634. NewVD->setInvalidDecl();
  6635. return;
  6636. }
  6637. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6638. NewVD->setType(FixedTInfo->getType());
  6639. NewVD->setTypeSourceInfo(FixedTInfo);
  6640. }
  6641. if (T->isVoidType()) {
  6642. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6643. // of objects and functions.
  6644. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6645. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6646. << T;
  6647. NewVD->setInvalidDecl();
  6648. return;
  6649. }
  6650. }
  6651. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6652. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6653. NewVD->setInvalidDecl();
  6654. return;
  6655. }
  6656. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6657. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6658. NewVD->setInvalidDecl();
  6659. return;
  6660. }
  6661. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6662. RequireLiteralType(NewVD->getLocation(), T,
  6663. diag::err_constexpr_var_non_literal)) {
  6664. NewVD->setInvalidDecl();
  6665. return;
  6666. }
  6667. }
  6668. /// \brief Perform semantic checking on a newly-created variable
  6669. /// declaration.
  6670. ///
  6671. /// This routine performs all of the type-checking required for a
  6672. /// variable declaration once it has been built. It is used both to
  6673. /// check variables after they have been parsed and their declarators
  6674. /// have been translated into a declaration, and to check variables
  6675. /// that have been instantiated from a template.
  6676. ///
  6677. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6678. ///
  6679. /// Returns true if the variable declaration is a redeclaration.
  6680. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6681. CheckVariableDeclarationType(NewVD);
  6682. // If the decl is already known invalid, don't check it.
  6683. if (NewVD->isInvalidDecl())
  6684. return false;
  6685. // If we did not find anything by this name, look for a non-visible
  6686. // extern "C" declaration with the same name.
  6687. if (Previous.empty() &&
  6688. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6689. Previous.setShadowed();
  6690. if (!Previous.empty()) {
  6691. MergeVarDecl(NewVD, Previous);
  6692. return true;
  6693. }
  6694. return false;
  6695. }
  6696. namespace {
  6697. struct FindOverriddenMethod {
  6698. Sema *S;
  6699. CXXMethodDecl *Method;
  6700. /// Member lookup function that determines whether a given C++
  6701. /// method overrides a method in a base class, to be used with
  6702. /// CXXRecordDecl::lookupInBases().
  6703. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6704. RecordDecl *BaseRecord =
  6705. Specifier->getType()->getAs<RecordType>()->getDecl();
  6706. DeclarationName Name = Method->getDeclName();
  6707. // FIXME: Do we care about other names here too?
  6708. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6709. // We really want to find the base class destructor here.
  6710. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6711. CanQualType CT = S->Context.getCanonicalType(T);
  6712. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6713. }
  6714. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6715. Path.Decls = Path.Decls.slice(1)) {
  6716. NamedDecl *D = Path.Decls.front();
  6717. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6718. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6719. return true;
  6720. }
  6721. }
  6722. return false;
  6723. }
  6724. };
  6725. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6726. } // end anonymous namespace
  6727. /// \brief Report an error regarding overriding, along with any relevant
  6728. /// overriden methods.
  6729. ///
  6730. /// \param DiagID the primary error to report.
  6731. /// \param MD the overriding method.
  6732. /// \param OEK which overrides to include as notes.
  6733. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6734. OverrideErrorKind OEK = OEK_All) {
  6735. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6736. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  6737. E = MD->end_overridden_methods();
  6738. I != E; ++I) {
  6739. // This check (& the OEK parameter) could be replaced by a predicate, but
  6740. // without lambdas that would be overkill. This is still nicer than writing
  6741. // out the diag loop 3 times.
  6742. if ((OEK == OEK_All) ||
  6743. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  6744. (OEK == OEK_Deleted && (*I)->isDeleted()))
  6745. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  6746. }
  6747. }
  6748. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6749. /// and if so, check that it's a valid override and remember it.
  6750. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6751. // Look for methods in base classes that this method might override.
  6752. CXXBasePaths Paths;
  6753. FindOverriddenMethod FOM;
  6754. FOM.Method = MD;
  6755. FOM.S = this;
  6756. bool hasDeletedOverridenMethods = false;
  6757. bool hasNonDeletedOverridenMethods = false;
  6758. bool AddedAny = false;
  6759. if (DC->lookupInBases(FOM, Paths)) {
  6760. for (auto *I : Paths.found_decls()) {
  6761. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6762. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6763. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6764. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6765. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6766. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6767. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6768. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6769. AddedAny = true;
  6770. }
  6771. }
  6772. }
  6773. }
  6774. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6775. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6776. }
  6777. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6778. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6779. }
  6780. return AddedAny;
  6781. }
  6782. namespace {
  6783. // Struct for holding all of the extra arguments needed by
  6784. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6785. struct ActOnFDArgs {
  6786. Scope *S;
  6787. Declarator &D;
  6788. MultiTemplateParamsArg TemplateParamLists;
  6789. bool AddToScope;
  6790. };
  6791. } // end anonymous namespace
  6792. namespace {
  6793. // Callback to only accept typo corrections that have a non-zero edit distance.
  6794. // Also only accept corrections that have the same parent decl.
  6795. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6796. public:
  6797. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6798. CXXRecordDecl *Parent)
  6799. : Context(Context), OriginalFD(TypoFD),
  6800. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6801. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6802. if (candidate.getEditDistance() == 0)
  6803. return false;
  6804. SmallVector<unsigned, 1> MismatchedParams;
  6805. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6806. CDeclEnd = candidate.end();
  6807. CDecl != CDeclEnd; ++CDecl) {
  6808. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6809. if (FD && !FD->hasBody() &&
  6810. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6811. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6812. CXXRecordDecl *Parent = MD->getParent();
  6813. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6814. return true;
  6815. } else if (!ExpectedParent) {
  6816. return true;
  6817. }
  6818. }
  6819. }
  6820. return false;
  6821. }
  6822. private:
  6823. ASTContext &Context;
  6824. FunctionDecl *OriginalFD;
  6825. CXXRecordDecl *ExpectedParent;
  6826. };
  6827. } // end anonymous namespace
  6828. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6829. TypoCorrectedFunctionDefinitions.insert(F);
  6830. }
  6831. /// \brief Generate diagnostics for an invalid function redeclaration.
  6832. ///
  6833. /// This routine handles generating the diagnostic messages for an invalid
  6834. /// function redeclaration, including finding possible similar declarations
  6835. /// or performing typo correction if there are no previous declarations with
  6836. /// the same name.
  6837. ///
  6838. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6839. /// the new declaration name does not cause new errors.
  6840. static NamedDecl *DiagnoseInvalidRedeclaration(
  6841. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6842. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6843. DeclarationName Name = NewFD->getDeclName();
  6844. DeclContext *NewDC = NewFD->getDeclContext();
  6845. SmallVector<unsigned, 1> MismatchedParams;
  6846. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6847. TypoCorrection Correction;
  6848. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6849. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  6850. : diag::err_member_decl_does_not_match;
  6851. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6852. IsLocalFriend ? Sema::LookupLocalFriendName
  6853. : Sema::LookupOrdinaryName,
  6854. Sema::ForVisibleRedeclaration);
  6855. NewFD->setInvalidDecl();
  6856. if (IsLocalFriend)
  6857. SemaRef.LookupName(Prev, S);
  6858. else
  6859. SemaRef.LookupQualifiedName(Prev, NewDC);
  6860. assert(!Prev.isAmbiguous() &&
  6861. "Cannot have an ambiguity in previous-declaration lookup");
  6862. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6863. if (!Prev.empty()) {
  6864. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6865. Func != FuncEnd; ++Func) {
  6866. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6867. if (FD &&
  6868. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6869. // Add 1 to the index so that 0 can mean the mismatch didn't
  6870. // involve a parameter
  6871. unsigned ParamNum =
  6872. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6873. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6874. }
  6875. }
  6876. // If the qualified name lookup yielded nothing, try typo correction
  6877. } else if ((Correction = SemaRef.CorrectTypo(
  6878. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6879. &ExtraArgs.D.getCXXScopeSpec(),
  6880. llvm::make_unique<DifferentNameValidatorCCC>(
  6881. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6882. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6883. // Set up everything for the call to ActOnFunctionDeclarator
  6884. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6885. ExtraArgs.D.getIdentifierLoc());
  6886. Previous.clear();
  6887. Previous.setLookupName(Correction.getCorrection());
  6888. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6889. CDeclEnd = Correction.end();
  6890. CDecl != CDeclEnd; ++CDecl) {
  6891. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6892. if (FD && !FD->hasBody() &&
  6893. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6894. Previous.addDecl(FD);
  6895. }
  6896. }
  6897. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6898. NamedDecl *Result;
  6899. // Retry building the function declaration with the new previous
  6900. // declarations, and with errors suppressed.
  6901. {
  6902. // Trap errors.
  6903. Sema::SFINAETrap Trap(SemaRef);
  6904. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6905. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6906. // eliminate the need for the parameter pack ExtraArgs.
  6907. Result = SemaRef.ActOnFunctionDeclarator(
  6908. ExtraArgs.S, ExtraArgs.D,
  6909. Correction.getCorrectionDecl()->getDeclContext(),
  6910. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6911. ExtraArgs.AddToScope);
  6912. if (Trap.hasErrorOccurred())
  6913. Result = nullptr;
  6914. }
  6915. if (Result) {
  6916. // Determine which correction we picked.
  6917. Decl *Canonical = Result->getCanonicalDecl();
  6918. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6919. I != E; ++I)
  6920. if ((*I)->getCanonicalDecl() == Canonical)
  6921. Correction.setCorrectionDecl(*I);
  6922. // Let Sema know about the correction.
  6923. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6924. SemaRef.diagnoseTypo(
  6925. Correction,
  6926. SemaRef.PDiag(IsLocalFriend
  6927. ? diag::err_no_matching_local_friend_suggest
  6928. : diag::err_member_decl_does_not_match_suggest)
  6929. << Name << NewDC << IsDefinition);
  6930. return Result;
  6931. }
  6932. // Pretend the typo correction never occurred
  6933. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6934. ExtraArgs.D.getIdentifierLoc());
  6935. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6936. Previous.clear();
  6937. Previous.setLookupName(Name);
  6938. }
  6939. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6940. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6941. bool NewFDisConst = false;
  6942. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6943. NewFDisConst = NewMD->isConst();
  6944. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6945. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6946. NearMatch != NearMatchEnd; ++NearMatch) {
  6947. FunctionDecl *FD = NearMatch->first;
  6948. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6949. bool FDisConst = MD && MD->isConst();
  6950. bool IsMember = MD || !IsLocalFriend;
  6951. // FIXME: These notes are poorly worded for the local friend case.
  6952. if (unsigned Idx = NearMatch->second) {
  6953. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6954. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6955. if (Loc.isInvalid()) Loc = FD->getLocation();
  6956. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6957. : diag::note_local_decl_close_param_match)
  6958. << Idx << FDParam->getType()
  6959. << NewFD->getParamDecl(Idx - 1)->getType();
  6960. } else if (FDisConst != NewFDisConst) {
  6961. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6962. << NewFDisConst << FD->getSourceRange().getEnd();
  6963. } else
  6964. SemaRef.Diag(FD->getLocation(),
  6965. IsMember ? diag::note_member_def_close_match
  6966. : diag::note_local_decl_close_match);
  6967. }
  6968. return nullptr;
  6969. }
  6970. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6971. switch (D.getDeclSpec().getStorageClassSpec()) {
  6972. default: llvm_unreachable("Unknown storage class!");
  6973. case DeclSpec::SCS_auto:
  6974. case DeclSpec::SCS_register:
  6975. case DeclSpec::SCS_mutable:
  6976. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6977. diag::err_typecheck_sclass_func);
  6978. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6979. D.setInvalidType();
  6980. break;
  6981. case DeclSpec::SCS_unspecified: break;
  6982. case DeclSpec::SCS_extern:
  6983. if (D.getDeclSpec().isExternInLinkageSpec())
  6984. return SC_None;
  6985. return SC_Extern;
  6986. case DeclSpec::SCS_static: {
  6987. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6988. // C99 6.7.1p5:
  6989. // The declaration of an identifier for a function that has
  6990. // block scope shall have no explicit storage-class specifier
  6991. // other than extern
  6992. // See also (C++ [dcl.stc]p4).
  6993. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6994. diag::err_static_block_func);
  6995. break;
  6996. } else
  6997. return SC_Static;
  6998. }
  6999. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7000. }
  7001. // No explicit storage class has already been returned
  7002. return SC_None;
  7003. }
  7004. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7005. DeclContext *DC, QualType &R,
  7006. TypeSourceInfo *TInfo,
  7007. StorageClass SC,
  7008. bool &IsVirtualOkay) {
  7009. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7010. DeclarationName Name = NameInfo.getName();
  7011. FunctionDecl *NewFD = nullptr;
  7012. bool isInline = D.getDeclSpec().isInlineSpecified();
  7013. if (!SemaRef.getLangOpts().CPlusPlus) {
  7014. // Determine whether the function was written with a
  7015. // prototype. This true when:
  7016. // - there is a prototype in the declarator, or
  7017. // - the type R of the function is some kind of typedef or other non-
  7018. // attributed reference to a type name (which eventually refers to a
  7019. // function type).
  7020. bool HasPrototype =
  7021. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7022. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7023. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  7024. D.getLocStart(), NameInfo, R,
  7025. TInfo, SC, isInline,
  7026. HasPrototype, false);
  7027. if (D.isInvalidType())
  7028. NewFD->setInvalidDecl();
  7029. return NewFD;
  7030. }
  7031. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7032. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7033. // Check that the return type is not an abstract class type.
  7034. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7035. // the class has been completely parsed.
  7036. if (!DC->isRecord() &&
  7037. SemaRef.RequireNonAbstractType(
  7038. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7039. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7040. D.setInvalidType();
  7041. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7042. // This is a C++ constructor declaration.
  7043. assert(DC->isRecord() &&
  7044. "Constructors can only be declared in a member context");
  7045. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7046. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7047. D.getLocStart(), NameInfo,
  7048. R, TInfo, isExplicit, isInline,
  7049. /*isImplicitlyDeclared=*/false,
  7050. isConstexpr);
  7051. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7052. // This is a C++ destructor declaration.
  7053. if (DC->isRecord()) {
  7054. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7055. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7056. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7057. SemaRef.Context, Record,
  7058. D.getLocStart(),
  7059. NameInfo, R, TInfo, isInline,
  7060. /*isImplicitlyDeclared=*/false);
  7061. // If the class is complete, then we now create the implicit exception
  7062. // specification. If the class is incomplete or dependent, we can't do
  7063. // it yet.
  7064. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  7065. Record->getDefinition() && !Record->isBeingDefined() &&
  7066. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  7067. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  7068. }
  7069. IsVirtualOkay = true;
  7070. return NewDD;
  7071. } else {
  7072. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7073. D.setInvalidType();
  7074. // Create a FunctionDecl to satisfy the function definition parsing
  7075. // code path.
  7076. return FunctionDecl::Create(SemaRef.Context, DC,
  7077. D.getLocStart(),
  7078. D.getIdentifierLoc(), Name, R, TInfo,
  7079. SC, isInline,
  7080. /*hasPrototype=*/true, isConstexpr);
  7081. }
  7082. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7083. if (!DC->isRecord()) {
  7084. SemaRef.Diag(D.getIdentifierLoc(),
  7085. diag::err_conv_function_not_member);
  7086. return nullptr;
  7087. }
  7088. SemaRef.CheckConversionDeclarator(D, R, SC);
  7089. IsVirtualOkay = true;
  7090. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7091. D.getLocStart(), NameInfo,
  7092. R, TInfo, isInline, isExplicit,
  7093. isConstexpr, SourceLocation());
  7094. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7095. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7096. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
  7097. isExplicit, NameInfo, R, TInfo,
  7098. D.getLocEnd());
  7099. } else if (DC->isRecord()) {
  7100. // If the name of the function is the same as the name of the record,
  7101. // then this must be an invalid constructor that has a return type.
  7102. // (The parser checks for a return type and makes the declarator a
  7103. // constructor if it has no return type).
  7104. if (Name.getAsIdentifierInfo() &&
  7105. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7106. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7107. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7108. << SourceRange(D.getIdentifierLoc());
  7109. return nullptr;
  7110. }
  7111. // This is a C++ method declaration.
  7112. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  7113. cast<CXXRecordDecl>(DC),
  7114. D.getLocStart(), NameInfo, R,
  7115. TInfo, SC, isInline,
  7116. isConstexpr, SourceLocation());
  7117. IsVirtualOkay = !Ret->isStatic();
  7118. return Ret;
  7119. } else {
  7120. bool isFriend =
  7121. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7122. if (!isFriend && SemaRef.CurContext->isRecord())
  7123. return nullptr;
  7124. // Determine whether the function was written with a
  7125. // prototype. This true when:
  7126. // - we're in C++ (where every function has a prototype),
  7127. return FunctionDecl::Create(SemaRef.Context, DC,
  7128. D.getLocStart(),
  7129. NameInfo, R, TInfo, SC, isInline,
  7130. true/*HasPrototype*/, isConstexpr);
  7131. }
  7132. }
  7133. enum OpenCLParamType {
  7134. ValidKernelParam,
  7135. PtrPtrKernelParam,
  7136. PtrKernelParam,
  7137. InvalidAddrSpacePtrKernelParam,
  7138. InvalidKernelParam,
  7139. RecordKernelParam
  7140. };
  7141. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7142. if (PT->isPointerType()) {
  7143. QualType PointeeType = PT->getPointeeType();
  7144. if (PointeeType->isPointerType())
  7145. return PtrPtrKernelParam;
  7146. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7147. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7148. PointeeType.getAddressSpace() == LangAS::Default)
  7149. return InvalidAddrSpacePtrKernelParam;
  7150. return PtrKernelParam;
  7151. }
  7152. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  7153. // be used as builtin types.
  7154. if (PT->isImageType())
  7155. return PtrKernelParam;
  7156. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7157. return InvalidKernelParam;
  7158. // OpenCL extension spec v1.2 s9.5:
  7159. // This extension adds support for half scalar and vector types as built-in
  7160. // types that can be used for arithmetic operations, conversions etc.
  7161. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7162. return InvalidKernelParam;
  7163. if (PT->isRecordType())
  7164. return RecordKernelParam;
  7165. return ValidKernelParam;
  7166. }
  7167. static void checkIsValidOpenCLKernelParameter(
  7168. Sema &S,
  7169. Declarator &D,
  7170. ParmVarDecl *Param,
  7171. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7172. QualType PT = Param->getType();
  7173. // Cache the valid types we encounter to avoid rechecking structs that are
  7174. // used again
  7175. if (ValidTypes.count(PT.getTypePtr()))
  7176. return;
  7177. switch (getOpenCLKernelParameterType(S, PT)) {
  7178. case PtrPtrKernelParam:
  7179. // OpenCL v1.2 s6.9.a:
  7180. // A kernel function argument cannot be declared as a
  7181. // pointer to a pointer type.
  7182. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7183. D.setInvalidType();
  7184. return;
  7185. case InvalidAddrSpacePtrKernelParam:
  7186. // OpenCL v1.0 s6.5:
  7187. // __kernel function arguments declared to be a pointer of a type can point
  7188. // to one of the following address spaces only : __global, __local or
  7189. // __constant.
  7190. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7191. D.setInvalidType();
  7192. return;
  7193. // OpenCL v1.2 s6.9.k:
  7194. // Arguments to kernel functions in a program cannot be declared with the
  7195. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7196. // uintptr_t or a struct and/or union that contain fields declared to be
  7197. // one of these built-in scalar types.
  7198. case InvalidKernelParam:
  7199. // OpenCL v1.2 s6.8 n:
  7200. // A kernel function argument cannot be declared
  7201. // of event_t type.
  7202. // Do not diagnose half type since it is diagnosed as invalid argument
  7203. // type for any function elsewhere.
  7204. if (!PT->isHalfType())
  7205. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7206. D.setInvalidType();
  7207. return;
  7208. case PtrKernelParam:
  7209. case ValidKernelParam:
  7210. ValidTypes.insert(PT.getTypePtr());
  7211. return;
  7212. case RecordKernelParam:
  7213. break;
  7214. }
  7215. // Track nested structs we will inspect
  7216. SmallVector<const Decl *, 4> VisitStack;
  7217. // Track where we are in the nested structs. Items will migrate from
  7218. // VisitStack to HistoryStack as we do the DFS for bad field.
  7219. SmallVector<const FieldDecl *, 4> HistoryStack;
  7220. HistoryStack.push_back(nullptr);
  7221. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  7222. VisitStack.push_back(PD);
  7223. assert(VisitStack.back() && "First decl null?");
  7224. do {
  7225. const Decl *Next = VisitStack.pop_back_val();
  7226. if (!Next) {
  7227. assert(!HistoryStack.empty());
  7228. // Found a marker, we have gone up a level
  7229. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7230. ValidTypes.insert(Hist->getType().getTypePtr());
  7231. continue;
  7232. }
  7233. // Adds everything except the original parameter declaration (which is not a
  7234. // field itself) to the history stack.
  7235. const RecordDecl *RD;
  7236. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7237. HistoryStack.push_back(Field);
  7238. RD = Field->getType()->castAs<RecordType>()->getDecl();
  7239. } else {
  7240. RD = cast<RecordDecl>(Next);
  7241. }
  7242. // Add a null marker so we know when we've gone back up a level
  7243. VisitStack.push_back(nullptr);
  7244. for (const auto *FD : RD->fields()) {
  7245. QualType QT = FD->getType();
  7246. if (ValidTypes.count(QT.getTypePtr()))
  7247. continue;
  7248. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7249. if (ParamType == ValidKernelParam)
  7250. continue;
  7251. if (ParamType == RecordKernelParam) {
  7252. VisitStack.push_back(FD);
  7253. continue;
  7254. }
  7255. // OpenCL v1.2 s6.9.p:
  7256. // Arguments to kernel functions that are declared to be a struct or union
  7257. // do not allow OpenCL objects to be passed as elements of the struct or
  7258. // union.
  7259. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7260. ParamType == InvalidAddrSpacePtrKernelParam) {
  7261. S.Diag(Param->getLocation(),
  7262. diag::err_record_with_pointers_kernel_param)
  7263. << PT->isUnionType()
  7264. << PT;
  7265. } else {
  7266. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7267. }
  7268. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  7269. << PD->getDeclName();
  7270. // We have an error, now let's go back up through history and show where
  7271. // the offending field came from
  7272. for (ArrayRef<const FieldDecl *>::const_iterator
  7273. I = HistoryStack.begin() + 1,
  7274. E = HistoryStack.end();
  7275. I != E; ++I) {
  7276. const FieldDecl *OuterField = *I;
  7277. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7278. << OuterField->getType();
  7279. }
  7280. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7281. << QT->isPointerType()
  7282. << QT;
  7283. D.setInvalidType();
  7284. return;
  7285. }
  7286. } while (!VisitStack.empty());
  7287. }
  7288. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7289. /// elaborated type specifier in the specified context, and lookup finds
  7290. /// nothing.
  7291. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7292. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7293. DC = DC->getParent();
  7294. return DC;
  7295. }
  7296. /// Find the Scope in which a tag is implicitly declared if we see an
  7297. /// elaborated type specifier in the specified context, and lookup finds
  7298. /// nothing.
  7299. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7300. while (S->isClassScope() ||
  7301. (LangOpts.CPlusPlus &&
  7302. S->isFunctionPrototypeScope()) ||
  7303. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7304. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7305. S = S->getParent();
  7306. return S;
  7307. }
  7308. NamedDecl*
  7309. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7310. TypeSourceInfo *TInfo, LookupResult &Previous,
  7311. MultiTemplateParamsArg TemplateParamLists,
  7312. bool &AddToScope) {
  7313. QualType R = TInfo->getType();
  7314. assert(R.getTypePtr()->isFunctionType());
  7315. // TODO: consider using NameInfo for diagnostic.
  7316. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7317. DeclarationName Name = NameInfo.getName();
  7318. StorageClass SC = getFunctionStorageClass(*this, D);
  7319. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7320. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7321. diag::err_invalid_thread)
  7322. << DeclSpec::getSpecifierName(TSCS);
  7323. if (D.isFirstDeclarationOfMember())
  7324. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7325. D.getIdentifierLoc());
  7326. bool isFriend = false;
  7327. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7328. bool isMemberSpecialization = false;
  7329. bool isFunctionTemplateSpecialization = false;
  7330. bool isDependentClassScopeExplicitSpecialization = false;
  7331. bool HasExplicitTemplateArgs = false;
  7332. TemplateArgumentListInfo TemplateArgs;
  7333. bool isVirtualOkay = false;
  7334. DeclContext *OriginalDC = DC;
  7335. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7336. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7337. isVirtualOkay);
  7338. if (!NewFD) return nullptr;
  7339. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7340. NewFD->setTopLevelDeclInObjCContainer();
  7341. // Set the lexical context. If this is a function-scope declaration, or has a
  7342. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7343. // context will be different from the semantic context.
  7344. NewFD->setLexicalDeclContext(CurContext);
  7345. if (IsLocalExternDecl)
  7346. NewFD->setLocalExternDecl();
  7347. if (getLangOpts().CPlusPlus) {
  7348. bool isInline = D.getDeclSpec().isInlineSpecified();
  7349. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7350. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7351. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7352. bool isConcept = D.getDeclSpec().isConceptSpecified();
  7353. isFriend = D.getDeclSpec().isFriendSpecified();
  7354. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7355. // C++ [class.friend]p5
  7356. // A function can be defined in a friend declaration of a
  7357. // class . . . . Such a function is implicitly inline.
  7358. NewFD->setImplicitlyInline();
  7359. }
  7360. // If this is a method defined in an __interface, and is not a constructor
  7361. // or an overloaded operator, then set the pure flag (isVirtual will already
  7362. // return true).
  7363. if (const CXXRecordDecl *Parent =
  7364. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7365. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7366. NewFD->setPure(true);
  7367. // C++ [class.union]p2
  7368. // A union can have member functions, but not virtual functions.
  7369. if (isVirtual && Parent->isUnion())
  7370. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7371. }
  7372. SetNestedNameSpecifier(NewFD, D);
  7373. isMemberSpecialization = false;
  7374. isFunctionTemplateSpecialization = false;
  7375. if (D.isInvalidType())
  7376. NewFD->setInvalidDecl();
  7377. // Match up the template parameter lists with the scope specifier, then
  7378. // determine whether we have a template or a template specialization.
  7379. bool Invalid = false;
  7380. if (TemplateParameterList *TemplateParams =
  7381. MatchTemplateParametersToScopeSpecifier(
  7382. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  7383. D.getCXXScopeSpec(),
  7384. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  7385. ? D.getName().TemplateId
  7386. : nullptr,
  7387. TemplateParamLists, isFriend, isMemberSpecialization,
  7388. Invalid)) {
  7389. if (TemplateParams->size() > 0) {
  7390. // This is a function template
  7391. // Check that we can declare a template here.
  7392. if (CheckTemplateDeclScope(S, TemplateParams))
  7393. NewFD->setInvalidDecl();
  7394. // A destructor cannot be a template.
  7395. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7396. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7397. NewFD->setInvalidDecl();
  7398. }
  7399. // If we're adding a template to a dependent context, we may need to
  7400. // rebuilding some of the types used within the template parameter list,
  7401. // now that we know what the current instantiation is.
  7402. if (DC->isDependentContext()) {
  7403. ContextRAII SavedContext(*this, DC);
  7404. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7405. Invalid = true;
  7406. }
  7407. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7408. NewFD->getLocation(),
  7409. Name, TemplateParams,
  7410. NewFD);
  7411. FunctionTemplate->setLexicalDeclContext(CurContext);
  7412. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7413. // For source fidelity, store the other template param lists.
  7414. if (TemplateParamLists.size() > 1) {
  7415. NewFD->setTemplateParameterListsInfo(Context,
  7416. TemplateParamLists.drop_back(1));
  7417. }
  7418. } else {
  7419. // This is a function template specialization.
  7420. isFunctionTemplateSpecialization = true;
  7421. // For source fidelity, store all the template param lists.
  7422. if (TemplateParamLists.size() > 0)
  7423. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7424. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7425. if (isFriend) {
  7426. // We want to remove the "template<>", found here.
  7427. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7428. // If we remove the template<> and the name is not a
  7429. // template-id, we're actually silently creating a problem:
  7430. // the friend declaration will refer to an untemplated decl,
  7431. // and clearly the user wants a template specialization. So
  7432. // we need to insert '<>' after the name.
  7433. SourceLocation InsertLoc;
  7434. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  7435. InsertLoc = D.getName().getSourceRange().getEnd();
  7436. InsertLoc = getLocForEndOfToken(InsertLoc);
  7437. }
  7438. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7439. << Name << RemoveRange
  7440. << FixItHint::CreateRemoval(RemoveRange)
  7441. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7442. }
  7443. }
  7444. }
  7445. else {
  7446. // All template param lists were matched against the scope specifier:
  7447. // this is NOT (an explicit specialization of) a template.
  7448. if (TemplateParamLists.size() > 0)
  7449. // For source fidelity, store all the template param lists.
  7450. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7451. }
  7452. if (Invalid) {
  7453. NewFD->setInvalidDecl();
  7454. if (FunctionTemplate)
  7455. FunctionTemplate->setInvalidDecl();
  7456. }
  7457. // C++ [dcl.fct.spec]p5:
  7458. // The virtual specifier shall only be used in declarations of
  7459. // nonstatic class member functions that appear within a
  7460. // member-specification of a class declaration; see 10.3.
  7461. //
  7462. if (isVirtual && !NewFD->isInvalidDecl()) {
  7463. if (!isVirtualOkay) {
  7464. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7465. diag::err_virtual_non_function);
  7466. } else if (!CurContext->isRecord()) {
  7467. // 'virtual' was specified outside of the class.
  7468. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7469. diag::err_virtual_out_of_class)
  7470. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7471. } else if (NewFD->getDescribedFunctionTemplate()) {
  7472. // C++ [temp.mem]p3:
  7473. // A member function template shall not be virtual.
  7474. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7475. diag::err_virtual_member_function_template)
  7476. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7477. } else {
  7478. // Okay: Add virtual to the method.
  7479. NewFD->setVirtualAsWritten(true);
  7480. }
  7481. if (getLangOpts().CPlusPlus14 &&
  7482. NewFD->getReturnType()->isUndeducedType())
  7483. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7484. }
  7485. if (getLangOpts().CPlusPlus14 &&
  7486. (NewFD->isDependentContext() ||
  7487. (isFriend && CurContext->isDependentContext())) &&
  7488. NewFD->getReturnType()->isUndeducedType()) {
  7489. // If the function template is referenced directly (for instance, as a
  7490. // member of the current instantiation), pretend it has a dependent type.
  7491. // This is not really justified by the standard, but is the only sane
  7492. // thing to do.
  7493. // FIXME: For a friend function, we have not marked the function as being
  7494. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7495. const FunctionProtoType *FPT =
  7496. NewFD->getType()->castAs<FunctionProtoType>();
  7497. QualType Result =
  7498. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7499. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7500. FPT->getExtProtoInfo()));
  7501. }
  7502. // C++ [dcl.fct.spec]p3:
  7503. // The inline specifier shall not appear on a block scope function
  7504. // declaration.
  7505. if (isInline && !NewFD->isInvalidDecl()) {
  7506. if (CurContext->isFunctionOrMethod()) {
  7507. // 'inline' is not allowed on block scope function declaration.
  7508. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7509. diag::err_inline_declaration_block_scope) << Name
  7510. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7511. }
  7512. }
  7513. // C++ [dcl.fct.spec]p6:
  7514. // The explicit specifier shall be used only in the declaration of a
  7515. // constructor or conversion function within its class definition;
  7516. // see 12.3.1 and 12.3.2.
  7517. if (isExplicit && !NewFD->isInvalidDecl() &&
  7518. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7519. if (!CurContext->isRecord()) {
  7520. // 'explicit' was specified outside of the class.
  7521. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7522. diag::err_explicit_out_of_class)
  7523. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7524. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7525. !isa<CXXConversionDecl>(NewFD)) {
  7526. // 'explicit' was specified on a function that wasn't a constructor
  7527. // or conversion function.
  7528. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7529. diag::err_explicit_non_ctor_or_conv_function)
  7530. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7531. }
  7532. }
  7533. if (isConstexpr) {
  7534. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7535. // are implicitly inline.
  7536. NewFD->setImplicitlyInline();
  7537. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7538. // be either constructors or to return a literal type. Therefore,
  7539. // destructors cannot be declared constexpr.
  7540. if (isa<CXXDestructorDecl>(NewFD))
  7541. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7542. }
  7543. if (isConcept) {
  7544. // This is a function concept.
  7545. if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
  7546. FTD->setConcept();
  7547. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7548. // applied only to the definition of a function template [...]
  7549. if (!D.isFunctionDefinition()) {
  7550. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7551. diag::err_function_concept_not_defined);
  7552. NewFD->setInvalidDecl();
  7553. }
  7554. // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
  7555. // have no exception-specification and is treated as if it were specified
  7556. // with noexcept(true) (15.4). [...]
  7557. if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
  7558. if (FPT->hasExceptionSpec()) {
  7559. SourceRange Range;
  7560. if (D.isFunctionDeclarator())
  7561. Range = D.getFunctionTypeInfo().getExceptionSpecRange();
  7562. Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
  7563. << FixItHint::CreateRemoval(Range);
  7564. NewFD->setInvalidDecl();
  7565. } else {
  7566. Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
  7567. }
  7568. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7569. // following restrictions:
  7570. // - The declared return type shall have the type bool.
  7571. if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
  7572. Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
  7573. NewFD->setInvalidDecl();
  7574. }
  7575. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7576. // following restrictions:
  7577. // - The declaration's parameter list shall be equivalent to an empty
  7578. // parameter list.
  7579. if (FPT->getNumParams() > 0 || FPT->isVariadic())
  7580. Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
  7581. }
  7582. // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
  7583. // implicity defined to be a constexpr declaration (implicitly inline)
  7584. NewFD->setImplicitlyInline();
  7585. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  7586. // be declared with the thread_local, inline, friend, or constexpr
  7587. // specifiers, [...]
  7588. if (isInline) {
  7589. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7590. diag::err_concept_decl_invalid_specifiers)
  7591. << 1 << 1;
  7592. NewFD->setInvalidDecl(true);
  7593. }
  7594. if (isFriend) {
  7595. Diag(D.getDeclSpec().getFriendSpecLoc(),
  7596. diag::err_concept_decl_invalid_specifiers)
  7597. << 1 << 2;
  7598. NewFD->setInvalidDecl(true);
  7599. }
  7600. if (isConstexpr) {
  7601. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7602. diag::err_concept_decl_invalid_specifiers)
  7603. << 1 << 3;
  7604. NewFD->setInvalidDecl(true);
  7605. }
  7606. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7607. // applied only to the definition of a function template or variable
  7608. // template, declared in namespace scope.
  7609. if (isFunctionTemplateSpecialization) {
  7610. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7611. diag::err_concept_specified_specialization) << 1;
  7612. NewFD->setInvalidDecl(true);
  7613. return NewFD;
  7614. }
  7615. }
  7616. // If __module_private__ was specified, mark the function accordingly.
  7617. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7618. if (isFunctionTemplateSpecialization) {
  7619. SourceLocation ModulePrivateLoc
  7620. = D.getDeclSpec().getModulePrivateSpecLoc();
  7621. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7622. << 0
  7623. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7624. } else {
  7625. NewFD->setModulePrivate();
  7626. if (FunctionTemplate)
  7627. FunctionTemplate->setModulePrivate();
  7628. }
  7629. }
  7630. if (isFriend) {
  7631. if (FunctionTemplate) {
  7632. FunctionTemplate->setObjectOfFriendDecl();
  7633. FunctionTemplate->setAccess(AS_public);
  7634. }
  7635. NewFD->setObjectOfFriendDecl();
  7636. NewFD->setAccess(AS_public);
  7637. }
  7638. // If a function is defined as defaulted or deleted, mark it as such now.
  7639. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7640. // definition kind to FDK_Definition.
  7641. switch (D.getFunctionDefinitionKind()) {
  7642. case FDK_Declaration:
  7643. case FDK_Definition:
  7644. break;
  7645. case FDK_Defaulted:
  7646. NewFD->setDefaulted();
  7647. break;
  7648. case FDK_Deleted:
  7649. NewFD->setDeletedAsWritten();
  7650. break;
  7651. }
  7652. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7653. D.isFunctionDefinition()) {
  7654. // C++ [class.mfct]p2:
  7655. // A member function may be defined (8.4) in its class definition, in
  7656. // which case it is an inline member function (7.1.2)
  7657. NewFD->setImplicitlyInline();
  7658. }
  7659. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7660. !CurContext->isRecord()) {
  7661. // C++ [class.static]p1:
  7662. // A data or function member of a class may be declared static
  7663. // in a class definition, in which case it is a static member of
  7664. // the class.
  7665. // Complain about the 'static' specifier if it's on an out-of-line
  7666. // member function definition.
  7667. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7668. diag::err_static_out_of_line)
  7669. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7670. }
  7671. // C++11 [except.spec]p15:
  7672. // A deallocation function with no exception-specification is treated
  7673. // as if it were specified with noexcept(true).
  7674. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7675. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7676. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7677. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7678. NewFD->setType(Context.getFunctionType(
  7679. FPT->getReturnType(), FPT->getParamTypes(),
  7680. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7681. }
  7682. // Filter out previous declarations that don't match the scope.
  7683. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7684. D.getCXXScopeSpec().isNotEmpty() ||
  7685. isMemberSpecialization ||
  7686. isFunctionTemplateSpecialization);
  7687. // Handle GNU asm-label extension (encoded as an attribute).
  7688. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7689. // The parser guarantees this is a string.
  7690. StringLiteral *SE = cast<StringLiteral>(E);
  7691. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7692. SE->getString(), 0));
  7693. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7694. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7695. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7696. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7697. if (isDeclExternC(NewFD)) {
  7698. NewFD->addAttr(I->second);
  7699. ExtnameUndeclaredIdentifiers.erase(I);
  7700. } else
  7701. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7702. << /*Variable*/0 << NewFD;
  7703. }
  7704. }
  7705. // Copy the parameter declarations from the declarator D to the function
  7706. // declaration NewFD, if they are available. First scavenge them into Params.
  7707. SmallVector<ParmVarDecl*, 16> Params;
  7708. unsigned FTIIdx;
  7709. if (D.isFunctionDeclarator(FTIIdx)) {
  7710. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7711. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7712. // function that takes no arguments, not a function that takes a
  7713. // single void argument.
  7714. // We let through "const void" here because Sema::GetTypeForDeclarator
  7715. // already checks for that case.
  7716. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7717. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7718. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7719. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7720. Param->setDeclContext(NewFD);
  7721. Params.push_back(Param);
  7722. if (Param->isInvalidDecl())
  7723. NewFD->setInvalidDecl();
  7724. }
  7725. }
  7726. if (!getLangOpts().CPlusPlus) {
  7727. // In C, find all the tag declarations from the prototype and move them
  7728. // into the function DeclContext. Remove them from the surrounding tag
  7729. // injection context of the function, which is typically but not always
  7730. // the TU.
  7731. DeclContext *PrototypeTagContext =
  7732. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7733. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7734. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7735. // We don't want to reparent enumerators. Look at their parent enum
  7736. // instead.
  7737. if (!TD) {
  7738. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7739. TD = cast<EnumDecl>(ECD->getDeclContext());
  7740. }
  7741. if (!TD)
  7742. continue;
  7743. DeclContext *TagDC = TD->getLexicalDeclContext();
  7744. if (!TagDC->containsDecl(TD))
  7745. continue;
  7746. TagDC->removeDecl(TD);
  7747. TD->setDeclContext(NewFD);
  7748. NewFD->addDecl(TD);
  7749. // Preserve the lexical DeclContext if it is not the surrounding tag
  7750. // injection context of the FD. In this example, the semantic context of
  7751. // E will be f and the lexical context will be S, while both the
  7752. // semantic and lexical contexts of S will be f:
  7753. // void f(struct S { enum E { a } f; } s);
  7754. if (TagDC != PrototypeTagContext)
  7755. TD->setLexicalDeclContext(TagDC);
  7756. }
  7757. }
  7758. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7759. // When we're declaring a function with a typedef, typeof, etc as in the
  7760. // following example, we'll need to synthesize (unnamed)
  7761. // parameters for use in the declaration.
  7762. //
  7763. // @code
  7764. // typedef void fn(int);
  7765. // fn f;
  7766. // @endcode
  7767. // Synthesize a parameter for each argument type.
  7768. for (const auto &AI : FT->param_types()) {
  7769. ParmVarDecl *Param =
  7770. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7771. Param->setScopeInfo(0, Params.size());
  7772. Params.push_back(Param);
  7773. }
  7774. } else {
  7775. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7776. "Should not need args for typedef of non-prototype fn");
  7777. }
  7778. // Finally, we know we have the right number of parameters, install them.
  7779. NewFD->setParams(Params);
  7780. if (D.getDeclSpec().isNoreturnSpecified())
  7781. NewFD->addAttr(
  7782. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7783. Context, 0));
  7784. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7785. // because all functions have linkage.
  7786. if (!NewFD->isInvalidDecl() &&
  7787. NewFD->getReturnType()->isVariablyModifiedType()) {
  7788. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7789. NewFD->setInvalidDecl();
  7790. }
  7791. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7792. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7793. !NewFD->hasAttr<SectionAttr>()) {
  7794. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7795. PragmaClangTextSection.SectionName,
  7796. PragmaClangTextSection.PragmaLocation));
  7797. }
  7798. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7799. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7800. !NewFD->hasAttr<SectionAttr>()) {
  7801. NewFD->addAttr(
  7802. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7803. CodeSegStack.CurrentValue->getString(),
  7804. CodeSegStack.CurrentPragmaLocation));
  7805. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7806. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7807. ASTContext::PSF_Read,
  7808. NewFD))
  7809. NewFD->dropAttr<SectionAttr>();
  7810. }
  7811. // Handle attributes.
  7812. ProcessDeclAttributes(S, NewFD, D);
  7813. if (getLangOpts().OpenCL) {
  7814. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7815. // type declaration will generate a compilation error.
  7816. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7817. if (AddressSpace != LangAS::Default) {
  7818. Diag(NewFD->getLocation(),
  7819. diag::err_opencl_return_value_with_address_space);
  7820. NewFD->setInvalidDecl();
  7821. }
  7822. }
  7823. if (!getLangOpts().CPlusPlus) {
  7824. // Perform semantic checking on the function declaration.
  7825. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7826. CheckMain(NewFD, D.getDeclSpec());
  7827. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7828. CheckMSVCRTEntryPoint(NewFD);
  7829. if (!NewFD->isInvalidDecl())
  7830. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7831. isMemberSpecialization));
  7832. else if (!Previous.empty())
  7833. // Recover gracefully from an invalid redeclaration.
  7834. D.setRedeclaration(true);
  7835. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7836. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7837. "previous declaration set still overloaded");
  7838. // Diagnose no-prototype function declarations with calling conventions that
  7839. // don't support variadic calls. Only do this in C and do it after merging
  7840. // possibly prototyped redeclarations.
  7841. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7842. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7843. CallingConv CC = FT->getExtInfo().getCC();
  7844. if (!supportsVariadicCall(CC)) {
  7845. // Windows system headers sometimes accidentally use stdcall without
  7846. // (void) parameters, so we relax this to a warning.
  7847. int DiagID =
  7848. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7849. Diag(NewFD->getLocation(), DiagID)
  7850. << FunctionType::getNameForCallConv(CC);
  7851. }
  7852. }
  7853. } else {
  7854. // C++11 [replacement.functions]p3:
  7855. // The program's definitions shall not be specified as inline.
  7856. //
  7857. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7858. //
  7859. // Suppress the diagnostic if the function is __attribute__((used)), since
  7860. // that forces an external definition to be emitted.
  7861. if (D.getDeclSpec().isInlineSpecified() &&
  7862. NewFD->isReplaceableGlobalAllocationFunction() &&
  7863. !NewFD->hasAttr<UsedAttr>())
  7864. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7865. diag::ext_operator_new_delete_declared_inline)
  7866. << NewFD->getDeclName();
  7867. // If the declarator is a template-id, translate the parser's template
  7868. // argument list into our AST format.
  7869. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  7870. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7871. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7872. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7873. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7874. TemplateId->NumArgs);
  7875. translateTemplateArguments(TemplateArgsPtr,
  7876. TemplateArgs);
  7877. HasExplicitTemplateArgs = true;
  7878. if (NewFD->isInvalidDecl()) {
  7879. HasExplicitTemplateArgs = false;
  7880. } else if (FunctionTemplate) {
  7881. // Function template with explicit template arguments.
  7882. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7883. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7884. HasExplicitTemplateArgs = false;
  7885. } else {
  7886. assert((isFunctionTemplateSpecialization ||
  7887. D.getDeclSpec().isFriendSpecified()) &&
  7888. "should have a 'template<>' for this decl");
  7889. // "friend void foo<>(int);" is an implicit specialization decl.
  7890. isFunctionTemplateSpecialization = true;
  7891. }
  7892. } else if (isFriend && isFunctionTemplateSpecialization) {
  7893. // This combination is only possible in a recovery case; the user
  7894. // wrote something like:
  7895. // template <> friend void foo(int);
  7896. // which we're recovering from as if the user had written:
  7897. // friend void foo<>(int);
  7898. // Go ahead and fake up a template id.
  7899. HasExplicitTemplateArgs = true;
  7900. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7901. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7902. }
  7903. // We do not add HD attributes to specializations here because
  7904. // they may have different constexpr-ness compared to their
  7905. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7906. // may end up with different effective targets. Instead, a
  7907. // specialization inherits its target attributes from its template
  7908. // in the CheckFunctionTemplateSpecialization() call below.
  7909. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7910. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7911. // If it's a friend (and only if it's a friend), it's possible
  7912. // that either the specialized function type or the specialized
  7913. // template is dependent, and therefore matching will fail. In
  7914. // this case, don't check the specialization yet.
  7915. bool InstantiationDependent = false;
  7916. if (isFunctionTemplateSpecialization && isFriend &&
  7917. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7918. TemplateSpecializationType::anyDependentTemplateArguments(
  7919. TemplateArgs,
  7920. InstantiationDependent))) {
  7921. assert(HasExplicitTemplateArgs &&
  7922. "friend function specialization without template args");
  7923. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7924. Previous))
  7925. NewFD->setInvalidDecl();
  7926. } else if (isFunctionTemplateSpecialization) {
  7927. if (CurContext->isDependentContext() && CurContext->isRecord()
  7928. && !isFriend) {
  7929. isDependentClassScopeExplicitSpecialization = true;
  7930. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  7931. diag::ext_function_specialization_in_class :
  7932. diag::err_function_specialization_in_class)
  7933. << NewFD->getDeclName();
  7934. } else if (!NewFD->isInvalidDecl() &&
  7935. CheckFunctionTemplateSpecialization(
  7936. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7937. Previous))
  7938. NewFD->setInvalidDecl();
  7939. // C++ [dcl.stc]p1:
  7940. // A storage-class-specifier shall not be specified in an explicit
  7941. // specialization (14.7.3)
  7942. FunctionTemplateSpecializationInfo *Info =
  7943. NewFD->getTemplateSpecializationInfo();
  7944. if (Info && SC != SC_None) {
  7945. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7946. Diag(NewFD->getLocation(),
  7947. diag::err_explicit_specialization_inconsistent_storage_class)
  7948. << SC
  7949. << FixItHint::CreateRemoval(
  7950. D.getDeclSpec().getStorageClassSpecLoc());
  7951. else
  7952. Diag(NewFD->getLocation(),
  7953. diag::ext_explicit_specialization_storage_class)
  7954. << FixItHint::CreateRemoval(
  7955. D.getDeclSpec().getStorageClassSpecLoc());
  7956. }
  7957. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7958. if (CheckMemberSpecialization(NewFD, Previous))
  7959. NewFD->setInvalidDecl();
  7960. }
  7961. // Perform semantic checking on the function declaration.
  7962. if (!isDependentClassScopeExplicitSpecialization) {
  7963. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7964. CheckMain(NewFD, D.getDeclSpec());
  7965. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7966. CheckMSVCRTEntryPoint(NewFD);
  7967. if (!NewFD->isInvalidDecl())
  7968. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7969. isMemberSpecialization));
  7970. else if (!Previous.empty())
  7971. // Recover gracefully from an invalid redeclaration.
  7972. D.setRedeclaration(true);
  7973. }
  7974. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7975. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7976. "previous declaration set still overloaded");
  7977. NamedDecl *PrincipalDecl = (FunctionTemplate
  7978. ? cast<NamedDecl>(FunctionTemplate)
  7979. : NewFD);
  7980. if (isFriend && NewFD->getPreviousDecl()) {
  7981. AccessSpecifier Access = AS_public;
  7982. if (!NewFD->isInvalidDecl())
  7983. Access = NewFD->getPreviousDecl()->getAccess();
  7984. NewFD->setAccess(Access);
  7985. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7986. }
  7987. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7988. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7989. PrincipalDecl->setNonMemberOperator();
  7990. // If we have a function template, check the template parameter
  7991. // list. This will check and merge default template arguments.
  7992. if (FunctionTemplate) {
  7993. FunctionTemplateDecl *PrevTemplate =
  7994. FunctionTemplate->getPreviousDecl();
  7995. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7996. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7997. : nullptr,
  7998. D.getDeclSpec().isFriendSpecified()
  7999. ? (D.isFunctionDefinition()
  8000. ? TPC_FriendFunctionTemplateDefinition
  8001. : TPC_FriendFunctionTemplate)
  8002. : (D.getCXXScopeSpec().isSet() &&
  8003. DC && DC->isRecord() &&
  8004. DC->isDependentContext())
  8005. ? TPC_ClassTemplateMember
  8006. : TPC_FunctionTemplate);
  8007. }
  8008. if (NewFD->isInvalidDecl()) {
  8009. // Ignore all the rest of this.
  8010. } else if (!D.isRedeclaration()) {
  8011. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8012. AddToScope };
  8013. // Fake up an access specifier if it's supposed to be a class member.
  8014. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8015. NewFD->setAccess(AS_public);
  8016. // Qualified decls generally require a previous declaration.
  8017. if (D.getCXXScopeSpec().isSet()) {
  8018. // ...with the major exception of templated-scope or
  8019. // dependent-scope friend declarations.
  8020. // TODO: we currently also suppress this check in dependent
  8021. // contexts because (1) the parameter depth will be off when
  8022. // matching friend templates and (2) we might actually be
  8023. // selecting a friend based on a dependent factor. But there
  8024. // are situations where these conditions don't apply and we
  8025. // can actually do this check immediately.
  8026. if (isFriend &&
  8027. (TemplateParamLists.size() ||
  8028. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8029. CurContext->isDependentContext())) {
  8030. // ignore these
  8031. } else {
  8032. // The user tried to provide an out-of-line definition for a
  8033. // function that is a member of a class or namespace, but there
  8034. // was no such member function declared (C++ [class.mfct]p2,
  8035. // C++ [namespace.memdef]p2). For example:
  8036. //
  8037. // class X {
  8038. // void f() const;
  8039. // };
  8040. //
  8041. // void X::f() { } // ill-formed
  8042. //
  8043. // Complain about this problem, and attempt to suggest close
  8044. // matches (e.g., those that differ only in cv-qualifiers and
  8045. // whether the parameter types are references).
  8046. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8047. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8048. AddToScope = ExtraArgs.AddToScope;
  8049. return Result;
  8050. }
  8051. }
  8052. // Unqualified local friend declarations are required to resolve
  8053. // to something.
  8054. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8055. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8056. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8057. AddToScope = ExtraArgs.AddToScope;
  8058. return Result;
  8059. }
  8060. }
  8061. } else if (!D.isFunctionDefinition() &&
  8062. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8063. !isFriend && !isFunctionTemplateSpecialization &&
  8064. !isMemberSpecialization) {
  8065. // An out-of-line member function declaration must also be a
  8066. // definition (C++ [class.mfct]p2).
  8067. // Note that this is not the case for explicit specializations of
  8068. // function templates or member functions of class templates, per
  8069. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8070. // extension for compatibility with old SWIG code which likes to
  8071. // generate them.
  8072. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8073. << D.getCXXScopeSpec().getRange();
  8074. }
  8075. }
  8076. ProcessPragmaWeak(S, NewFD);
  8077. checkAttributesAfterMerging(*this, *NewFD);
  8078. AddKnownFunctionAttributes(NewFD);
  8079. if (NewFD->hasAttr<OverloadableAttr>() &&
  8080. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8081. Diag(NewFD->getLocation(),
  8082. diag::err_attribute_overloadable_no_prototype)
  8083. << NewFD;
  8084. // Turn this into a variadic function with no parameters.
  8085. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8086. FunctionProtoType::ExtProtoInfo EPI(
  8087. Context.getDefaultCallingConvention(true, false));
  8088. EPI.Variadic = true;
  8089. EPI.ExtInfo = FT->getExtInfo();
  8090. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8091. NewFD->setType(R);
  8092. }
  8093. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8094. // member, set the visibility of this function.
  8095. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8096. AddPushedVisibilityAttribute(NewFD);
  8097. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8098. // marking the function.
  8099. AddCFAuditedAttribute(NewFD);
  8100. // If this is a function definition, check if we have to apply optnone due to
  8101. // a pragma.
  8102. if(D.isFunctionDefinition())
  8103. AddRangeBasedOptnone(NewFD);
  8104. // If this is the first declaration of an extern C variable, update
  8105. // the map of such variables.
  8106. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8107. isIncompleteDeclExternC(*this, NewFD))
  8108. RegisterLocallyScopedExternCDecl(NewFD, S);
  8109. // Set this FunctionDecl's range up to the right paren.
  8110. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8111. if (D.isRedeclaration() && !Previous.empty()) {
  8112. checkDLLAttributeRedeclaration(
  8113. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  8114. isMemberSpecialization || isFunctionTemplateSpecialization,
  8115. D.isFunctionDefinition());
  8116. }
  8117. if (getLangOpts().CUDA) {
  8118. IdentifierInfo *II = NewFD->getIdentifier();
  8119. if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
  8120. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8121. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8122. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  8123. Context.setcudaConfigureCallDecl(NewFD);
  8124. }
  8125. // Variadic functions, other than a *declaration* of printf, are not allowed
  8126. // in device-side CUDA code, unless someone passed
  8127. // -fcuda-allow-variadic-functions.
  8128. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8129. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8130. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8131. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8132. !D.isFunctionDefinition())) {
  8133. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8134. }
  8135. }
  8136. MarkUnusedFileScopedDecl(NewFD);
  8137. if (getLangOpts().CPlusPlus) {
  8138. if (FunctionTemplate) {
  8139. if (NewFD->isInvalidDecl())
  8140. FunctionTemplate->setInvalidDecl();
  8141. return FunctionTemplate;
  8142. }
  8143. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8144. CompleteMemberSpecialization(NewFD, Previous);
  8145. }
  8146. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  8147. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8148. if ((getLangOpts().OpenCLVersion >= 120)
  8149. && (SC == SC_Static)) {
  8150. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8151. D.setInvalidType();
  8152. }
  8153. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8154. if (!NewFD->getReturnType()->isVoidType()) {
  8155. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8156. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8157. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8158. : FixItHint());
  8159. D.setInvalidType();
  8160. }
  8161. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8162. for (auto Param : NewFD->parameters())
  8163. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8164. }
  8165. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8166. QualType PT = Param->getType();
  8167. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8168. // types.
  8169. if (getLangOpts().OpenCLVersion >= 200) {
  8170. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8171. QualType ElemTy = PipeTy->getElementType();
  8172. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8173. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8174. D.setInvalidType();
  8175. }
  8176. }
  8177. }
  8178. }
  8179. // Here we have an function template explicit specialization at class scope.
  8180. // The actually specialization will be postponed to template instatiation
  8181. // time via the ClassScopeFunctionSpecializationDecl node.
  8182. if (isDependentClassScopeExplicitSpecialization) {
  8183. ClassScopeFunctionSpecializationDecl *NewSpec =
  8184. ClassScopeFunctionSpecializationDecl::Create(
  8185. Context, CurContext, SourceLocation(),
  8186. cast<CXXMethodDecl>(NewFD),
  8187. HasExplicitTemplateArgs, TemplateArgs);
  8188. CurContext->addDecl(NewSpec);
  8189. AddToScope = false;
  8190. }
  8191. return NewFD;
  8192. }
  8193. /// \brief Checks if the new declaration declared in dependent context must be
  8194. /// put in the same redeclaration chain as the specified declaration.
  8195. ///
  8196. /// \param D Declaration that is checked.
  8197. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8198. /// same declaration name.
  8199. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8200. /// belongs to.
  8201. ///
  8202. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8203. // Any declarations should be put into redeclaration chains except for
  8204. // friend declaration in a dependent context that names a function in
  8205. // namespace scope.
  8206. //
  8207. // This allows to compile code like:
  8208. //
  8209. // void func();
  8210. // template<typename T> class C1 { friend void func() { } };
  8211. // template<typename T> class C2 { friend void func() { } };
  8212. //
  8213. // This code snippet is a valid code unless both templates are instantiated.
  8214. return !(D->getLexicalDeclContext()->isDependentContext() &&
  8215. D->getDeclContext()->isFileContext() &&
  8216. D->getFriendObjectKind() != Decl::FOK_None);
  8217. }
  8218. /// \brief Perform semantic checking of a new function declaration.
  8219. ///
  8220. /// Performs semantic analysis of the new function declaration
  8221. /// NewFD. This routine performs all semantic checking that does not
  8222. /// require the actual declarator involved in the declaration, and is
  8223. /// used both for the declaration of functions as they are parsed
  8224. /// (called via ActOnDeclarator) and for the declaration of functions
  8225. /// that have been instantiated via C++ template instantiation (called
  8226. /// via InstantiateDecl).
  8227. ///
  8228. /// \param IsMemberSpecialization whether this new function declaration is
  8229. /// a member specialization (that replaces any definition provided by the
  8230. /// previous declaration).
  8231. ///
  8232. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8233. ///
  8234. /// \returns true if the function declaration is a redeclaration.
  8235. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8236. LookupResult &Previous,
  8237. bool IsMemberSpecialization) {
  8238. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8239. "Variably modified return types are not handled here");
  8240. // Determine whether the type of this function should be merged with
  8241. // a previous visible declaration. This never happens for functions in C++,
  8242. // and always happens in C if the previous declaration was visible.
  8243. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8244. !Previous.isShadowed();
  8245. bool Redeclaration = false;
  8246. NamedDecl *OldDecl = nullptr;
  8247. bool MayNeedOverloadableChecks = false;
  8248. // Merge or overload the declaration with an existing declaration of
  8249. // the same name, if appropriate.
  8250. if (!Previous.empty()) {
  8251. // Determine whether NewFD is an overload of PrevDecl or
  8252. // a declaration that requires merging. If it's an overload,
  8253. // there's no more work to do here; we'll just add the new
  8254. // function to the scope.
  8255. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8256. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8257. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8258. Redeclaration = true;
  8259. OldDecl = Candidate;
  8260. }
  8261. } else {
  8262. MayNeedOverloadableChecks = true;
  8263. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8264. /*NewIsUsingDecl*/ false)) {
  8265. case Ovl_Match:
  8266. Redeclaration = true;
  8267. break;
  8268. case Ovl_NonFunction:
  8269. Redeclaration = true;
  8270. break;
  8271. case Ovl_Overload:
  8272. Redeclaration = false;
  8273. break;
  8274. }
  8275. }
  8276. }
  8277. // Check for a previous extern "C" declaration with this name.
  8278. if (!Redeclaration &&
  8279. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8280. if (!Previous.empty()) {
  8281. // This is an extern "C" declaration with the same name as a previous
  8282. // declaration, and thus redeclares that entity...
  8283. Redeclaration = true;
  8284. OldDecl = Previous.getFoundDecl();
  8285. MergeTypeWithPrevious = false;
  8286. // ... except in the presence of __attribute__((overloadable)).
  8287. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8288. NewFD->hasAttr<OverloadableAttr>()) {
  8289. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8290. MayNeedOverloadableChecks = true;
  8291. Redeclaration = false;
  8292. OldDecl = nullptr;
  8293. }
  8294. }
  8295. }
  8296. }
  8297. // C++11 [dcl.constexpr]p8:
  8298. // A constexpr specifier for a non-static member function that is not
  8299. // a constructor declares that member function to be const.
  8300. //
  8301. // This needs to be delayed until we know whether this is an out-of-line
  8302. // definition of a static member function.
  8303. //
  8304. // This rule is not present in C++1y, so we produce a backwards
  8305. // compatibility warning whenever it happens in C++11.
  8306. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8307. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8308. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8309. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  8310. CXXMethodDecl *OldMD = nullptr;
  8311. if (OldDecl)
  8312. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8313. if (!OldMD || !OldMD->isStatic()) {
  8314. const FunctionProtoType *FPT =
  8315. MD->getType()->castAs<FunctionProtoType>();
  8316. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8317. EPI.TypeQuals |= Qualifiers::Const;
  8318. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8319. FPT->getParamTypes(), EPI));
  8320. // Warn that we did this, if we're not performing template instantiation.
  8321. // In that case, we'll have warned already when the template was defined.
  8322. if (!inTemplateInstantiation()) {
  8323. SourceLocation AddConstLoc;
  8324. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8325. .IgnoreParens().getAs<FunctionTypeLoc>())
  8326. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8327. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8328. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8329. }
  8330. }
  8331. }
  8332. if (Redeclaration) {
  8333. // NewFD and OldDecl represent declarations that need to be
  8334. // merged.
  8335. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8336. NewFD->setInvalidDecl();
  8337. return Redeclaration;
  8338. }
  8339. Previous.clear();
  8340. Previous.addDecl(OldDecl);
  8341. if (FunctionTemplateDecl *OldTemplateDecl
  8342. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8343. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  8344. FunctionTemplateDecl *NewTemplateDecl
  8345. = NewFD->getDescribedFunctionTemplate();
  8346. assert(NewTemplateDecl && "Template/non-template mismatch");
  8347. if (CXXMethodDecl *Method
  8348. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  8349. Method->setAccess(OldTemplateDecl->getAccess());
  8350. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8351. }
  8352. // If this is an explicit specialization of a member that is a function
  8353. // template, mark it as a member specialization.
  8354. if (IsMemberSpecialization &&
  8355. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8356. NewTemplateDecl->setMemberSpecialization();
  8357. assert(OldTemplateDecl->isMemberSpecialization());
  8358. // Explicit specializations of a member template do not inherit deleted
  8359. // status from the parent member template that they are specializing.
  8360. if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
  8361. FunctionDecl *const OldTemplatedDecl =
  8362. OldTemplateDecl->getTemplatedDecl();
  8363. // FIXME: This assert will not hold in the presence of modules.
  8364. assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
  8365. // FIXME: We need an update record for this AST mutation.
  8366. OldTemplatedDecl->setDeletedAsWritten(false);
  8367. }
  8368. }
  8369. } else {
  8370. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8371. // This needs to happen first so that 'inline' propagates.
  8372. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  8373. if (isa<CXXMethodDecl>(NewFD))
  8374. NewFD->setAccess(OldDecl->getAccess());
  8375. }
  8376. }
  8377. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  8378. !NewFD->getAttr<OverloadableAttr>()) {
  8379. assert((Previous.empty() ||
  8380. llvm::any_of(Previous,
  8381. [](const NamedDecl *ND) {
  8382. return ND->hasAttr<OverloadableAttr>();
  8383. })) &&
  8384. "Non-redecls shouldn't happen without overloadable present");
  8385. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  8386. const auto *FD = dyn_cast<FunctionDecl>(ND);
  8387. return FD && !FD->hasAttr<OverloadableAttr>();
  8388. });
  8389. if (OtherUnmarkedIter != Previous.end()) {
  8390. Diag(NewFD->getLocation(),
  8391. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  8392. Diag((*OtherUnmarkedIter)->getLocation(),
  8393. diag::note_attribute_overloadable_prev_overload)
  8394. << false;
  8395. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  8396. }
  8397. }
  8398. // Semantic checking for this function declaration (in isolation).
  8399. if (getLangOpts().CPlusPlus) {
  8400. // C++-specific checks.
  8401. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  8402. CheckConstructor(Constructor);
  8403. } else if (CXXDestructorDecl *Destructor =
  8404. dyn_cast<CXXDestructorDecl>(NewFD)) {
  8405. CXXRecordDecl *Record = Destructor->getParent();
  8406. QualType ClassType = Context.getTypeDeclType(Record);
  8407. // FIXME: Shouldn't we be able to perform this check even when the class
  8408. // type is dependent? Both gcc and edg can handle that.
  8409. if (!ClassType->isDependentType()) {
  8410. DeclarationName Name
  8411. = Context.DeclarationNames.getCXXDestructorName(
  8412. Context.getCanonicalType(ClassType));
  8413. if (NewFD->getDeclName() != Name) {
  8414. Diag(NewFD->getLocation(), diag::err_destructor_name);
  8415. NewFD->setInvalidDecl();
  8416. return Redeclaration;
  8417. }
  8418. }
  8419. } else if (CXXConversionDecl *Conversion
  8420. = dyn_cast<CXXConversionDecl>(NewFD)) {
  8421. ActOnConversionDeclarator(Conversion);
  8422. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  8423. if (auto *TD = Guide->getDescribedFunctionTemplate())
  8424. CheckDeductionGuideTemplate(TD);
  8425. // A deduction guide is not on the list of entities that can be
  8426. // explicitly specialized.
  8427. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  8428. Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
  8429. << /*explicit specialization*/ 1;
  8430. }
  8431. // Find any virtual functions that this function overrides.
  8432. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  8433. if (!Method->isFunctionTemplateSpecialization() &&
  8434. !Method->getDescribedFunctionTemplate() &&
  8435. Method->isCanonicalDecl()) {
  8436. if (AddOverriddenMethods(Method->getParent(), Method)) {
  8437. // If the function was marked as "static", we have a problem.
  8438. if (NewFD->getStorageClass() == SC_Static) {
  8439. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  8440. }
  8441. }
  8442. }
  8443. if (Method->isStatic())
  8444. checkThisInStaticMemberFunctionType(Method);
  8445. }
  8446. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  8447. if (NewFD->isOverloadedOperator() &&
  8448. CheckOverloadedOperatorDeclaration(NewFD)) {
  8449. NewFD->setInvalidDecl();
  8450. return Redeclaration;
  8451. }
  8452. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  8453. if (NewFD->getLiteralIdentifier() &&
  8454. CheckLiteralOperatorDeclaration(NewFD)) {
  8455. NewFD->setInvalidDecl();
  8456. return Redeclaration;
  8457. }
  8458. // In C++, check default arguments now that we have merged decls. Unless
  8459. // the lexical context is the class, because in this case this is done
  8460. // during delayed parsing anyway.
  8461. if (!CurContext->isRecord())
  8462. CheckCXXDefaultArguments(NewFD);
  8463. // If this function declares a builtin function, check the type of this
  8464. // declaration against the expected type for the builtin.
  8465. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  8466. ASTContext::GetBuiltinTypeError Error;
  8467. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  8468. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  8469. // If the type of the builtin differs only in its exception
  8470. // specification, that's OK.
  8471. // FIXME: If the types do differ in this way, it would be better to
  8472. // retain the 'noexcept' form of the type.
  8473. if (!T.isNull() &&
  8474. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  8475. NewFD->getType()))
  8476. // The type of this function differs from the type of the builtin,
  8477. // so forget about the builtin entirely.
  8478. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  8479. }
  8480. // If this function is declared as being extern "C", then check to see if
  8481. // the function returns a UDT (class, struct, or union type) that is not C
  8482. // compatible, and if it does, warn the user.
  8483. // But, issue any diagnostic on the first declaration only.
  8484. if (Previous.empty() && NewFD->isExternC()) {
  8485. QualType R = NewFD->getReturnType();
  8486. if (R->isIncompleteType() && !R->isVoidType())
  8487. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  8488. << NewFD << R;
  8489. else if (!R.isPODType(Context) && !R->isVoidType() &&
  8490. !R->isObjCObjectPointerType())
  8491. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  8492. }
  8493. // C++1z [dcl.fct]p6:
  8494. // [...] whether the function has a non-throwing exception-specification
  8495. // [is] part of the function type
  8496. //
  8497. // This results in an ABI break between C++14 and C++17 for functions whose
  8498. // declared type includes an exception-specification in a parameter or
  8499. // return type. (Exception specifications on the function itself are OK in
  8500. // most cases, and exception specifications are not permitted in most other
  8501. // contexts where they could make it into a mangling.)
  8502. if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
  8503. auto HasNoexcept = [&](QualType T) -> bool {
  8504. // Strip off declarator chunks that could be between us and a function
  8505. // type. We don't need to look far, exception specifications are very
  8506. // restricted prior to C++17.
  8507. if (auto *RT = T->getAs<ReferenceType>())
  8508. T = RT->getPointeeType();
  8509. else if (T->isAnyPointerType())
  8510. T = T->getPointeeType();
  8511. else if (auto *MPT = T->getAs<MemberPointerType>())
  8512. T = MPT->getPointeeType();
  8513. if (auto *FPT = T->getAs<FunctionProtoType>())
  8514. if (FPT->isNothrow(Context))
  8515. return true;
  8516. return false;
  8517. };
  8518. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  8519. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  8520. for (QualType T : FPT->param_types())
  8521. AnyNoexcept |= HasNoexcept(T);
  8522. if (AnyNoexcept)
  8523. Diag(NewFD->getLocation(),
  8524. diag::warn_cxx17_compat_exception_spec_in_signature)
  8525. << NewFD;
  8526. }
  8527. if (!Redeclaration && LangOpts.CUDA)
  8528. checkCUDATargetOverload(NewFD, Previous);
  8529. }
  8530. return Redeclaration;
  8531. }
  8532. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  8533. // C++11 [basic.start.main]p3:
  8534. // A program that [...] declares main to be inline, static or
  8535. // constexpr is ill-formed.
  8536. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  8537. // appear in a declaration of main.
  8538. // static main is not an error under C99, but we should warn about it.
  8539. // We accept _Noreturn main as an extension.
  8540. if (FD->getStorageClass() == SC_Static)
  8541. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  8542. ? diag::err_static_main : diag::warn_static_main)
  8543. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  8544. if (FD->isInlineSpecified())
  8545. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  8546. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  8547. if (DS.isNoreturnSpecified()) {
  8548. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  8549. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  8550. Diag(NoreturnLoc, diag::ext_noreturn_main);
  8551. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  8552. << FixItHint::CreateRemoval(NoreturnRange);
  8553. }
  8554. if (FD->isConstexpr()) {
  8555. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  8556. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  8557. FD->setConstexpr(false);
  8558. }
  8559. if (getLangOpts().OpenCL) {
  8560. Diag(FD->getLocation(), diag::err_opencl_no_main)
  8561. << FD->hasAttr<OpenCLKernelAttr>();
  8562. FD->setInvalidDecl();
  8563. return;
  8564. }
  8565. QualType T = FD->getType();
  8566. assert(T->isFunctionType() && "function decl is not of function type");
  8567. const FunctionType* FT = T->castAs<FunctionType>();
  8568. // Set default calling convention for main()
  8569. if (FT->getCallConv() != CC_C) {
  8570. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  8571. FD->setType(QualType(FT, 0));
  8572. T = Context.getCanonicalType(FD->getType());
  8573. }
  8574. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  8575. // In C with GNU extensions we allow main() to have non-integer return
  8576. // type, but we should warn about the extension, and we disable the
  8577. // implicit-return-zero rule.
  8578. // GCC in C mode accepts qualified 'int'.
  8579. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  8580. FD->setHasImplicitReturnZero(true);
  8581. else {
  8582. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  8583. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8584. if (RTRange.isValid())
  8585. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  8586. << FixItHint::CreateReplacement(RTRange, "int");
  8587. }
  8588. } else {
  8589. // In C and C++, main magically returns 0 if you fall off the end;
  8590. // set the flag which tells us that.
  8591. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  8592. // All the standards say that main() should return 'int'.
  8593. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  8594. FD->setHasImplicitReturnZero(true);
  8595. else {
  8596. // Otherwise, this is just a flat-out error.
  8597. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8598. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  8599. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  8600. : FixItHint());
  8601. FD->setInvalidDecl(true);
  8602. }
  8603. }
  8604. // Treat protoless main() as nullary.
  8605. if (isa<FunctionNoProtoType>(FT)) return;
  8606. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  8607. unsigned nparams = FTP->getNumParams();
  8608. assert(FD->getNumParams() == nparams);
  8609. bool HasExtraParameters = (nparams > 3);
  8610. if (FTP->isVariadic()) {
  8611. Diag(FD->getLocation(), diag::ext_variadic_main);
  8612. // FIXME: if we had information about the location of the ellipsis, we
  8613. // could add a FixIt hint to remove it as a parameter.
  8614. }
  8615. // Darwin passes an undocumented fourth argument of type char**. If
  8616. // other platforms start sprouting these, the logic below will start
  8617. // getting shifty.
  8618. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  8619. HasExtraParameters = false;
  8620. if (HasExtraParameters) {
  8621. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  8622. FD->setInvalidDecl(true);
  8623. nparams = 3;
  8624. }
  8625. // FIXME: a lot of the following diagnostics would be improved
  8626. // if we had some location information about types.
  8627. QualType CharPP =
  8628. Context.getPointerType(Context.getPointerType(Context.CharTy));
  8629. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  8630. for (unsigned i = 0; i < nparams; ++i) {
  8631. QualType AT = FTP->getParamType(i);
  8632. bool mismatch = true;
  8633. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  8634. mismatch = false;
  8635. else if (Expected[i] == CharPP) {
  8636. // As an extension, the following forms are okay:
  8637. // char const **
  8638. // char const * const *
  8639. // char * const *
  8640. QualifierCollector qs;
  8641. const PointerType* PT;
  8642. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  8643. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  8644. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  8645. Context.CharTy)) {
  8646. qs.removeConst();
  8647. mismatch = !qs.empty();
  8648. }
  8649. }
  8650. if (mismatch) {
  8651. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  8652. // TODO: suggest replacing given type with expected type
  8653. FD->setInvalidDecl(true);
  8654. }
  8655. }
  8656. if (nparams == 1 && !FD->isInvalidDecl()) {
  8657. Diag(FD->getLocation(), diag::warn_main_one_arg);
  8658. }
  8659. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8660. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8661. FD->setInvalidDecl();
  8662. }
  8663. }
  8664. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  8665. QualType T = FD->getType();
  8666. assert(T->isFunctionType() && "function decl is not of function type");
  8667. const FunctionType *FT = T->castAs<FunctionType>();
  8668. // Set an implicit return of 'zero' if the function can return some integral,
  8669. // enumeration, pointer or nullptr type.
  8670. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  8671. FT->getReturnType()->isAnyPointerType() ||
  8672. FT->getReturnType()->isNullPtrType())
  8673. // DllMain is exempt because a return value of zero means it failed.
  8674. if (FD->getName() != "DllMain")
  8675. FD->setHasImplicitReturnZero(true);
  8676. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8677. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8678. FD->setInvalidDecl();
  8679. }
  8680. }
  8681. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  8682. // FIXME: Need strict checking. In C89, we need to check for
  8683. // any assignment, increment, decrement, function-calls, or
  8684. // commas outside of a sizeof. In C99, it's the same list,
  8685. // except that the aforementioned are allowed in unevaluated
  8686. // expressions. Everything else falls under the
  8687. // "may accept other forms of constant expressions" exception.
  8688. // (We never end up here for C++, so the constant expression
  8689. // rules there don't matter.)
  8690. const Expr *Culprit;
  8691. if (Init->isConstantInitializer(Context, false, &Culprit))
  8692. return false;
  8693. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  8694. << Culprit->getSourceRange();
  8695. return true;
  8696. }
  8697. namespace {
  8698. // Visits an initialization expression to see if OrigDecl is evaluated in
  8699. // its own initialization and throws a warning if it does.
  8700. class SelfReferenceChecker
  8701. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  8702. Sema &S;
  8703. Decl *OrigDecl;
  8704. bool isRecordType;
  8705. bool isPODType;
  8706. bool isReferenceType;
  8707. bool isInitList;
  8708. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  8709. public:
  8710. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  8711. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  8712. S(S), OrigDecl(OrigDecl) {
  8713. isPODType = false;
  8714. isRecordType = false;
  8715. isReferenceType = false;
  8716. isInitList = false;
  8717. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  8718. isPODType = VD->getType().isPODType(S.Context);
  8719. isRecordType = VD->getType()->isRecordType();
  8720. isReferenceType = VD->getType()->isReferenceType();
  8721. }
  8722. }
  8723. // For most expressions, just call the visitor. For initializer lists,
  8724. // track the index of the field being initialized since fields are
  8725. // initialized in order allowing use of previously initialized fields.
  8726. void CheckExpr(Expr *E) {
  8727. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  8728. if (!InitList) {
  8729. Visit(E);
  8730. return;
  8731. }
  8732. // Track and increment the index here.
  8733. isInitList = true;
  8734. InitFieldIndex.push_back(0);
  8735. for (auto Child : InitList->children()) {
  8736. CheckExpr(cast<Expr>(Child));
  8737. ++InitFieldIndex.back();
  8738. }
  8739. InitFieldIndex.pop_back();
  8740. }
  8741. // Returns true if MemberExpr is checked and no further checking is needed.
  8742. // Returns false if additional checking is required.
  8743. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  8744. llvm::SmallVector<FieldDecl*, 4> Fields;
  8745. Expr *Base = E;
  8746. bool ReferenceField = false;
  8747. // Get the field memebers used.
  8748. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8749. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  8750. if (!FD)
  8751. return false;
  8752. Fields.push_back(FD);
  8753. if (FD->getType()->isReferenceType())
  8754. ReferenceField = true;
  8755. Base = ME->getBase()->IgnoreParenImpCasts();
  8756. }
  8757. // Keep checking only if the base Decl is the same.
  8758. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  8759. if (!DRE || DRE->getDecl() != OrigDecl)
  8760. return false;
  8761. // A reference field can be bound to an unininitialized field.
  8762. if (CheckReference && !ReferenceField)
  8763. return true;
  8764. // Convert FieldDecls to their index number.
  8765. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  8766. for (const FieldDecl *I : llvm::reverse(Fields))
  8767. UsedFieldIndex.push_back(I->getFieldIndex());
  8768. // See if a warning is needed by checking the first difference in index
  8769. // numbers. If field being used has index less than the field being
  8770. // initialized, then the use is safe.
  8771. for (auto UsedIter = UsedFieldIndex.begin(),
  8772. UsedEnd = UsedFieldIndex.end(),
  8773. OrigIter = InitFieldIndex.begin(),
  8774. OrigEnd = InitFieldIndex.end();
  8775. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  8776. if (*UsedIter < *OrigIter)
  8777. return true;
  8778. if (*UsedIter > *OrigIter)
  8779. break;
  8780. }
  8781. // TODO: Add a different warning which will print the field names.
  8782. HandleDeclRefExpr(DRE);
  8783. return true;
  8784. }
  8785. // For most expressions, the cast is directly above the DeclRefExpr.
  8786. // For conditional operators, the cast can be outside the conditional
  8787. // operator if both expressions are DeclRefExpr's.
  8788. void HandleValue(Expr *E) {
  8789. E = E->IgnoreParens();
  8790. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  8791. HandleDeclRefExpr(DRE);
  8792. return;
  8793. }
  8794. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  8795. Visit(CO->getCond());
  8796. HandleValue(CO->getTrueExpr());
  8797. HandleValue(CO->getFalseExpr());
  8798. return;
  8799. }
  8800. if (BinaryConditionalOperator *BCO =
  8801. dyn_cast<BinaryConditionalOperator>(E)) {
  8802. Visit(BCO->getCond());
  8803. HandleValue(BCO->getFalseExpr());
  8804. return;
  8805. }
  8806. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  8807. HandleValue(OVE->getSourceExpr());
  8808. return;
  8809. }
  8810. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8811. if (BO->getOpcode() == BO_Comma) {
  8812. Visit(BO->getLHS());
  8813. HandleValue(BO->getRHS());
  8814. return;
  8815. }
  8816. }
  8817. if (isa<MemberExpr>(E)) {
  8818. if (isInitList) {
  8819. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  8820. false /*CheckReference*/))
  8821. return;
  8822. }
  8823. Expr *Base = E->IgnoreParenImpCasts();
  8824. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8825. // Check for static member variables and don't warn on them.
  8826. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8827. return;
  8828. Base = ME->getBase()->IgnoreParenImpCasts();
  8829. }
  8830. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  8831. HandleDeclRefExpr(DRE);
  8832. return;
  8833. }
  8834. Visit(E);
  8835. }
  8836. // Reference types not handled in HandleValue are handled here since all
  8837. // uses of references are bad, not just r-value uses.
  8838. void VisitDeclRefExpr(DeclRefExpr *E) {
  8839. if (isReferenceType)
  8840. HandleDeclRefExpr(E);
  8841. }
  8842. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  8843. if (E->getCastKind() == CK_LValueToRValue) {
  8844. HandleValue(E->getSubExpr());
  8845. return;
  8846. }
  8847. Inherited::VisitImplicitCastExpr(E);
  8848. }
  8849. void VisitMemberExpr(MemberExpr *E) {
  8850. if (isInitList) {
  8851. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  8852. return;
  8853. }
  8854. // Don't warn on arrays since they can be treated as pointers.
  8855. if (E->getType()->canDecayToPointerType()) return;
  8856. // Warn when a non-static method call is followed by non-static member
  8857. // field accesses, which is followed by a DeclRefExpr.
  8858. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  8859. bool Warn = (MD && !MD->isStatic());
  8860. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  8861. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8862. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8863. Warn = false;
  8864. Base = ME->getBase()->IgnoreParenImpCasts();
  8865. }
  8866. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  8867. if (Warn)
  8868. HandleDeclRefExpr(DRE);
  8869. return;
  8870. }
  8871. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  8872. // Visit that expression.
  8873. Visit(Base);
  8874. }
  8875. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  8876. Expr *Callee = E->getCallee();
  8877. if (isa<UnresolvedLookupExpr>(Callee))
  8878. return Inherited::VisitCXXOperatorCallExpr(E);
  8879. Visit(Callee);
  8880. for (auto Arg: E->arguments())
  8881. HandleValue(Arg->IgnoreParenImpCasts());
  8882. }
  8883. void VisitUnaryOperator(UnaryOperator *E) {
  8884. // For POD record types, addresses of its own members are well-defined.
  8885. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  8886. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  8887. if (!isPODType)
  8888. HandleValue(E->getSubExpr());
  8889. return;
  8890. }
  8891. if (E->isIncrementDecrementOp()) {
  8892. HandleValue(E->getSubExpr());
  8893. return;
  8894. }
  8895. Inherited::VisitUnaryOperator(E);
  8896. }
  8897. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  8898. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  8899. if (E->getConstructor()->isCopyConstructor()) {
  8900. Expr *ArgExpr = E->getArg(0);
  8901. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  8902. if (ILE->getNumInits() == 1)
  8903. ArgExpr = ILE->getInit(0);
  8904. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  8905. if (ICE->getCastKind() == CK_NoOp)
  8906. ArgExpr = ICE->getSubExpr();
  8907. HandleValue(ArgExpr);
  8908. return;
  8909. }
  8910. Inherited::VisitCXXConstructExpr(E);
  8911. }
  8912. void VisitCallExpr(CallExpr *E) {
  8913. // Treat std::move as a use.
  8914. if (E->isCallToStdMove()) {
  8915. HandleValue(E->getArg(0));
  8916. return;
  8917. }
  8918. Inherited::VisitCallExpr(E);
  8919. }
  8920. void VisitBinaryOperator(BinaryOperator *E) {
  8921. if (E->isCompoundAssignmentOp()) {
  8922. HandleValue(E->getLHS());
  8923. Visit(E->getRHS());
  8924. return;
  8925. }
  8926. Inherited::VisitBinaryOperator(E);
  8927. }
  8928. // A custom visitor for BinaryConditionalOperator is needed because the
  8929. // regular visitor would check the condition and true expression separately
  8930. // but both point to the same place giving duplicate diagnostics.
  8931. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  8932. Visit(E->getCond());
  8933. Visit(E->getFalseExpr());
  8934. }
  8935. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  8936. Decl* ReferenceDecl = DRE->getDecl();
  8937. if (OrigDecl != ReferenceDecl) return;
  8938. unsigned diag;
  8939. if (isReferenceType) {
  8940. diag = diag::warn_uninit_self_reference_in_reference_init;
  8941. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  8942. diag = diag::warn_static_self_reference_in_init;
  8943. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  8944. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  8945. DRE->getDecl()->getType()->isRecordType()) {
  8946. diag = diag::warn_uninit_self_reference_in_init;
  8947. } else {
  8948. // Local variables will be handled by the CFG analysis.
  8949. return;
  8950. }
  8951. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  8952. S.PDiag(diag)
  8953. << DRE->getNameInfo().getName()
  8954. << OrigDecl->getLocation()
  8955. << DRE->getSourceRange());
  8956. }
  8957. };
  8958. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  8959. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  8960. bool DirectInit) {
  8961. // Parameters arguments are occassionially constructed with itself,
  8962. // for instance, in recursive functions. Skip them.
  8963. if (isa<ParmVarDecl>(OrigDecl))
  8964. return;
  8965. E = E->IgnoreParens();
  8966. // Skip checking T a = a where T is not a record or reference type.
  8967. // Doing so is a way to silence uninitialized warnings.
  8968. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  8969. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  8970. if (ICE->getCastKind() == CK_LValueToRValue)
  8971. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  8972. if (DRE->getDecl() == OrigDecl)
  8973. return;
  8974. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  8975. }
  8976. } // end anonymous namespace
  8977. namespace {
  8978. // Simple wrapper to add the name of a variable or (if no variable is
  8979. // available) a DeclarationName into a diagnostic.
  8980. struct VarDeclOrName {
  8981. VarDecl *VDecl;
  8982. DeclarationName Name;
  8983. friend const Sema::SemaDiagnosticBuilder &
  8984. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  8985. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  8986. }
  8987. };
  8988. } // end anonymous namespace
  8989. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  8990. DeclarationName Name, QualType Type,
  8991. TypeSourceInfo *TSI,
  8992. SourceRange Range, bool DirectInit,
  8993. Expr *Init) {
  8994. bool IsInitCapture = !VDecl;
  8995. assert((!VDecl || !VDecl->isInitCapture()) &&
  8996. "init captures are expected to be deduced prior to initialization");
  8997. VarDeclOrName VN{VDecl, Name};
  8998. DeducedType *Deduced = Type->getContainedDeducedType();
  8999. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9000. // C++11 [dcl.spec.auto]p3
  9001. if (!Init) {
  9002. assert(VDecl && "no init for init capture deduction?");
  9003. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9004. << VDecl->getDeclName() << Type;
  9005. return QualType();
  9006. }
  9007. ArrayRef<Expr*> DeduceInits = Init;
  9008. if (DirectInit) {
  9009. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9010. DeduceInits = PL->exprs();
  9011. }
  9012. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9013. assert(VDecl && "non-auto type for init capture deduction?");
  9014. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9015. InitializationKind Kind = InitializationKind::CreateForInit(
  9016. VDecl->getLocation(), DirectInit, Init);
  9017. // FIXME: Initialization should not be taking a mutable list of inits.
  9018. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9019. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9020. InitsCopy);
  9021. }
  9022. if (DirectInit) {
  9023. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9024. DeduceInits = IL->inits();
  9025. }
  9026. // Deduction only works if we have exactly one source expression.
  9027. if (DeduceInits.empty()) {
  9028. // It isn't possible to write this directly, but it is possible to
  9029. // end up in this situation with "auto x(some_pack...);"
  9030. Diag(Init->getLocStart(), IsInitCapture
  9031. ? diag::err_init_capture_no_expression
  9032. : diag::err_auto_var_init_no_expression)
  9033. << VN << Type << Range;
  9034. return QualType();
  9035. }
  9036. if (DeduceInits.size() > 1) {
  9037. Diag(DeduceInits[1]->getLocStart(),
  9038. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9039. : diag::err_auto_var_init_multiple_expressions)
  9040. << VN << Type << Range;
  9041. return QualType();
  9042. }
  9043. Expr *DeduceInit = DeduceInits[0];
  9044. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9045. Diag(Init->getLocStart(), IsInitCapture
  9046. ? diag::err_init_capture_paren_braces
  9047. : diag::err_auto_var_init_paren_braces)
  9048. << isa<InitListExpr>(Init) << VN << Type << Range;
  9049. return QualType();
  9050. }
  9051. // Expressions default to 'id' when we're in a debugger.
  9052. bool DefaultedAnyToId = false;
  9053. if (getLangOpts().DebuggerCastResultToId &&
  9054. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9055. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9056. if (Result.isInvalid()) {
  9057. return QualType();
  9058. }
  9059. Init = Result.get();
  9060. DefaultedAnyToId = true;
  9061. }
  9062. // C++ [dcl.decomp]p1:
  9063. // If the assignment-expression [...] has array type A and no ref-qualifier
  9064. // is present, e has type cv A
  9065. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9066. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9067. DeduceInit->getType()->isConstantArrayType())
  9068. return Context.getQualifiedType(DeduceInit->getType(),
  9069. Type.getQualifiers());
  9070. QualType DeducedType;
  9071. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9072. if (!IsInitCapture)
  9073. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9074. else if (isa<InitListExpr>(Init))
  9075. Diag(Range.getBegin(),
  9076. diag::err_init_capture_deduction_failure_from_init_list)
  9077. << VN
  9078. << (DeduceInit->getType().isNull() ? TSI->getType()
  9079. : DeduceInit->getType())
  9080. << DeduceInit->getSourceRange();
  9081. else
  9082. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9083. << VN << TSI->getType()
  9084. << (DeduceInit->getType().isNull() ? TSI->getType()
  9085. : DeduceInit->getType())
  9086. << DeduceInit->getSourceRange();
  9087. }
  9088. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9089. // 'id' instead of a specific object type prevents most of our usual
  9090. // checks.
  9091. // We only want to warn outside of template instantiations, though:
  9092. // inside a template, the 'id' could have come from a parameter.
  9093. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9094. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9095. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9096. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9097. }
  9098. return DeducedType;
  9099. }
  9100. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9101. Expr *Init) {
  9102. QualType DeducedType = deduceVarTypeFromInitializer(
  9103. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9104. VDecl->getSourceRange(), DirectInit, Init);
  9105. if (DeducedType.isNull()) {
  9106. VDecl->setInvalidDecl();
  9107. return true;
  9108. }
  9109. VDecl->setType(DeducedType);
  9110. assert(VDecl->isLinkageValid());
  9111. // In ARC, infer lifetime.
  9112. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9113. VDecl->setInvalidDecl();
  9114. // If this is a redeclaration, check that the type we just deduced matches
  9115. // the previously declared type.
  9116. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9117. // We never need to merge the type, because we cannot form an incomplete
  9118. // array of auto, nor deduce such a type.
  9119. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9120. }
  9121. // Check the deduced type is valid for a variable declaration.
  9122. CheckVariableDeclarationType(VDecl);
  9123. return VDecl->isInvalidDecl();
  9124. }
  9125. /// AddInitializerToDecl - Adds the initializer Init to the
  9126. /// declaration dcl. If DirectInit is true, this is C++ direct
  9127. /// initialization rather than copy initialization.
  9128. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9129. // If there is no declaration, there was an error parsing it. Just ignore
  9130. // the initializer.
  9131. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9132. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9133. return;
  9134. }
  9135. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9136. // Pure-specifiers are handled in ActOnPureSpecifier.
  9137. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9138. << Method->getDeclName() << Init->getSourceRange();
  9139. Method->setInvalidDecl();
  9140. return;
  9141. }
  9142. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9143. if (!VDecl) {
  9144. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9145. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9146. RealDecl->setInvalidDecl();
  9147. return;
  9148. }
  9149. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9150. if (VDecl->getType()->isUndeducedType()) {
  9151. // Attempt typo correction early so that the type of the init expression can
  9152. // be deduced based on the chosen correction if the original init contains a
  9153. // TypoExpr.
  9154. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9155. if (!Res.isUsable()) {
  9156. RealDecl->setInvalidDecl();
  9157. return;
  9158. }
  9159. Init = Res.get();
  9160. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9161. return;
  9162. }
  9163. // dllimport cannot be used on variable definitions.
  9164. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9165. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9166. VDecl->setInvalidDecl();
  9167. return;
  9168. }
  9169. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9170. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9171. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9172. VDecl->setInvalidDecl();
  9173. return;
  9174. }
  9175. if (!VDecl->getType()->isDependentType()) {
  9176. // A definition must end up with a complete type, which means it must be
  9177. // complete with the restriction that an array type might be completed by
  9178. // the initializer; note that later code assumes this restriction.
  9179. QualType BaseDeclType = VDecl->getType();
  9180. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9181. BaseDeclType = Array->getElementType();
  9182. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9183. diag::err_typecheck_decl_incomplete_type)) {
  9184. RealDecl->setInvalidDecl();
  9185. return;
  9186. }
  9187. // The variable can not have an abstract class type.
  9188. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9189. diag::err_abstract_type_in_decl,
  9190. AbstractVariableType))
  9191. VDecl->setInvalidDecl();
  9192. }
  9193. // If adding the initializer will turn this declaration into a definition,
  9194. // and we already have a definition for this variable, diagnose or otherwise
  9195. // handle the situation.
  9196. VarDecl *Def;
  9197. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9198. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9199. !VDecl->isThisDeclarationADemotedDefinition() &&
  9200. checkVarDeclRedefinition(Def, VDecl))
  9201. return;
  9202. if (getLangOpts().CPlusPlus) {
  9203. // C++ [class.static.data]p4
  9204. // If a static data member is of const integral or const
  9205. // enumeration type, its declaration in the class definition can
  9206. // specify a constant-initializer which shall be an integral
  9207. // constant expression (5.19). In that case, the member can appear
  9208. // in integral constant expressions. The member shall still be
  9209. // defined in a namespace scope if it is used in the program and the
  9210. // namespace scope definition shall not contain an initializer.
  9211. //
  9212. // We already performed a redefinition check above, but for static
  9213. // data members we also need to check whether there was an in-class
  9214. // declaration with an initializer.
  9215. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9216. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9217. << VDecl->getDeclName();
  9218. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9219. diag::note_previous_initializer)
  9220. << 0;
  9221. return;
  9222. }
  9223. if (VDecl->hasLocalStorage())
  9224. getCurFunction()->setHasBranchProtectedScope();
  9225. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9226. VDecl->setInvalidDecl();
  9227. return;
  9228. }
  9229. }
  9230. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  9231. // a kernel function cannot be initialized."
  9232. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  9233. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  9234. VDecl->setInvalidDecl();
  9235. return;
  9236. }
  9237. // Get the decls type and save a reference for later, since
  9238. // CheckInitializerTypes may change it.
  9239. QualType DclT = VDecl->getType(), SavT = DclT;
  9240. // Expressions default to 'id' when we're in a debugger
  9241. // and we are assigning it to a variable of Objective-C pointer type.
  9242. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  9243. Init->getType() == Context.UnknownAnyTy) {
  9244. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9245. if (Result.isInvalid()) {
  9246. VDecl->setInvalidDecl();
  9247. return;
  9248. }
  9249. Init = Result.get();
  9250. }
  9251. // Perform the initialization.
  9252. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  9253. if (!VDecl->isInvalidDecl()) {
  9254. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9255. InitializationKind Kind = InitializationKind::CreateForInit(
  9256. VDecl->getLocation(), DirectInit, Init);
  9257. MultiExprArg Args = Init;
  9258. if (CXXDirectInit)
  9259. Args = MultiExprArg(CXXDirectInit->getExprs(),
  9260. CXXDirectInit->getNumExprs());
  9261. // Try to correct any TypoExprs in the initialization arguments.
  9262. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  9263. ExprResult Res = CorrectDelayedTyposInExpr(
  9264. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  9265. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  9266. return Init.Failed() ? ExprError() : E;
  9267. });
  9268. if (Res.isInvalid()) {
  9269. VDecl->setInvalidDecl();
  9270. } else if (Res.get() != Args[Idx]) {
  9271. Args[Idx] = Res.get();
  9272. }
  9273. }
  9274. if (VDecl->isInvalidDecl())
  9275. return;
  9276. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  9277. /*TopLevelOfInitList=*/false,
  9278. /*TreatUnavailableAsInvalid=*/false);
  9279. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  9280. if (Result.isInvalid()) {
  9281. VDecl->setInvalidDecl();
  9282. return;
  9283. }
  9284. Init = Result.getAs<Expr>();
  9285. }
  9286. // Check for self-references within variable initializers.
  9287. // Variables declared within a function/method body (except for references)
  9288. // are handled by a dataflow analysis.
  9289. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  9290. VDecl->getType()->isReferenceType()) {
  9291. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  9292. }
  9293. // If the type changed, it means we had an incomplete type that was
  9294. // completed by the initializer. For example:
  9295. // int ary[] = { 1, 3, 5 };
  9296. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  9297. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  9298. VDecl->setType(DclT);
  9299. if (!VDecl->isInvalidDecl()) {
  9300. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  9301. if (VDecl->hasAttr<BlocksAttr>())
  9302. checkRetainCycles(VDecl, Init);
  9303. // It is safe to assign a weak reference into a strong variable.
  9304. // Although this code can still have problems:
  9305. // id x = self.weakProp;
  9306. // id y = self.weakProp;
  9307. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9308. // paths through the function. This should be revisited if
  9309. // -Wrepeated-use-of-weak is made flow-sensitive.
  9310. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  9311. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  9312. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9313. Init->getLocStart()))
  9314. getCurFunction()->markSafeWeakUse(Init);
  9315. }
  9316. // The initialization is usually a full-expression.
  9317. //
  9318. // FIXME: If this is a braced initialization of an aggregate, it is not
  9319. // an expression, and each individual field initializer is a separate
  9320. // full-expression. For instance, in:
  9321. //
  9322. // struct Temp { ~Temp(); };
  9323. // struct S { S(Temp); };
  9324. // struct T { S a, b; } t = { Temp(), Temp() }
  9325. //
  9326. // we should destroy the first Temp before constructing the second.
  9327. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9328. false,
  9329. VDecl->isConstexpr());
  9330. if (Result.isInvalid()) {
  9331. VDecl->setInvalidDecl();
  9332. return;
  9333. }
  9334. Init = Result.get();
  9335. // Attach the initializer to the decl.
  9336. VDecl->setInit(Init);
  9337. if (VDecl->isLocalVarDecl()) {
  9338. // Don't check the initializer if the declaration is malformed.
  9339. if (VDecl->isInvalidDecl()) {
  9340. // do nothing
  9341. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  9342. // This is true even in OpenCL C++.
  9343. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  9344. CheckForConstantInitializer(Init, DclT);
  9345. // Otherwise, C++ does not restrict the initializer.
  9346. } else if (getLangOpts().CPlusPlus) {
  9347. // do nothing
  9348. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9349. // static storage duration shall be constant expressions or string literals.
  9350. } else if (VDecl->getStorageClass() == SC_Static) {
  9351. CheckForConstantInitializer(Init, DclT);
  9352. // C89 is stricter than C99 for aggregate initializers.
  9353. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9354. // for an object that has aggregate or union type shall be
  9355. // constant expressions.
  9356. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9357. isa<InitListExpr>(Init)) {
  9358. const Expr *Culprit;
  9359. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  9360. Diag(Culprit->getExprLoc(),
  9361. diag::ext_aggregate_init_not_constant)
  9362. << Culprit->getSourceRange();
  9363. }
  9364. }
  9365. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  9366. VDecl->getLexicalDeclContext()->isRecord()) {
  9367. // This is an in-class initialization for a static data member, e.g.,
  9368. //
  9369. // struct S {
  9370. // static const int value = 17;
  9371. // };
  9372. // C++ [class.mem]p4:
  9373. // A member-declarator can contain a constant-initializer only
  9374. // if it declares a static member (9.4) of const integral or
  9375. // const enumeration type, see 9.4.2.
  9376. //
  9377. // C++11 [class.static.data]p3:
  9378. // If a non-volatile non-inline const static data member is of integral
  9379. // or enumeration type, its declaration in the class definition can
  9380. // specify a brace-or-equal-initializer in which every initializer-clause
  9381. // that is an assignment-expression is a constant expression. A static
  9382. // data member of literal type can be declared in the class definition
  9383. // with the constexpr specifier; if so, its declaration shall specify a
  9384. // brace-or-equal-initializer in which every initializer-clause that is
  9385. // an assignment-expression is a constant expression.
  9386. // Do nothing on dependent types.
  9387. if (DclT->isDependentType()) {
  9388. // Allow any 'static constexpr' members, whether or not they are of literal
  9389. // type. We separately check that every constexpr variable is of literal
  9390. // type.
  9391. } else if (VDecl->isConstexpr()) {
  9392. // Require constness.
  9393. } else if (!DclT.isConstQualified()) {
  9394. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  9395. << Init->getSourceRange();
  9396. VDecl->setInvalidDecl();
  9397. // We allow integer constant expressions in all cases.
  9398. } else if (DclT->isIntegralOrEnumerationType()) {
  9399. // Check whether the expression is a constant expression.
  9400. SourceLocation Loc;
  9401. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  9402. // In C++11, a non-constexpr const static data member with an
  9403. // in-class initializer cannot be volatile.
  9404. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  9405. else if (Init->isValueDependent())
  9406. ; // Nothing to check.
  9407. else if (Init->isIntegerConstantExpr(Context, &Loc))
  9408. ; // Ok, it's an ICE!
  9409. else if (Init->isEvaluatable(Context)) {
  9410. // If we can constant fold the initializer through heroics, accept it,
  9411. // but report this as a use of an extension for -pedantic.
  9412. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  9413. << Init->getSourceRange();
  9414. } else {
  9415. // Otherwise, this is some crazy unknown case. Report the issue at the
  9416. // location provided by the isIntegerConstantExpr failed check.
  9417. Diag(Loc, diag::err_in_class_initializer_non_constant)
  9418. << Init->getSourceRange();
  9419. VDecl->setInvalidDecl();
  9420. }
  9421. // We allow foldable floating-point constants as an extension.
  9422. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  9423. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  9424. // it anyway and provide a fixit to add the 'constexpr'.
  9425. if (getLangOpts().CPlusPlus11) {
  9426. Diag(VDecl->getLocation(),
  9427. diag::ext_in_class_initializer_float_type_cxx11)
  9428. << DclT << Init->getSourceRange();
  9429. Diag(VDecl->getLocStart(),
  9430. diag::note_in_class_initializer_float_type_cxx11)
  9431. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9432. } else {
  9433. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  9434. << DclT << Init->getSourceRange();
  9435. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  9436. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  9437. << Init->getSourceRange();
  9438. VDecl->setInvalidDecl();
  9439. }
  9440. }
  9441. // Suggest adding 'constexpr' in C++11 for literal types.
  9442. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  9443. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  9444. << DclT << Init->getSourceRange()
  9445. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9446. VDecl->setConstexpr(true);
  9447. } else {
  9448. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  9449. << DclT << Init->getSourceRange();
  9450. VDecl->setInvalidDecl();
  9451. }
  9452. } else if (VDecl->isFileVarDecl()) {
  9453. // In C, extern is typically used to avoid tentative definitions when
  9454. // declaring variables in headers, but adding an intializer makes it a
  9455. // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
  9456. // In C++, extern is often used to give implictly static const variables
  9457. // external linkage, so don't warn in that case. If selectany is present,
  9458. // this might be header code intended for C and C++ inclusion, so apply the
  9459. // C++ rules.
  9460. if (VDecl->getStorageClass() == SC_Extern &&
  9461. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  9462. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  9463. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  9464. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  9465. Diag(VDecl->getLocation(), diag::warn_extern_init);
  9466. // C99 6.7.8p4. All file scoped initializers need to be constant.
  9467. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  9468. CheckForConstantInitializer(Init, DclT);
  9469. }
  9470. // We will represent direct-initialization similarly to copy-initialization:
  9471. // int x(1); -as-> int x = 1;
  9472. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  9473. //
  9474. // Clients that want to distinguish between the two forms, can check for
  9475. // direct initializer using VarDecl::getInitStyle().
  9476. // A major benefit is that clients that don't particularly care about which
  9477. // exactly form was it (like the CodeGen) can handle both cases without
  9478. // special case code.
  9479. // C++ 8.5p11:
  9480. // The form of initialization (using parentheses or '=') is generally
  9481. // insignificant, but does matter when the entity being initialized has a
  9482. // class type.
  9483. if (CXXDirectInit) {
  9484. assert(DirectInit && "Call-style initializer must be direct init.");
  9485. VDecl->setInitStyle(VarDecl::CallInit);
  9486. } else if (DirectInit) {
  9487. // This must be list-initialization. No other way is direct-initialization.
  9488. VDecl->setInitStyle(VarDecl::ListInit);
  9489. }
  9490. CheckCompleteVariableDeclaration(VDecl);
  9491. }
  9492. /// ActOnInitializerError - Given that there was an error parsing an
  9493. /// initializer for the given declaration, try to return to some form
  9494. /// of sanity.
  9495. void Sema::ActOnInitializerError(Decl *D) {
  9496. // Our main concern here is re-establishing invariants like "a
  9497. // variable's type is either dependent or complete".
  9498. if (!D || D->isInvalidDecl()) return;
  9499. VarDecl *VD = dyn_cast<VarDecl>(D);
  9500. if (!VD) return;
  9501. // Bindings are not usable if we can't make sense of the initializer.
  9502. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  9503. for (auto *BD : DD->bindings())
  9504. BD->setInvalidDecl();
  9505. // Auto types are meaningless if we can't make sense of the initializer.
  9506. if (ParsingInitForAutoVars.count(D)) {
  9507. D->setInvalidDecl();
  9508. return;
  9509. }
  9510. QualType Ty = VD->getType();
  9511. if (Ty->isDependentType()) return;
  9512. // Require a complete type.
  9513. if (RequireCompleteType(VD->getLocation(),
  9514. Context.getBaseElementType(Ty),
  9515. diag::err_typecheck_decl_incomplete_type)) {
  9516. VD->setInvalidDecl();
  9517. return;
  9518. }
  9519. // Require a non-abstract type.
  9520. if (RequireNonAbstractType(VD->getLocation(), Ty,
  9521. diag::err_abstract_type_in_decl,
  9522. AbstractVariableType)) {
  9523. VD->setInvalidDecl();
  9524. return;
  9525. }
  9526. // Don't bother complaining about constructors or destructors,
  9527. // though.
  9528. }
  9529. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  9530. // If there is no declaration, there was an error parsing it. Just ignore it.
  9531. if (!RealDecl)
  9532. return;
  9533. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  9534. QualType Type = Var->getType();
  9535. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  9536. if (isa<DecompositionDecl>(RealDecl)) {
  9537. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  9538. Var->setInvalidDecl();
  9539. return;
  9540. }
  9541. if (Type->isUndeducedType() &&
  9542. DeduceVariableDeclarationType(Var, false, nullptr))
  9543. return;
  9544. // C++11 [class.static.data]p3: A static data member can be declared with
  9545. // the constexpr specifier; if so, its declaration shall specify
  9546. // a brace-or-equal-initializer.
  9547. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  9548. // the definition of a variable [...] or the declaration of a static data
  9549. // member.
  9550. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  9551. !Var->isThisDeclarationADemotedDefinition()) {
  9552. if (Var->isStaticDataMember()) {
  9553. // C++1z removes the relevant rule; the in-class declaration is always
  9554. // a definition there.
  9555. if (!getLangOpts().CPlusPlus1z) {
  9556. Diag(Var->getLocation(),
  9557. diag::err_constexpr_static_mem_var_requires_init)
  9558. << Var->getDeclName();
  9559. Var->setInvalidDecl();
  9560. return;
  9561. }
  9562. } else {
  9563. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  9564. Var->setInvalidDecl();
  9565. return;
  9566. }
  9567. }
  9568. // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
  9569. // definition having the concept specifier is called a variable concept. A
  9570. // concept definition refers to [...] a variable concept and its initializer.
  9571. if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
  9572. if (VTD->isConcept()) {
  9573. Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
  9574. Var->setInvalidDecl();
  9575. return;
  9576. }
  9577. }
  9578. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  9579. // be initialized.
  9580. if (!Var->isInvalidDecl() &&
  9581. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  9582. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  9583. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  9584. Var->setInvalidDecl();
  9585. return;
  9586. }
  9587. switch (Var->isThisDeclarationADefinition()) {
  9588. case VarDecl::Definition:
  9589. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  9590. break;
  9591. // We have an out-of-line definition of a static data member
  9592. // that has an in-class initializer, so we type-check this like
  9593. // a declaration.
  9594. //
  9595. // Fall through
  9596. case VarDecl::DeclarationOnly:
  9597. // It's only a declaration.
  9598. // Block scope. C99 6.7p7: If an identifier for an object is
  9599. // declared with no linkage (C99 6.2.2p6), the type for the
  9600. // object shall be complete.
  9601. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  9602. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  9603. RequireCompleteType(Var->getLocation(), Type,
  9604. diag::err_typecheck_decl_incomplete_type))
  9605. Var->setInvalidDecl();
  9606. // Make sure that the type is not abstract.
  9607. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9608. RequireNonAbstractType(Var->getLocation(), Type,
  9609. diag::err_abstract_type_in_decl,
  9610. AbstractVariableType))
  9611. Var->setInvalidDecl();
  9612. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9613. Var->getStorageClass() == SC_PrivateExtern) {
  9614. Diag(Var->getLocation(), diag::warn_private_extern);
  9615. Diag(Var->getLocation(), diag::note_private_extern);
  9616. }
  9617. return;
  9618. case VarDecl::TentativeDefinition:
  9619. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  9620. // object that has file scope without an initializer, and without a
  9621. // storage-class specifier or with the storage-class specifier "static",
  9622. // constitutes a tentative definition. Note: A tentative definition with
  9623. // external linkage is valid (C99 6.2.2p5).
  9624. if (!Var->isInvalidDecl()) {
  9625. if (const IncompleteArrayType *ArrayT
  9626. = Context.getAsIncompleteArrayType(Type)) {
  9627. if (RequireCompleteType(Var->getLocation(),
  9628. ArrayT->getElementType(),
  9629. diag::err_illegal_decl_array_incomplete_type))
  9630. Var->setInvalidDecl();
  9631. } else if (Var->getStorageClass() == SC_Static) {
  9632. // C99 6.9.2p3: If the declaration of an identifier for an object is
  9633. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  9634. // declared type shall not be an incomplete type.
  9635. // NOTE: code such as the following
  9636. // static struct s;
  9637. // struct s { int a; };
  9638. // is accepted by gcc. Hence here we issue a warning instead of
  9639. // an error and we do not invalidate the static declaration.
  9640. // NOTE: to avoid multiple warnings, only check the first declaration.
  9641. if (Var->isFirstDecl())
  9642. RequireCompleteType(Var->getLocation(), Type,
  9643. diag::ext_typecheck_decl_incomplete_type);
  9644. }
  9645. }
  9646. // Record the tentative definition; we're done.
  9647. if (!Var->isInvalidDecl())
  9648. TentativeDefinitions.push_back(Var);
  9649. return;
  9650. }
  9651. // Provide a specific diagnostic for uninitialized variable
  9652. // definitions with incomplete array type.
  9653. if (Type->isIncompleteArrayType()) {
  9654. Diag(Var->getLocation(),
  9655. diag::err_typecheck_incomplete_array_needs_initializer);
  9656. Var->setInvalidDecl();
  9657. return;
  9658. }
  9659. // Provide a specific diagnostic for uninitialized variable
  9660. // definitions with reference type.
  9661. if (Type->isReferenceType()) {
  9662. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  9663. << Var->getDeclName()
  9664. << SourceRange(Var->getLocation(), Var->getLocation());
  9665. Var->setInvalidDecl();
  9666. return;
  9667. }
  9668. // Do not attempt to type-check the default initializer for a
  9669. // variable with dependent type.
  9670. if (Type->isDependentType())
  9671. return;
  9672. if (Var->isInvalidDecl())
  9673. return;
  9674. if (!Var->hasAttr<AliasAttr>()) {
  9675. if (RequireCompleteType(Var->getLocation(),
  9676. Context.getBaseElementType(Type),
  9677. diag::err_typecheck_decl_incomplete_type)) {
  9678. Var->setInvalidDecl();
  9679. return;
  9680. }
  9681. } else {
  9682. return;
  9683. }
  9684. // The variable can not have an abstract class type.
  9685. if (RequireNonAbstractType(Var->getLocation(), Type,
  9686. diag::err_abstract_type_in_decl,
  9687. AbstractVariableType)) {
  9688. Var->setInvalidDecl();
  9689. return;
  9690. }
  9691. // Check for jumps past the implicit initializer. C++0x
  9692. // clarifies that this applies to a "variable with automatic
  9693. // storage duration", not a "local variable".
  9694. // C++11 [stmt.dcl]p3
  9695. // A program that jumps from a point where a variable with automatic
  9696. // storage duration is not in scope to a point where it is in scope is
  9697. // ill-formed unless the variable has scalar type, class type with a
  9698. // trivial default constructor and a trivial destructor, a cv-qualified
  9699. // version of one of these types, or an array of one of the preceding
  9700. // types and is declared without an initializer.
  9701. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  9702. if (const RecordType *Record
  9703. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  9704. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  9705. // Mark the function for further checking even if the looser rules of
  9706. // C++11 do not require such checks, so that we can diagnose
  9707. // incompatibilities with C++98.
  9708. if (!CXXRecord->isPOD())
  9709. getCurFunction()->setHasBranchProtectedScope();
  9710. }
  9711. }
  9712. // C++03 [dcl.init]p9:
  9713. // If no initializer is specified for an object, and the
  9714. // object is of (possibly cv-qualified) non-POD class type (or
  9715. // array thereof), the object shall be default-initialized; if
  9716. // the object is of const-qualified type, the underlying class
  9717. // type shall have a user-declared default
  9718. // constructor. Otherwise, if no initializer is specified for
  9719. // a non- static object, the object and its subobjects, if
  9720. // any, have an indeterminate initial value); if the object
  9721. // or any of its subobjects are of const-qualified type, the
  9722. // program is ill-formed.
  9723. // C++0x [dcl.init]p11:
  9724. // If no initializer is specified for an object, the object is
  9725. // default-initialized; [...].
  9726. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  9727. InitializationKind Kind
  9728. = InitializationKind::CreateDefault(Var->getLocation());
  9729. InitializationSequence InitSeq(*this, Entity, Kind, None);
  9730. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  9731. if (Init.isInvalid())
  9732. Var->setInvalidDecl();
  9733. else if (Init.get()) {
  9734. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  9735. // This is important for template substitution.
  9736. Var->setInitStyle(VarDecl::CallInit);
  9737. }
  9738. CheckCompleteVariableDeclaration(Var);
  9739. }
  9740. }
  9741. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  9742. // If there is no declaration, there was an error parsing it. Ignore it.
  9743. if (!D)
  9744. return;
  9745. VarDecl *VD = dyn_cast<VarDecl>(D);
  9746. if (!VD) {
  9747. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  9748. D->setInvalidDecl();
  9749. return;
  9750. }
  9751. VD->setCXXForRangeDecl(true);
  9752. // for-range-declaration cannot be given a storage class specifier.
  9753. int Error = -1;
  9754. switch (VD->getStorageClass()) {
  9755. case SC_None:
  9756. break;
  9757. case SC_Extern:
  9758. Error = 0;
  9759. break;
  9760. case SC_Static:
  9761. Error = 1;
  9762. break;
  9763. case SC_PrivateExtern:
  9764. Error = 2;
  9765. break;
  9766. case SC_Auto:
  9767. Error = 3;
  9768. break;
  9769. case SC_Register:
  9770. Error = 4;
  9771. break;
  9772. }
  9773. if (Error != -1) {
  9774. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  9775. << VD->getDeclName() << Error;
  9776. D->setInvalidDecl();
  9777. }
  9778. }
  9779. StmtResult
  9780. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  9781. IdentifierInfo *Ident,
  9782. ParsedAttributes &Attrs,
  9783. SourceLocation AttrEnd) {
  9784. // C++1y [stmt.iter]p1:
  9785. // A range-based for statement of the form
  9786. // for ( for-range-identifier : for-range-initializer ) statement
  9787. // is equivalent to
  9788. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  9789. DeclSpec DS(Attrs.getPool().getFactory());
  9790. const char *PrevSpec;
  9791. unsigned DiagID;
  9792. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  9793. getPrintingPolicy());
  9794. Declarator D(DS, Declarator::ForContext);
  9795. D.SetIdentifier(Ident, IdentLoc);
  9796. D.takeAttributes(Attrs, AttrEnd);
  9797. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  9798. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  9799. EmptyAttrs, IdentLoc);
  9800. Decl *Var = ActOnDeclarator(S, D);
  9801. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  9802. FinalizeDeclaration(Var);
  9803. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  9804. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  9805. }
  9806. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  9807. if (var->isInvalidDecl()) return;
  9808. if (getLangOpts().OpenCL) {
  9809. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  9810. // initialiser
  9811. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  9812. !var->hasInit()) {
  9813. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  9814. << 1 /*Init*/;
  9815. var->setInvalidDecl();
  9816. return;
  9817. }
  9818. }
  9819. // In Objective-C, don't allow jumps past the implicit initialization of a
  9820. // local retaining variable.
  9821. if (getLangOpts().ObjC1 &&
  9822. var->hasLocalStorage()) {
  9823. switch (var->getType().getObjCLifetime()) {
  9824. case Qualifiers::OCL_None:
  9825. case Qualifiers::OCL_ExplicitNone:
  9826. case Qualifiers::OCL_Autoreleasing:
  9827. break;
  9828. case Qualifiers::OCL_Weak:
  9829. case Qualifiers::OCL_Strong:
  9830. getCurFunction()->setHasBranchProtectedScope();
  9831. break;
  9832. }
  9833. }
  9834. // Warn about externally-visible variables being defined without a
  9835. // prior declaration. We only want to do this for global
  9836. // declarations, but we also specifically need to avoid doing it for
  9837. // class members because the linkage of an anonymous class can
  9838. // change if it's later given a typedef name.
  9839. if (var->isThisDeclarationADefinition() &&
  9840. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  9841. var->isExternallyVisible() && var->hasLinkage() &&
  9842. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  9843. var->getLocation())) {
  9844. // Find a previous declaration that's not a definition.
  9845. VarDecl *prev = var->getPreviousDecl();
  9846. while (prev && prev->isThisDeclarationADefinition())
  9847. prev = prev->getPreviousDecl();
  9848. if (!prev)
  9849. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  9850. }
  9851. // Cache the result of checking for constant initialization.
  9852. Optional<bool> CacheHasConstInit;
  9853. const Expr *CacheCulprit;
  9854. auto checkConstInit = [&]() mutable {
  9855. if (!CacheHasConstInit)
  9856. CacheHasConstInit = var->getInit()->isConstantInitializer(
  9857. Context, var->getType()->isReferenceType(), &CacheCulprit);
  9858. return *CacheHasConstInit;
  9859. };
  9860. if (var->getTLSKind() == VarDecl::TLS_Static) {
  9861. if (var->getType().isDestructedType()) {
  9862. // GNU C++98 edits for __thread, [basic.start.term]p3:
  9863. // The type of an object with thread storage duration shall not
  9864. // have a non-trivial destructor.
  9865. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  9866. if (getLangOpts().CPlusPlus11)
  9867. Diag(var->getLocation(), diag::note_use_thread_local);
  9868. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  9869. if (!checkConstInit()) {
  9870. // GNU C++98 edits for __thread, [basic.start.init]p4:
  9871. // An object of thread storage duration shall not require dynamic
  9872. // initialization.
  9873. // FIXME: Need strict checking here.
  9874. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  9875. << CacheCulprit->getSourceRange();
  9876. if (getLangOpts().CPlusPlus11)
  9877. Diag(var->getLocation(), diag::note_use_thread_local);
  9878. }
  9879. }
  9880. }
  9881. // Apply section attributes and pragmas to global variables.
  9882. bool GlobalStorage = var->hasGlobalStorage();
  9883. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  9884. !inTemplateInstantiation()) {
  9885. PragmaStack<StringLiteral *> *Stack = nullptr;
  9886. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  9887. if (var->getType().isConstQualified())
  9888. Stack = &ConstSegStack;
  9889. else if (!var->getInit()) {
  9890. Stack = &BSSSegStack;
  9891. SectionFlags |= ASTContext::PSF_Write;
  9892. } else {
  9893. Stack = &DataSegStack;
  9894. SectionFlags |= ASTContext::PSF_Write;
  9895. }
  9896. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  9897. var->addAttr(SectionAttr::CreateImplicit(
  9898. Context, SectionAttr::Declspec_allocate,
  9899. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  9900. }
  9901. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  9902. if (UnifySection(SA->getName(), SectionFlags, var))
  9903. var->dropAttr<SectionAttr>();
  9904. // Apply the init_seg attribute if this has an initializer. If the
  9905. // initializer turns out to not be dynamic, we'll end up ignoring this
  9906. // attribute.
  9907. if (CurInitSeg && var->getInit())
  9908. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  9909. CurInitSegLoc));
  9910. }
  9911. // All the following checks are C++ only.
  9912. if (!getLangOpts().CPlusPlus) {
  9913. // If this variable must be emitted, add it as an initializer for the
  9914. // current module.
  9915. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9916. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9917. return;
  9918. }
  9919. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  9920. CheckCompleteDecompositionDeclaration(DD);
  9921. QualType type = var->getType();
  9922. if (type->isDependentType()) return;
  9923. // __block variables might require us to capture a copy-initializer.
  9924. if (var->hasAttr<BlocksAttr>()) {
  9925. // It's currently invalid to ever have a __block variable with an
  9926. // array type; should we diagnose that here?
  9927. // Regardless, we don't want to ignore array nesting when
  9928. // constructing this copy.
  9929. if (type->isStructureOrClassType()) {
  9930. EnterExpressionEvaluationContext scope(
  9931. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  9932. SourceLocation poi = var->getLocation();
  9933. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  9934. ExprResult result
  9935. = PerformMoveOrCopyInitialization(
  9936. InitializedEntity::InitializeBlock(poi, type, false),
  9937. var, var->getType(), varRef, /*AllowNRVO=*/true);
  9938. if (!result.isInvalid()) {
  9939. result = MaybeCreateExprWithCleanups(result);
  9940. Expr *init = result.getAs<Expr>();
  9941. Context.setBlockVarCopyInits(var, init);
  9942. }
  9943. }
  9944. }
  9945. Expr *Init = var->getInit();
  9946. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  9947. QualType baseType = Context.getBaseElementType(type);
  9948. if (Init && !Init->isValueDependent()) {
  9949. if (var->isConstexpr()) {
  9950. SmallVector<PartialDiagnosticAt, 8> Notes;
  9951. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  9952. SourceLocation DiagLoc = var->getLocation();
  9953. // If the note doesn't add any useful information other than a source
  9954. // location, fold it into the primary diagnostic.
  9955. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  9956. diag::note_invalid_subexpr_in_const_expr) {
  9957. DiagLoc = Notes[0].first;
  9958. Notes.clear();
  9959. }
  9960. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  9961. << var << Init->getSourceRange();
  9962. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  9963. Diag(Notes[I].first, Notes[I].second);
  9964. }
  9965. } else if (var->isUsableInConstantExpressions(Context)) {
  9966. // Check whether the initializer of a const variable of integral or
  9967. // enumeration type is an ICE now, since we can't tell whether it was
  9968. // initialized by a constant expression if we check later.
  9969. var->checkInitIsICE();
  9970. }
  9971. // Don't emit further diagnostics about constexpr globals since they
  9972. // were just diagnosed.
  9973. if (!var->isConstexpr() && GlobalStorage &&
  9974. var->hasAttr<RequireConstantInitAttr>()) {
  9975. // FIXME: Need strict checking in C++03 here.
  9976. bool DiagErr = getLangOpts().CPlusPlus11
  9977. ? !var->checkInitIsICE() : !checkConstInit();
  9978. if (DiagErr) {
  9979. auto attr = var->getAttr<RequireConstantInitAttr>();
  9980. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  9981. << Init->getSourceRange();
  9982. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  9983. << attr->getRange();
  9984. if (getLangOpts().CPlusPlus11) {
  9985. APValue Value;
  9986. SmallVector<PartialDiagnosticAt, 8> Notes;
  9987. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  9988. for (auto &it : Notes)
  9989. Diag(it.first, it.second);
  9990. } else {
  9991. Diag(CacheCulprit->getExprLoc(),
  9992. diag::note_invalid_subexpr_in_const_expr)
  9993. << CacheCulprit->getSourceRange();
  9994. }
  9995. }
  9996. }
  9997. else if (!var->isConstexpr() && IsGlobal &&
  9998. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  9999. var->getLocation())) {
  10000. // Warn about globals which don't have a constant initializer. Don't
  10001. // warn about globals with a non-trivial destructor because we already
  10002. // warned about them.
  10003. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10004. if (!(RD && !RD->hasTrivialDestructor())) {
  10005. if (!checkConstInit())
  10006. Diag(var->getLocation(), diag::warn_global_constructor)
  10007. << Init->getSourceRange();
  10008. }
  10009. }
  10010. }
  10011. // Require the destructor.
  10012. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10013. FinalizeVarWithDestructor(var, recordType);
  10014. // If this variable must be emitted, add it as an initializer for the current
  10015. // module.
  10016. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10017. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10018. }
  10019. /// \brief Determines if a variable's alignment is dependent.
  10020. static bool hasDependentAlignment(VarDecl *VD) {
  10021. if (VD->getType()->isDependentType())
  10022. return true;
  10023. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10024. if (I->isAlignmentDependent())
  10025. return true;
  10026. return false;
  10027. }
  10028. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10029. /// any semantic actions necessary after any initializer has been attached.
  10030. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10031. // Note that we are no longer parsing the initializer for this declaration.
  10032. ParsingInitForAutoVars.erase(ThisDecl);
  10033. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10034. if (!VD)
  10035. return;
  10036. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10037. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10038. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10039. if (PragmaClangBSSSection.Valid)
  10040. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10041. PragmaClangBSSSection.SectionName,
  10042. PragmaClangBSSSection.PragmaLocation));
  10043. if (PragmaClangDataSection.Valid)
  10044. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10045. PragmaClangDataSection.SectionName,
  10046. PragmaClangDataSection.PragmaLocation));
  10047. if (PragmaClangRodataSection.Valid)
  10048. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10049. PragmaClangRodataSection.SectionName,
  10050. PragmaClangRodataSection.PragmaLocation));
  10051. }
  10052. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10053. for (auto *BD : DD->bindings()) {
  10054. FinalizeDeclaration(BD);
  10055. }
  10056. }
  10057. checkAttributesAfterMerging(*this, *VD);
  10058. // Perform TLS alignment check here after attributes attached to the variable
  10059. // which may affect the alignment have been processed. Only perform the check
  10060. // if the target has a maximum TLS alignment (zero means no constraints).
  10061. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10062. // Protect the check so that it's not performed on dependent types and
  10063. // dependent alignments (we can't determine the alignment in that case).
  10064. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10065. !VD->isInvalidDecl()) {
  10066. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10067. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10068. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10069. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10070. << (unsigned)MaxAlignChars.getQuantity();
  10071. }
  10072. }
  10073. }
  10074. if (VD->isStaticLocal()) {
  10075. if (FunctionDecl *FD =
  10076. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10077. // Static locals inherit dll attributes from their function.
  10078. if (Attr *A = getDLLAttr(FD)) {
  10079. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10080. NewAttr->setInherited(true);
  10081. VD->addAttr(NewAttr);
  10082. }
  10083. // CUDA E.2.9.4: Within the body of a __device__ or __global__
  10084. // function, only __shared__ variables may be declared with
  10085. // static storage class.
  10086. if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
  10087. CUDADiagIfDeviceCode(VD->getLocation(),
  10088. diag::err_device_static_local_var)
  10089. << CurrentCUDATarget())
  10090. VD->setInvalidDecl();
  10091. }
  10092. }
  10093. // Perform check for initializers of device-side global variables.
  10094. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10095. // 7.5). We must also apply the same checks to all __shared__
  10096. // variables whether they are local or not. CUDA also allows
  10097. // constant initializers for __constant__ and __device__ variables.
  10098. if (getLangOpts().CUDA) {
  10099. const Expr *Init = VD->getInit();
  10100. if (Init && VD->hasGlobalStorage()) {
  10101. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  10102. VD->hasAttr<CUDASharedAttr>()) {
  10103. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  10104. bool AllowedInit = false;
  10105. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  10106. AllowedInit =
  10107. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  10108. // We'll allow constant initializers even if it's a non-empty
  10109. // constructor according to CUDA rules. This deviates from NVCC,
  10110. // but allows us to handle things like constexpr constructors.
  10111. if (!AllowedInit &&
  10112. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10113. AllowedInit = VD->getInit()->isConstantInitializer(
  10114. Context, VD->getType()->isReferenceType());
  10115. // Also make sure that destructor, if there is one, is empty.
  10116. if (AllowedInit)
  10117. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  10118. AllowedInit =
  10119. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  10120. if (!AllowedInit) {
  10121. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  10122. ? diag::err_shared_var_init
  10123. : diag::err_dynamic_var_init)
  10124. << Init->getSourceRange();
  10125. VD->setInvalidDecl();
  10126. }
  10127. } else {
  10128. // This is a host-side global variable. Check that the initializer is
  10129. // callable from the host side.
  10130. const FunctionDecl *InitFn = nullptr;
  10131. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  10132. InitFn = CE->getConstructor();
  10133. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  10134. InitFn = CE->getDirectCallee();
  10135. }
  10136. if (InitFn) {
  10137. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  10138. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  10139. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  10140. << InitFnTarget << InitFn;
  10141. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  10142. VD->setInvalidDecl();
  10143. }
  10144. }
  10145. }
  10146. }
  10147. }
  10148. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10149. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10150. // Imported static data members cannot be defined out-of-line.
  10151. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10152. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10153. VD->isThisDeclarationADefinition()) {
  10154. // We allow definitions of dllimport class template static data members
  10155. // with a warning.
  10156. CXXRecordDecl *Context =
  10157. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10158. bool IsClassTemplateMember =
  10159. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10160. Context->getDescribedClassTemplate();
  10161. Diag(VD->getLocation(),
  10162. IsClassTemplateMember
  10163. ? diag::warn_attribute_dllimport_static_field_definition
  10164. : diag::err_attribute_dllimport_static_field_definition);
  10165. Diag(IA->getLocation(), diag::note_attribute);
  10166. if (!IsClassTemplateMember)
  10167. VD->setInvalidDecl();
  10168. }
  10169. }
  10170. // dllimport/dllexport variables cannot be thread local, their TLS index
  10171. // isn't exported with the variable.
  10172. if (DLLAttr && VD->getTLSKind()) {
  10173. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10174. if (F && getDLLAttr(F)) {
  10175. assert(VD->isStaticLocal());
  10176. // But if this is a static local in a dlimport/dllexport function, the
  10177. // function will never be inlined, which means the var would never be
  10178. // imported, so having it marked import/export is safe.
  10179. } else {
  10180. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10181. << DLLAttr;
  10182. VD->setInvalidDecl();
  10183. }
  10184. }
  10185. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10186. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10187. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10188. VD->dropAttr<UsedAttr>();
  10189. }
  10190. }
  10191. const DeclContext *DC = VD->getDeclContext();
  10192. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10193. // member, set the visibility of this variable.
  10194. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10195. AddPushedVisibilityAttribute(VD);
  10196. // FIXME: Warn on unused var template partial specializations.
  10197. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10198. MarkUnusedFileScopedDecl(VD);
  10199. // Now we have parsed the initializer and can update the table of magic
  10200. // tag values.
  10201. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10202. !VD->getType()->isIntegralOrEnumerationType())
  10203. return;
  10204. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10205. const Expr *MagicValueExpr = VD->getInit();
  10206. if (!MagicValueExpr) {
  10207. continue;
  10208. }
  10209. llvm::APSInt MagicValueInt;
  10210. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10211. Diag(I->getRange().getBegin(),
  10212. diag::err_type_tag_for_datatype_not_ice)
  10213. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10214. continue;
  10215. }
  10216. if (MagicValueInt.getActiveBits() > 64) {
  10217. Diag(I->getRange().getBegin(),
  10218. diag::err_type_tag_for_datatype_too_large)
  10219. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10220. continue;
  10221. }
  10222. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10223. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10224. MagicValue,
  10225. I->getMatchingCType(),
  10226. I->getLayoutCompatible(),
  10227. I->getMustBeNull());
  10228. }
  10229. }
  10230. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10231. auto *VD = dyn_cast<VarDecl>(DD);
  10232. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10233. }
  10234. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10235. ArrayRef<Decl *> Group) {
  10236. SmallVector<Decl*, 8> Decls;
  10237. if (DS.isTypeSpecOwned())
  10238. Decls.push_back(DS.getRepAsDecl());
  10239. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  10240. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  10241. bool DiagnosedMultipleDecomps = false;
  10242. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  10243. bool DiagnosedNonDeducedAuto = false;
  10244. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10245. if (Decl *D = Group[i]) {
  10246. // For declarators, there are some additional syntactic-ish checks we need
  10247. // to perform.
  10248. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  10249. if (!FirstDeclaratorInGroup)
  10250. FirstDeclaratorInGroup = DD;
  10251. if (!FirstDecompDeclaratorInGroup)
  10252. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  10253. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  10254. !hasDeducedAuto(DD))
  10255. FirstNonDeducedAutoInGroup = DD;
  10256. if (FirstDeclaratorInGroup != DD) {
  10257. // A decomposition declaration cannot be combined with any other
  10258. // declaration in the same group.
  10259. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  10260. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  10261. diag::err_decomp_decl_not_alone)
  10262. << FirstDeclaratorInGroup->getSourceRange()
  10263. << DD->getSourceRange();
  10264. DiagnosedMultipleDecomps = true;
  10265. }
  10266. // A declarator that uses 'auto' in any way other than to declare a
  10267. // variable with a deduced type cannot be combined with any other
  10268. // declarator in the same group.
  10269. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  10270. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  10271. diag::err_auto_non_deduced_not_alone)
  10272. << FirstNonDeducedAutoInGroup->getType()
  10273. ->hasAutoForTrailingReturnType()
  10274. << FirstDeclaratorInGroup->getSourceRange()
  10275. << DD->getSourceRange();
  10276. DiagnosedNonDeducedAuto = true;
  10277. }
  10278. }
  10279. }
  10280. Decls.push_back(D);
  10281. }
  10282. }
  10283. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  10284. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  10285. handleTagNumbering(Tag, S);
  10286. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  10287. getLangOpts().CPlusPlus)
  10288. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  10289. }
  10290. }
  10291. return BuildDeclaratorGroup(Decls);
  10292. }
  10293. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  10294. /// group, performing any necessary semantic checking.
  10295. Sema::DeclGroupPtrTy
  10296. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  10297. // C++14 [dcl.spec.auto]p7: (DR1347)
  10298. // If the type that replaces the placeholder type is not the same in each
  10299. // deduction, the program is ill-formed.
  10300. if (Group.size() > 1) {
  10301. QualType Deduced;
  10302. VarDecl *DeducedDecl = nullptr;
  10303. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10304. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  10305. if (!D || D->isInvalidDecl())
  10306. break;
  10307. DeducedType *DT = D->getType()->getContainedDeducedType();
  10308. if (!DT || DT->getDeducedType().isNull())
  10309. continue;
  10310. if (Deduced.isNull()) {
  10311. Deduced = DT->getDeducedType();
  10312. DeducedDecl = D;
  10313. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  10314. auto *AT = dyn_cast<AutoType>(DT);
  10315. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  10316. diag::err_auto_different_deductions)
  10317. << (AT ? (unsigned)AT->getKeyword() : 3)
  10318. << Deduced << DeducedDecl->getDeclName()
  10319. << DT->getDeducedType() << D->getDeclName()
  10320. << DeducedDecl->getInit()->getSourceRange()
  10321. << D->getInit()->getSourceRange();
  10322. D->setInvalidDecl();
  10323. break;
  10324. }
  10325. }
  10326. }
  10327. ActOnDocumentableDecls(Group);
  10328. return DeclGroupPtrTy::make(
  10329. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  10330. }
  10331. void Sema::ActOnDocumentableDecl(Decl *D) {
  10332. ActOnDocumentableDecls(D);
  10333. }
  10334. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10335. // Don't parse the comment if Doxygen diagnostics are ignored.
  10336. if (Group.empty() || !Group[0])
  10337. return;
  10338. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10339. Group[0]->getLocation()) &&
  10340. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10341. Group[0]->getLocation()))
  10342. return;
  10343. if (Group.size() >= 2) {
  10344. // This is a decl group. Normally it will contain only declarations
  10345. // produced from declarator list. But in case we have any definitions or
  10346. // additional declaration references:
  10347. // 'typedef struct S {} S;'
  10348. // 'typedef struct S *S;'
  10349. // 'struct S *pS;'
  10350. // FinalizeDeclaratorGroup adds these as separate declarations.
  10351. Decl *MaybeTagDecl = Group[0];
  10352. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10353. Group = Group.slice(1);
  10354. }
  10355. }
  10356. // See if there are any new comments that are not attached to a decl.
  10357. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10358. if (!Comments.empty() &&
  10359. !Comments.back()->isAttached()) {
  10360. // There is at least one comment that not attached to a decl.
  10361. // Maybe it should be attached to one of these decls?
  10362. //
  10363. // Note that this way we pick up not only comments that precede the
  10364. // declaration, but also comments that *follow* the declaration -- thanks to
  10365. // the lookahead in the lexer: we've consumed the semicolon and looked
  10366. // ahead through comments.
  10367. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10368. Context.getCommentForDecl(Group[i], &PP);
  10369. }
  10370. }
  10371. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10372. /// to introduce parameters into function prototype scope.
  10373. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10374. const DeclSpec &DS = D.getDeclSpec();
  10375. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10376. // C++03 [dcl.stc]p2 also permits 'auto'.
  10377. StorageClass SC = SC_None;
  10378. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10379. SC = SC_Register;
  10380. // In C++11, the 'register' storage class specifier is deprecated.
  10381. // In C++17, it is not allowed, but we tolerate it as an extension.
  10382. if (getLangOpts().CPlusPlus11) {
  10383. Diag(DS.getStorageClassSpecLoc(),
  10384. getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
  10385. : diag::warn_deprecated_register)
  10386. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  10387. }
  10388. } else if (getLangOpts().CPlusPlus &&
  10389. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  10390. SC = SC_Auto;
  10391. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  10392. Diag(DS.getStorageClassSpecLoc(),
  10393. diag::err_invalid_storage_class_in_func_decl);
  10394. D.getMutableDeclSpec().ClearStorageClassSpecs();
  10395. }
  10396. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  10397. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  10398. << DeclSpec::getSpecifierName(TSCS);
  10399. if (DS.isInlineSpecified())
  10400. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  10401. << getLangOpts().CPlusPlus1z;
  10402. if (DS.isConstexprSpecified())
  10403. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  10404. << 0;
  10405. if (DS.isConceptSpecified())
  10406. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  10407. DiagnoseFunctionSpecifiers(DS);
  10408. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10409. QualType parmDeclType = TInfo->getType();
  10410. if (getLangOpts().CPlusPlus) {
  10411. // Check that there are no default arguments inside the type of this
  10412. // parameter.
  10413. CheckExtraCXXDefaultArguments(D);
  10414. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  10415. if (D.getCXXScopeSpec().isSet()) {
  10416. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  10417. << D.getCXXScopeSpec().getRange();
  10418. D.getCXXScopeSpec().clear();
  10419. }
  10420. }
  10421. // Ensure we have a valid name
  10422. IdentifierInfo *II = nullptr;
  10423. if (D.hasName()) {
  10424. II = D.getIdentifier();
  10425. if (!II) {
  10426. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  10427. << GetNameForDeclarator(D).getName();
  10428. D.setInvalidType(true);
  10429. }
  10430. }
  10431. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  10432. if (II) {
  10433. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  10434. ForVisibleRedeclaration);
  10435. LookupName(R, S);
  10436. if (R.isSingleResult()) {
  10437. NamedDecl *PrevDecl = R.getFoundDecl();
  10438. if (PrevDecl->isTemplateParameter()) {
  10439. // Maybe we will complain about the shadowed template parameter.
  10440. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10441. // Just pretend that we didn't see the previous declaration.
  10442. PrevDecl = nullptr;
  10443. } else if (S->isDeclScope(PrevDecl)) {
  10444. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  10445. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10446. // Recover by removing the name
  10447. II = nullptr;
  10448. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  10449. D.setInvalidType(true);
  10450. }
  10451. }
  10452. }
  10453. // Temporarily put parameter variables in the translation unit, not
  10454. // the enclosing context. This prevents them from accidentally
  10455. // looking like class members in C++.
  10456. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  10457. D.getLocStart(),
  10458. D.getIdentifierLoc(), II,
  10459. parmDeclType, TInfo,
  10460. SC);
  10461. if (D.isInvalidType())
  10462. New->setInvalidDecl();
  10463. assert(S->isFunctionPrototypeScope());
  10464. assert(S->getFunctionPrototypeDepth() >= 1);
  10465. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  10466. S->getNextFunctionPrototypeIndex());
  10467. // Add the parameter declaration into this scope.
  10468. S->AddDecl(New);
  10469. if (II)
  10470. IdResolver.AddDecl(New);
  10471. ProcessDeclAttributes(S, New, D);
  10472. if (D.getDeclSpec().isModulePrivateSpecified())
  10473. Diag(New->getLocation(), diag::err_module_private_local)
  10474. << 1 << New->getDeclName()
  10475. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  10476. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  10477. if (New->hasAttr<BlocksAttr>()) {
  10478. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  10479. }
  10480. return New;
  10481. }
  10482. /// \brief Synthesizes a variable for a parameter arising from a
  10483. /// typedef.
  10484. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  10485. SourceLocation Loc,
  10486. QualType T) {
  10487. /* FIXME: setting StartLoc == Loc.
  10488. Would it be worth to modify callers so as to provide proper source
  10489. location for the unnamed parameters, embedding the parameter's type? */
  10490. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  10491. T, Context.getTrivialTypeSourceInfo(T, Loc),
  10492. SC_None, nullptr);
  10493. Param->setImplicit();
  10494. return Param;
  10495. }
  10496. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  10497. // Don't diagnose unused-parameter errors in template instantiations; we
  10498. // will already have done so in the template itself.
  10499. if (inTemplateInstantiation())
  10500. return;
  10501. for (const ParmVarDecl *Parameter : Parameters) {
  10502. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  10503. !Parameter->hasAttr<UnusedAttr>()) {
  10504. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  10505. << Parameter->getDeclName();
  10506. }
  10507. }
  10508. }
  10509. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  10510. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  10511. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  10512. return;
  10513. // Warn if the return value is pass-by-value and larger than the specified
  10514. // threshold.
  10515. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  10516. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  10517. if (Size > LangOpts.NumLargeByValueCopy)
  10518. Diag(D->getLocation(), diag::warn_return_value_size)
  10519. << D->getDeclName() << Size;
  10520. }
  10521. // Warn if any parameter is pass-by-value and larger than the specified
  10522. // threshold.
  10523. for (const ParmVarDecl *Parameter : Parameters) {
  10524. QualType T = Parameter->getType();
  10525. if (T->isDependentType() || !T.isPODType(Context))
  10526. continue;
  10527. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  10528. if (Size > LangOpts.NumLargeByValueCopy)
  10529. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  10530. << Parameter->getDeclName() << Size;
  10531. }
  10532. }
  10533. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  10534. SourceLocation NameLoc, IdentifierInfo *Name,
  10535. QualType T, TypeSourceInfo *TSInfo,
  10536. StorageClass SC) {
  10537. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  10538. if (getLangOpts().ObjCAutoRefCount &&
  10539. T.getObjCLifetime() == Qualifiers::OCL_None &&
  10540. T->isObjCLifetimeType()) {
  10541. Qualifiers::ObjCLifetime lifetime;
  10542. // Special cases for arrays:
  10543. // - if it's const, use __unsafe_unretained
  10544. // - otherwise, it's an error
  10545. if (T->isArrayType()) {
  10546. if (!T.isConstQualified()) {
  10547. DelayedDiagnostics.add(
  10548. sema::DelayedDiagnostic::makeForbiddenType(
  10549. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  10550. }
  10551. lifetime = Qualifiers::OCL_ExplicitNone;
  10552. } else {
  10553. lifetime = T->getObjCARCImplicitLifetime();
  10554. }
  10555. T = Context.getLifetimeQualifiedType(T, lifetime);
  10556. }
  10557. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  10558. Context.getAdjustedParameterType(T),
  10559. TSInfo, SC, nullptr);
  10560. // Parameters can not be abstract class types.
  10561. // For record types, this is done by the AbstractClassUsageDiagnoser once
  10562. // the class has been completely parsed.
  10563. if (!CurContext->isRecord() &&
  10564. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  10565. AbstractParamType))
  10566. New->setInvalidDecl();
  10567. // Parameter declarators cannot be interface types. All ObjC objects are
  10568. // passed by reference.
  10569. if (T->isObjCObjectType()) {
  10570. SourceLocation TypeEndLoc =
  10571. getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
  10572. Diag(NameLoc,
  10573. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  10574. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  10575. T = Context.getObjCObjectPointerType(T);
  10576. New->setType(T);
  10577. }
  10578. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  10579. // duration shall not be qualified by an address-space qualifier."
  10580. // Since all parameters have automatic store duration, they can not have
  10581. // an address space.
  10582. if (T.getAddressSpace() != LangAS::Default &&
  10583. // OpenCL allows function arguments declared to be an array of a type
  10584. // to be qualified with an address space.
  10585. !(getLangOpts().OpenCL &&
  10586. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  10587. Diag(NameLoc, diag::err_arg_with_address_space);
  10588. New->setInvalidDecl();
  10589. }
  10590. return New;
  10591. }
  10592. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  10593. SourceLocation LocAfterDecls) {
  10594. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  10595. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  10596. // for a K&R function.
  10597. if (!FTI.hasPrototype) {
  10598. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  10599. --i;
  10600. if (FTI.Params[i].Param == nullptr) {
  10601. SmallString<256> Code;
  10602. llvm::raw_svector_ostream(Code)
  10603. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  10604. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  10605. << FTI.Params[i].Ident
  10606. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  10607. // Implicitly declare the argument as type 'int' for lack of a better
  10608. // type.
  10609. AttributeFactory attrs;
  10610. DeclSpec DS(attrs);
  10611. const char* PrevSpec; // unused
  10612. unsigned DiagID; // unused
  10613. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  10614. DiagID, Context.getPrintingPolicy());
  10615. // Use the identifier location for the type source range.
  10616. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  10617. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  10618. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  10619. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  10620. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  10621. }
  10622. }
  10623. }
  10624. }
  10625. Decl *
  10626. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  10627. MultiTemplateParamsArg TemplateParameterLists,
  10628. SkipBodyInfo *SkipBody) {
  10629. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  10630. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  10631. Scope *ParentScope = FnBodyScope->getParent();
  10632. D.setFunctionDefinitionKind(FDK_Definition);
  10633. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  10634. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  10635. }
  10636. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  10637. Consumer.HandleInlineFunctionDefinition(D);
  10638. }
  10639. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  10640. const FunctionDecl*& PossibleZeroParamPrototype) {
  10641. // Don't warn about invalid declarations.
  10642. if (FD->isInvalidDecl())
  10643. return false;
  10644. // Or declarations that aren't global.
  10645. if (!FD->isGlobal())
  10646. return false;
  10647. // Don't warn about C++ member functions.
  10648. if (isa<CXXMethodDecl>(FD))
  10649. return false;
  10650. // Don't warn about 'main'.
  10651. if (FD->isMain())
  10652. return false;
  10653. // Don't warn about inline functions.
  10654. if (FD->isInlined())
  10655. return false;
  10656. // Don't warn about function templates.
  10657. if (FD->getDescribedFunctionTemplate())
  10658. return false;
  10659. // Don't warn about function template specializations.
  10660. if (FD->isFunctionTemplateSpecialization())
  10661. return false;
  10662. // Don't warn for OpenCL kernels.
  10663. if (FD->hasAttr<OpenCLKernelAttr>())
  10664. return false;
  10665. // Don't warn on explicitly deleted functions.
  10666. if (FD->isDeleted())
  10667. return false;
  10668. bool MissingPrototype = true;
  10669. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  10670. Prev; Prev = Prev->getPreviousDecl()) {
  10671. // Ignore any declarations that occur in function or method
  10672. // scope, because they aren't visible from the header.
  10673. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  10674. continue;
  10675. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  10676. if (FD->getNumParams() == 0)
  10677. PossibleZeroParamPrototype = Prev;
  10678. break;
  10679. }
  10680. return MissingPrototype;
  10681. }
  10682. void
  10683. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  10684. const FunctionDecl *EffectiveDefinition,
  10685. SkipBodyInfo *SkipBody) {
  10686. const FunctionDecl *Definition = EffectiveDefinition;
  10687. if (!Definition)
  10688. if (!FD->isDefined(Definition))
  10689. return;
  10690. if (canRedefineFunction(Definition, getLangOpts()))
  10691. return;
  10692. // Don't emit an error when this is redefinition of a typo-corrected
  10693. // definition.
  10694. if (TypoCorrectedFunctionDefinitions.count(Definition))
  10695. return;
  10696. // If we don't have a visible definition of the function, and it's inline or
  10697. // a template, skip the new definition.
  10698. if (SkipBody && !hasVisibleDefinition(Definition) &&
  10699. (Definition->getFormalLinkage() == InternalLinkage ||
  10700. Definition->isInlined() ||
  10701. Definition->getDescribedFunctionTemplate() ||
  10702. Definition->getNumTemplateParameterLists())) {
  10703. SkipBody->ShouldSkip = true;
  10704. if (auto *TD = Definition->getDescribedFunctionTemplate())
  10705. makeMergedDefinitionVisible(TD);
  10706. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  10707. return;
  10708. }
  10709. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  10710. Definition->getStorageClass() == SC_Extern)
  10711. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  10712. << FD->getDeclName() << getLangOpts().CPlusPlus;
  10713. else
  10714. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  10715. Diag(Definition->getLocation(), diag::note_previous_definition);
  10716. FD->setInvalidDecl();
  10717. }
  10718. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  10719. Sema &S) {
  10720. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  10721. LambdaScopeInfo *LSI = S.PushLambdaScope();
  10722. LSI->CallOperator = CallOperator;
  10723. LSI->Lambda = LambdaClass;
  10724. LSI->ReturnType = CallOperator->getReturnType();
  10725. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  10726. if (LCD == LCD_None)
  10727. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  10728. else if (LCD == LCD_ByCopy)
  10729. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  10730. else if (LCD == LCD_ByRef)
  10731. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  10732. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  10733. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  10734. LSI->Mutable = !CallOperator->isConst();
  10735. // Add the captures to the LSI so they can be noted as already
  10736. // captured within tryCaptureVar.
  10737. auto I = LambdaClass->field_begin();
  10738. for (const auto &C : LambdaClass->captures()) {
  10739. if (C.capturesVariable()) {
  10740. VarDecl *VD = C.getCapturedVar();
  10741. if (VD->isInitCapture())
  10742. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  10743. QualType CaptureType = VD->getType();
  10744. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  10745. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  10746. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  10747. /*EllipsisLoc*/C.isPackExpansion()
  10748. ? C.getEllipsisLoc() : SourceLocation(),
  10749. CaptureType, /*Expr*/ nullptr);
  10750. } else if (C.capturesThis()) {
  10751. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  10752. /*Expr*/ nullptr,
  10753. C.getCaptureKind() == LCK_StarThis);
  10754. } else {
  10755. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  10756. }
  10757. ++I;
  10758. }
  10759. }
  10760. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  10761. SkipBodyInfo *SkipBody) {
  10762. if (!D)
  10763. return D;
  10764. FunctionDecl *FD = nullptr;
  10765. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  10766. FD = FunTmpl->getTemplatedDecl();
  10767. else
  10768. FD = cast<FunctionDecl>(D);
  10769. // Check for defining attributes before the check for redefinition.
  10770. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  10771. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  10772. FD->dropAttr<AliasAttr>();
  10773. FD->setInvalidDecl();
  10774. }
  10775. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  10776. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  10777. FD->dropAttr<IFuncAttr>();
  10778. FD->setInvalidDecl();
  10779. }
  10780. // See if this is a redefinition. If 'will have body' is already set, then
  10781. // these checks were already performed when it was set.
  10782. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  10783. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  10784. // If we're skipping the body, we're done. Don't enter the scope.
  10785. if (SkipBody && SkipBody->ShouldSkip)
  10786. return D;
  10787. }
  10788. // Mark this function as "will have a body eventually". This lets users to
  10789. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  10790. // this function.
  10791. FD->setWillHaveBody();
  10792. // If we are instantiating a generic lambda call operator, push
  10793. // a LambdaScopeInfo onto the function stack. But use the information
  10794. // that's already been calculated (ActOnLambdaExpr) to prime the current
  10795. // LambdaScopeInfo.
  10796. // When the template operator is being specialized, the LambdaScopeInfo,
  10797. // has to be properly restored so that tryCaptureVariable doesn't try
  10798. // and capture any new variables. In addition when calculating potential
  10799. // captures during transformation of nested lambdas, it is necessary to
  10800. // have the LSI properly restored.
  10801. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  10802. assert(inTemplateInstantiation() &&
  10803. "There should be an active template instantiation on the stack "
  10804. "when instantiating a generic lambda!");
  10805. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  10806. } else {
  10807. // Enter a new function scope
  10808. PushFunctionScope();
  10809. }
  10810. // Builtin functions cannot be defined.
  10811. if (unsigned BuiltinID = FD->getBuiltinID()) {
  10812. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  10813. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  10814. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  10815. FD->setInvalidDecl();
  10816. }
  10817. }
  10818. // The return type of a function definition must be complete
  10819. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  10820. QualType ResultType = FD->getReturnType();
  10821. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  10822. !FD->isInvalidDecl() &&
  10823. RequireCompleteType(FD->getLocation(), ResultType,
  10824. diag::err_func_def_incomplete_result))
  10825. FD->setInvalidDecl();
  10826. if (FnBodyScope)
  10827. PushDeclContext(FnBodyScope, FD);
  10828. // Check the validity of our function parameters
  10829. CheckParmsForFunctionDef(FD->parameters(),
  10830. /*CheckParameterNames=*/true);
  10831. // Add non-parameter declarations already in the function to the current
  10832. // scope.
  10833. if (FnBodyScope) {
  10834. for (Decl *NPD : FD->decls()) {
  10835. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  10836. if (!NonParmDecl)
  10837. continue;
  10838. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  10839. "parameters should not be in newly created FD yet");
  10840. // If the decl has a name, make it accessible in the current scope.
  10841. if (NonParmDecl->getDeclName())
  10842. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  10843. // Similarly, dive into enums and fish their constants out, making them
  10844. // accessible in this scope.
  10845. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  10846. for (auto *EI : ED->enumerators())
  10847. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  10848. }
  10849. }
  10850. }
  10851. // Introduce our parameters into the function scope
  10852. for (auto Param : FD->parameters()) {
  10853. Param->setOwningFunction(FD);
  10854. // If this has an identifier, add it to the scope stack.
  10855. if (Param->getIdentifier() && FnBodyScope) {
  10856. CheckShadow(FnBodyScope, Param);
  10857. PushOnScopeChains(Param, FnBodyScope);
  10858. }
  10859. }
  10860. // Ensure that the function's exception specification is instantiated.
  10861. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  10862. ResolveExceptionSpec(D->getLocation(), FPT);
  10863. // dllimport cannot be applied to non-inline function definitions.
  10864. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  10865. !FD->isTemplateInstantiation()) {
  10866. assert(!FD->hasAttr<DLLExportAttr>());
  10867. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  10868. FD->setInvalidDecl();
  10869. return D;
  10870. }
  10871. // We want to attach documentation to original Decl (which might be
  10872. // a function template).
  10873. ActOnDocumentableDecl(D);
  10874. if (getCurLexicalContext()->isObjCContainer() &&
  10875. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  10876. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  10877. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  10878. return D;
  10879. }
  10880. /// \brief Given the set of return statements within a function body,
  10881. /// compute the variables that are subject to the named return value
  10882. /// optimization.
  10883. ///
  10884. /// Each of the variables that is subject to the named return value
  10885. /// optimization will be marked as NRVO variables in the AST, and any
  10886. /// return statement that has a marked NRVO variable as its NRVO candidate can
  10887. /// use the named return value optimization.
  10888. ///
  10889. /// This function applies a very simplistic algorithm for NRVO: if every return
  10890. /// statement in the scope of a variable has the same NRVO candidate, that
  10891. /// candidate is an NRVO variable.
  10892. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  10893. ReturnStmt **Returns = Scope->Returns.data();
  10894. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  10895. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  10896. if (!NRVOCandidate->isNRVOVariable())
  10897. Returns[I]->setNRVOCandidate(nullptr);
  10898. }
  10899. }
  10900. }
  10901. bool Sema::canDelayFunctionBody(const Declarator &D) {
  10902. // We can't delay parsing the body of a constexpr function template (yet).
  10903. if (D.getDeclSpec().isConstexprSpecified())
  10904. return false;
  10905. // We can't delay parsing the body of a function template with a deduced
  10906. // return type (yet).
  10907. if (D.getDeclSpec().hasAutoTypeSpec()) {
  10908. // If the placeholder introduces a non-deduced trailing return type,
  10909. // we can still delay parsing it.
  10910. if (D.getNumTypeObjects()) {
  10911. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  10912. if (Outer.Kind == DeclaratorChunk::Function &&
  10913. Outer.Fun.hasTrailingReturnType()) {
  10914. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  10915. return Ty.isNull() || !Ty->isUndeducedType();
  10916. }
  10917. }
  10918. return false;
  10919. }
  10920. return true;
  10921. }
  10922. bool Sema::canSkipFunctionBody(Decl *D) {
  10923. // We cannot skip the body of a function (or function template) which is
  10924. // constexpr, since we may need to evaluate its body in order to parse the
  10925. // rest of the file.
  10926. // We cannot skip the body of a function with an undeduced return type,
  10927. // because any callers of that function need to know the type.
  10928. if (const FunctionDecl *FD = D->getAsFunction())
  10929. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  10930. return false;
  10931. return Consumer.shouldSkipFunctionBody(D);
  10932. }
  10933. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  10934. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  10935. FD->setHasSkippedBody();
  10936. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  10937. MD->setHasSkippedBody();
  10938. return Decl;
  10939. }
  10940. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  10941. return ActOnFinishFunctionBody(D, BodyArg, false);
  10942. }
  10943. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  10944. bool IsInstantiation) {
  10945. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  10946. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10947. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  10948. if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
  10949. CheckCompletedCoroutineBody(FD, Body);
  10950. if (FD) {
  10951. FD->setBody(Body);
  10952. FD->setWillHaveBody(false);
  10953. if (getLangOpts().CPlusPlus14) {
  10954. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  10955. FD->getReturnType()->isUndeducedType()) {
  10956. // If the function has a deduced result type but contains no 'return'
  10957. // statements, the result type as written must be exactly 'auto', and
  10958. // the deduced result type is 'void'.
  10959. if (!FD->getReturnType()->getAs<AutoType>()) {
  10960. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  10961. << FD->getReturnType();
  10962. FD->setInvalidDecl();
  10963. } else {
  10964. // Substitute 'void' for the 'auto' in the type.
  10965. TypeLoc ResultType = getReturnTypeLoc(FD);
  10966. Context.adjustDeducedFunctionResultType(
  10967. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  10968. }
  10969. }
  10970. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  10971. // In C++11, we don't use 'auto' deduction rules for lambda call
  10972. // operators because we don't support return type deduction.
  10973. auto *LSI = getCurLambda();
  10974. if (LSI->HasImplicitReturnType) {
  10975. deduceClosureReturnType(*LSI);
  10976. // C++11 [expr.prim.lambda]p4:
  10977. // [...] if there are no return statements in the compound-statement
  10978. // [the deduced type is] the type void
  10979. QualType RetType =
  10980. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  10981. // Update the return type to the deduced type.
  10982. const FunctionProtoType *Proto =
  10983. FD->getType()->getAs<FunctionProtoType>();
  10984. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  10985. Proto->getExtProtoInfo()));
  10986. }
  10987. }
  10988. // If the function implicitly returns zero (like 'main') or is naked,
  10989. // don't complain about missing return statements.
  10990. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  10991. WP.disableCheckFallThrough();
  10992. // MSVC permits the use of pure specifier (=0) on function definition,
  10993. // defined at class scope, warn about this non-standard construct.
  10994. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  10995. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  10996. if (!FD->isInvalidDecl()) {
  10997. // Don't diagnose unused parameters of defaulted or deleted functions.
  10998. if (!FD->isDeleted() && !FD->isDefaulted())
  10999. DiagnoseUnusedParameters(FD->parameters());
  11000. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  11001. FD->getReturnType(), FD);
  11002. // If this is a structor, we need a vtable.
  11003. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  11004. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  11005. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  11006. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  11007. // Try to apply the named return value optimization. We have to check
  11008. // if we can do this here because lambdas keep return statements around
  11009. // to deduce an implicit return type.
  11010. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  11011. !FD->isDependentContext())
  11012. computeNRVO(Body, getCurFunction());
  11013. }
  11014. // GNU warning -Wmissing-prototypes:
  11015. // Warn if a global function is defined without a previous
  11016. // prototype declaration. This warning is issued even if the
  11017. // definition itself provides a prototype. The aim is to detect
  11018. // global functions that fail to be declared in header files.
  11019. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  11020. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  11021. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  11022. if (PossibleZeroParamPrototype) {
  11023. // We found a declaration that is not a prototype,
  11024. // but that could be a zero-parameter prototype
  11025. if (TypeSourceInfo *TI =
  11026. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  11027. TypeLoc TL = TI->getTypeLoc();
  11028. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  11029. Diag(PossibleZeroParamPrototype->getLocation(),
  11030. diag::note_declaration_not_a_prototype)
  11031. << PossibleZeroParamPrototype
  11032. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  11033. }
  11034. }
  11035. // GNU warning -Wstrict-prototypes
  11036. // Warn if K&R function is defined without a previous declaration.
  11037. // This warning is issued only if the definition itself does not provide
  11038. // a prototype. Only K&R definitions do not provide a prototype.
  11039. // An empty list in a function declarator that is part of a definition
  11040. // of that function specifies that the function has no parameters
  11041. // (C99 6.7.5.3p14)
  11042. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  11043. !LangOpts.CPlusPlus) {
  11044. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  11045. TypeLoc TL = TI->getTypeLoc();
  11046. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  11047. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  11048. }
  11049. }
  11050. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  11051. const CXXMethodDecl *KeyFunction;
  11052. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  11053. MD->isVirtual() &&
  11054. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  11055. MD == KeyFunction->getCanonicalDecl()) {
  11056. // Update the key-function state if necessary for this ABI.
  11057. if (FD->isInlined() &&
  11058. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  11059. Context.setNonKeyFunction(MD);
  11060. // If the newly-chosen key function is already defined, then we
  11061. // need to mark the vtable as used retroactively.
  11062. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  11063. const FunctionDecl *Definition;
  11064. if (KeyFunction && KeyFunction->isDefined(Definition))
  11065. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  11066. } else {
  11067. // We just defined they key function; mark the vtable as used.
  11068. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  11069. }
  11070. }
  11071. }
  11072. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  11073. "Function parsing confused");
  11074. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  11075. assert(MD == getCurMethodDecl() && "Method parsing confused");
  11076. MD->setBody(Body);
  11077. if (!MD->isInvalidDecl()) {
  11078. DiagnoseUnusedParameters(MD->parameters());
  11079. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11080. MD->getReturnType(), MD);
  11081. if (Body)
  11082. computeNRVO(Body, getCurFunction());
  11083. }
  11084. if (getCurFunction()->ObjCShouldCallSuper) {
  11085. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  11086. << MD->getSelector().getAsString();
  11087. getCurFunction()->ObjCShouldCallSuper = false;
  11088. }
  11089. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11090. const ObjCMethodDecl *InitMethod = nullptr;
  11091. bool isDesignated =
  11092. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11093. assert(isDesignated && InitMethod);
  11094. (void)isDesignated;
  11095. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11096. auto IFace = MD->getClassInterface();
  11097. if (!IFace)
  11098. return false;
  11099. auto SuperD = IFace->getSuperClass();
  11100. if (!SuperD)
  11101. return false;
  11102. return SuperD->getIdentifier() ==
  11103. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  11104. };
  11105. // Don't issue this warning for unavailable inits or direct subclasses
  11106. // of NSObject.
  11107. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  11108. Diag(MD->getLocation(),
  11109. diag::warn_objc_designated_init_missing_super_call);
  11110. Diag(InitMethod->getLocation(),
  11111. diag::note_objc_designated_init_marked_here);
  11112. }
  11113. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  11114. }
  11115. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  11116. // Don't issue this warning for unavaialable inits.
  11117. if (!MD->isUnavailable())
  11118. Diag(MD->getLocation(),
  11119. diag::warn_objc_secondary_init_missing_init_call);
  11120. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  11121. }
  11122. } else {
  11123. return nullptr;
  11124. }
  11125. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11126. DiagnoseUnguardedAvailabilityViolations(dcl);
  11127. assert(!getCurFunction()->ObjCShouldCallSuper &&
  11128. "This should only be set for ObjC methods, which should have been "
  11129. "handled in the block above.");
  11130. // Verify and clean out per-function state.
  11131. if (Body && (!FD || !FD->isDefaulted())) {
  11132. // C++ constructors that have function-try-blocks can't have return
  11133. // statements in the handlers of that block. (C++ [except.handle]p14)
  11134. // Verify this.
  11135. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  11136. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  11137. // Verify that gotos and switch cases don't jump into scopes illegally.
  11138. if (getCurFunction()->NeedsScopeChecking() &&
  11139. !PP.isCodeCompletionEnabled())
  11140. DiagnoseInvalidJumps(Body);
  11141. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  11142. if (!Destructor->getParent()->isDependentType())
  11143. CheckDestructor(Destructor);
  11144. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11145. Destructor->getParent());
  11146. }
  11147. // If any errors have occurred, clear out any temporaries that may have
  11148. // been leftover. This ensures that these temporaries won't be picked up for
  11149. // deletion in some later function.
  11150. if (getDiagnostics().hasErrorOccurred() ||
  11151. getDiagnostics().getSuppressAllDiagnostics()) {
  11152. DiscardCleanupsInEvaluationContext();
  11153. }
  11154. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  11155. !isa<FunctionTemplateDecl>(dcl)) {
  11156. // Since the body is valid, issue any analysis-based warnings that are
  11157. // enabled.
  11158. ActivePolicy = &WP;
  11159. }
  11160. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  11161. (!CheckConstexprFunctionDecl(FD) ||
  11162. !CheckConstexprFunctionBody(FD, Body)))
  11163. FD->setInvalidDecl();
  11164. if (FD && FD->hasAttr<NakedAttr>()) {
  11165. for (const Stmt *S : Body->children()) {
  11166. // Allow local register variables without initializer as they don't
  11167. // require prologue.
  11168. bool RegisterVariables = false;
  11169. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  11170. for (const auto *Decl : DS->decls()) {
  11171. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  11172. RegisterVariables =
  11173. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  11174. if (!RegisterVariables)
  11175. break;
  11176. }
  11177. }
  11178. }
  11179. if (RegisterVariables)
  11180. continue;
  11181. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  11182. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  11183. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  11184. FD->setInvalidDecl();
  11185. break;
  11186. }
  11187. }
  11188. }
  11189. assert(ExprCleanupObjects.size() ==
  11190. ExprEvalContexts.back().NumCleanupObjects &&
  11191. "Leftover temporaries in function");
  11192. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  11193. assert(MaybeODRUseExprs.empty() &&
  11194. "Leftover expressions for odr-use checking");
  11195. }
  11196. if (!IsInstantiation)
  11197. PopDeclContext();
  11198. PopFunctionScopeInfo(ActivePolicy, dcl);
  11199. // If any errors have occurred, clear out any temporaries that may have
  11200. // been leftover. This ensures that these temporaries won't be picked up for
  11201. // deletion in some later function.
  11202. if (getDiagnostics().hasErrorOccurred()) {
  11203. DiscardCleanupsInEvaluationContext();
  11204. }
  11205. return dcl;
  11206. }
  11207. /// When we finish delayed parsing of an attribute, we must attach it to the
  11208. /// relevant Decl.
  11209. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  11210. ParsedAttributes &Attrs) {
  11211. // Always attach attributes to the underlying decl.
  11212. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  11213. D = TD->getTemplatedDecl();
  11214. ProcessDeclAttributeList(S, D, Attrs.getList());
  11215. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  11216. if (Method->isStatic())
  11217. checkThisInStaticMemberFunctionAttributes(Method);
  11218. }
  11219. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  11220. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  11221. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  11222. IdentifierInfo &II, Scope *S) {
  11223. Scope *BlockScope = S;
  11224. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  11225. BlockScope = BlockScope->getParent();
  11226. // Before we produce a declaration for an implicitly defined
  11227. // function, see whether there was a locally-scoped declaration of
  11228. // this name as a function or variable. If so, use that
  11229. // (non-visible) declaration, and complain about it.
  11230. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  11231. if (ExternCPrev) {
  11232. // We still need to inject the function into the enclosing block scope so
  11233. // that later (non-call) uses can see it.
  11234. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  11235. // C89 footnote 38:
  11236. // If in fact it is not defined as having type "function returning int",
  11237. // the behavior is undefined.
  11238. if (!isa<FunctionDecl>(ExternCPrev) ||
  11239. !Context.typesAreCompatible(
  11240. cast<FunctionDecl>(ExternCPrev)->getType(),
  11241. Context.getFunctionNoProtoType(Context.IntTy))) {
  11242. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  11243. << ExternCPrev << !getLangOpts().C99;
  11244. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  11245. return ExternCPrev;
  11246. }
  11247. }
  11248. // Extension in C99. Legal in C90, but warn about it.
  11249. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  11250. unsigned diag_id;
  11251. if (II.getName().startswith("__builtin_"))
  11252. diag_id = diag::warn_builtin_unknown;
  11253. else if (getLangOpts().C99 || getLangOpts().OpenCL)
  11254. diag_id = diag::ext_implicit_function_decl;
  11255. else
  11256. diag_id = diag::warn_implicit_function_decl;
  11257. Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
  11258. // If we found a prior declaration of this function, don't bother building
  11259. // another one. We've already pushed that one into scope, so there's nothing
  11260. // more to do.
  11261. if (ExternCPrev)
  11262. return ExternCPrev;
  11263. // Because typo correction is expensive, only do it if the implicit
  11264. // function declaration is going to be treated as an error.
  11265. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  11266. TypoCorrection Corrected;
  11267. if (S &&
  11268. (Corrected = CorrectTypo(
  11269. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  11270. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  11271. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  11272. /*ErrorRecovery*/false);
  11273. }
  11274. // Set a Declarator for the implicit definition: int foo();
  11275. const char *Dummy;
  11276. AttributeFactory attrFactory;
  11277. DeclSpec DS(attrFactory);
  11278. unsigned DiagID;
  11279. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  11280. Context.getPrintingPolicy());
  11281. (void)Error; // Silence warning.
  11282. assert(!Error && "Error setting up implicit decl!");
  11283. SourceLocation NoLoc;
  11284. Declarator D(DS, Declarator::BlockContext);
  11285. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  11286. /*IsAmbiguous=*/false,
  11287. /*LParenLoc=*/NoLoc,
  11288. /*Params=*/nullptr,
  11289. /*NumParams=*/0,
  11290. /*EllipsisLoc=*/NoLoc,
  11291. /*RParenLoc=*/NoLoc,
  11292. /*TypeQuals=*/0,
  11293. /*RefQualifierIsLvalueRef=*/true,
  11294. /*RefQualifierLoc=*/NoLoc,
  11295. /*ConstQualifierLoc=*/NoLoc,
  11296. /*VolatileQualifierLoc=*/NoLoc,
  11297. /*RestrictQualifierLoc=*/NoLoc,
  11298. /*MutableLoc=*/NoLoc,
  11299. EST_None,
  11300. /*ESpecRange=*/SourceRange(),
  11301. /*Exceptions=*/nullptr,
  11302. /*ExceptionRanges=*/nullptr,
  11303. /*NumExceptions=*/0,
  11304. /*NoexceptExpr=*/nullptr,
  11305. /*ExceptionSpecTokens=*/nullptr,
  11306. /*DeclsInPrototype=*/None,
  11307. Loc, Loc, D),
  11308. DS.getAttributes(),
  11309. SourceLocation());
  11310. D.SetIdentifier(&II, Loc);
  11311. // Insert this function into the enclosing block scope.
  11312. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  11313. FD->setImplicit();
  11314. AddKnownFunctionAttributes(FD);
  11315. return FD;
  11316. }
  11317. /// \brief Adds any function attributes that we know a priori based on
  11318. /// the declaration of this function.
  11319. ///
  11320. /// These attributes can apply both to implicitly-declared builtins
  11321. /// (like __builtin___printf_chk) or to library-declared functions
  11322. /// like NSLog or printf.
  11323. ///
  11324. /// We need to check for duplicate attributes both here and where user-written
  11325. /// attributes are applied to declarations.
  11326. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  11327. if (FD->isInvalidDecl())
  11328. return;
  11329. // If this is a built-in function, map its builtin attributes to
  11330. // actual attributes.
  11331. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11332. // Handle printf-formatting attributes.
  11333. unsigned FormatIdx;
  11334. bool HasVAListArg;
  11335. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  11336. if (!FD->hasAttr<FormatAttr>()) {
  11337. const char *fmt = "printf";
  11338. unsigned int NumParams = FD->getNumParams();
  11339. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  11340. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  11341. fmt = "NSString";
  11342. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11343. &Context.Idents.get(fmt),
  11344. FormatIdx+1,
  11345. HasVAListArg ? 0 : FormatIdx+2,
  11346. FD->getLocation()));
  11347. }
  11348. }
  11349. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  11350. HasVAListArg)) {
  11351. if (!FD->hasAttr<FormatAttr>())
  11352. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11353. &Context.Idents.get("scanf"),
  11354. FormatIdx+1,
  11355. HasVAListArg ? 0 : FormatIdx+2,
  11356. FD->getLocation()));
  11357. }
  11358. // Mark const if we don't care about errno and that is the only
  11359. // thing preventing the function from being const. This allows
  11360. // IRgen to use LLVM intrinsics for such functions.
  11361. if (!getLangOpts().MathErrno &&
  11362. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  11363. if (!FD->hasAttr<ConstAttr>())
  11364. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11365. }
  11366. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  11367. !FD->hasAttr<ReturnsTwiceAttr>())
  11368. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  11369. FD->getLocation()));
  11370. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  11371. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11372. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  11373. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  11374. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  11375. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11376. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  11377. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  11378. // Add the appropriate attribute, depending on the CUDA compilation mode
  11379. // and which target the builtin belongs to. For example, during host
  11380. // compilation, aux builtins are __device__, while the rest are __host__.
  11381. if (getLangOpts().CUDAIsDevice !=
  11382. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  11383. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  11384. else
  11385. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  11386. }
  11387. }
  11388. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  11389. // throw, add an implicit nothrow attribute to any extern "C" function we come
  11390. // across.
  11391. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  11392. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  11393. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  11394. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  11395. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11396. }
  11397. IdentifierInfo *Name = FD->getIdentifier();
  11398. if (!Name)
  11399. return;
  11400. if ((!getLangOpts().CPlusPlus &&
  11401. FD->getDeclContext()->isTranslationUnit()) ||
  11402. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  11403. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  11404. LinkageSpecDecl::lang_c)) {
  11405. // Okay: this could be a libc/libm/Objective-C function we know
  11406. // about.
  11407. } else
  11408. return;
  11409. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  11410. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  11411. // target-specific builtins, perhaps?
  11412. if (!FD->hasAttr<FormatAttr>())
  11413. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11414. &Context.Idents.get("printf"), 2,
  11415. Name->isStr("vasprintf") ? 0 : 3,
  11416. FD->getLocation()));
  11417. }
  11418. if (Name->isStr("__CFStringMakeConstantString")) {
  11419. // We already have a __builtin___CFStringMakeConstantString,
  11420. // but builds that use -fno-constant-cfstrings don't go through that.
  11421. if (!FD->hasAttr<FormatArgAttr>())
  11422. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  11423. FD->getLocation()));
  11424. }
  11425. }
  11426. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  11427. TypeSourceInfo *TInfo) {
  11428. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  11429. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  11430. if (!TInfo) {
  11431. assert(D.isInvalidType() && "no declarator info for valid type");
  11432. TInfo = Context.getTrivialTypeSourceInfo(T);
  11433. }
  11434. // Scope manipulation handled by caller.
  11435. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  11436. D.getLocStart(),
  11437. D.getIdentifierLoc(),
  11438. D.getIdentifier(),
  11439. TInfo);
  11440. // Bail out immediately if we have an invalid declaration.
  11441. if (D.isInvalidType()) {
  11442. NewTD->setInvalidDecl();
  11443. return NewTD;
  11444. }
  11445. if (D.getDeclSpec().isModulePrivateSpecified()) {
  11446. if (CurContext->isFunctionOrMethod())
  11447. Diag(NewTD->getLocation(), diag::err_module_private_local)
  11448. << 2 << NewTD->getDeclName()
  11449. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11450. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11451. else
  11452. NewTD->setModulePrivate();
  11453. }
  11454. // C++ [dcl.typedef]p8:
  11455. // If the typedef declaration defines an unnamed class (or
  11456. // enum), the first typedef-name declared by the declaration
  11457. // to be that class type (or enum type) is used to denote the
  11458. // class type (or enum type) for linkage purposes only.
  11459. // We need to check whether the type was declared in the declaration.
  11460. switch (D.getDeclSpec().getTypeSpecType()) {
  11461. case TST_enum:
  11462. case TST_struct:
  11463. case TST_interface:
  11464. case TST_union:
  11465. case TST_class: {
  11466. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  11467. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  11468. break;
  11469. }
  11470. default:
  11471. break;
  11472. }
  11473. return NewTD;
  11474. }
  11475. /// \brief Check that this is a valid underlying type for an enum declaration.
  11476. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  11477. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  11478. QualType T = TI->getType();
  11479. if (T->isDependentType())
  11480. return false;
  11481. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  11482. if (BT->isInteger())
  11483. return false;
  11484. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  11485. return true;
  11486. }
  11487. /// Check whether this is a valid redeclaration of a previous enumeration.
  11488. /// \return true if the redeclaration was invalid.
  11489. bool Sema::CheckEnumRedeclaration(
  11490. SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
  11491. bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
  11492. bool IsFixed = !EnumUnderlyingTy.isNull();
  11493. if (IsScoped != Prev->isScoped()) {
  11494. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  11495. << Prev->isScoped();
  11496. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11497. return true;
  11498. }
  11499. if (IsFixed && Prev->isFixed()) {
  11500. if (!EnumUnderlyingTy->isDependentType() &&
  11501. !Prev->getIntegerType()->isDependentType() &&
  11502. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  11503. Prev->getIntegerType())) {
  11504. // TODO: Highlight the underlying type of the redeclaration.
  11505. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  11506. << EnumUnderlyingTy << Prev->getIntegerType();
  11507. Diag(Prev->getLocation(), diag::note_previous_declaration)
  11508. << Prev->getIntegerTypeRange();
  11509. return true;
  11510. }
  11511. } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
  11512. ;
  11513. } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
  11514. ;
  11515. } else if (IsFixed != Prev->isFixed()) {
  11516. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  11517. << Prev->isFixed();
  11518. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11519. return true;
  11520. }
  11521. return false;
  11522. }
  11523. /// \brief Get diagnostic %select index for tag kind for
  11524. /// redeclaration diagnostic message.
  11525. /// WARNING: Indexes apply to particular diagnostics only!
  11526. ///
  11527. /// \returns diagnostic %select index.
  11528. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  11529. switch (Tag) {
  11530. case TTK_Struct: return 0;
  11531. case TTK_Interface: return 1;
  11532. case TTK_Class: return 2;
  11533. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  11534. }
  11535. }
  11536. /// \brief Determine if tag kind is a class-key compatible with
  11537. /// class for redeclaration (class, struct, or __interface).
  11538. ///
  11539. /// \returns true iff the tag kind is compatible.
  11540. static bool isClassCompatTagKind(TagTypeKind Tag)
  11541. {
  11542. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  11543. }
  11544. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  11545. TagTypeKind TTK) {
  11546. if (isa<TypedefDecl>(PrevDecl))
  11547. return NTK_Typedef;
  11548. else if (isa<TypeAliasDecl>(PrevDecl))
  11549. return NTK_TypeAlias;
  11550. else if (isa<ClassTemplateDecl>(PrevDecl))
  11551. return NTK_Template;
  11552. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  11553. return NTK_TypeAliasTemplate;
  11554. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  11555. return NTK_TemplateTemplateArgument;
  11556. switch (TTK) {
  11557. case TTK_Struct:
  11558. case TTK_Interface:
  11559. case TTK_Class:
  11560. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  11561. case TTK_Union:
  11562. return NTK_NonUnion;
  11563. case TTK_Enum:
  11564. return NTK_NonEnum;
  11565. }
  11566. llvm_unreachable("invalid TTK");
  11567. }
  11568. /// \brief Determine whether a tag with a given kind is acceptable
  11569. /// as a redeclaration of the given tag declaration.
  11570. ///
  11571. /// \returns true if the new tag kind is acceptable, false otherwise.
  11572. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  11573. TagTypeKind NewTag, bool isDefinition,
  11574. SourceLocation NewTagLoc,
  11575. const IdentifierInfo *Name) {
  11576. // C++ [dcl.type.elab]p3:
  11577. // The class-key or enum keyword present in the
  11578. // elaborated-type-specifier shall agree in kind with the
  11579. // declaration to which the name in the elaborated-type-specifier
  11580. // refers. This rule also applies to the form of
  11581. // elaborated-type-specifier that declares a class-name or
  11582. // friend class since it can be construed as referring to the
  11583. // definition of the class. Thus, in any
  11584. // elaborated-type-specifier, the enum keyword shall be used to
  11585. // refer to an enumeration (7.2), the union class-key shall be
  11586. // used to refer to a union (clause 9), and either the class or
  11587. // struct class-key shall be used to refer to a class (clause 9)
  11588. // declared using the class or struct class-key.
  11589. TagTypeKind OldTag = Previous->getTagKind();
  11590. if (!isDefinition || !isClassCompatTagKind(NewTag))
  11591. if (OldTag == NewTag)
  11592. return true;
  11593. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  11594. // Warn about the struct/class tag mismatch.
  11595. bool isTemplate = false;
  11596. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  11597. isTemplate = Record->getDescribedClassTemplate();
  11598. if (inTemplateInstantiation()) {
  11599. // In a template instantiation, do not offer fix-its for tag mismatches
  11600. // since they usually mess up the template instead of fixing the problem.
  11601. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11602. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11603. << getRedeclDiagFromTagKind(OldTag);
  11604. return true;
  11605. }
  11606. if (isDefinition) {
  11607. // On definitions, check previous tags and issue a fix-it for each
  11608. // one that doesn't match the current tag.
  11609. if (Previous->getDefinition()) {
  11610. // Don't suggest fix-its for redefinitions.
  11611. return true;
  11612. }
  11613. bool previousMismatch = false;
  11614. for (auto I : Previous->redecls()) {
  11615. if (I->getTagKind() != NewTag) {
  11616. if (!previousMismatch) {
  11617. previousMismatch = true;
  11618. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  11619. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11620. << getRedeclDiagFromTagKind(I->getTagKind());
  11621. }
  11622. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  11623. << getRedeclDiagFromTagKind(NewTag)
  11624. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  11625. TypeWithKeyword::getTagTypeKindName(NewTag));
  11626. }
  11627. }
  11628. return true;
  11629. }
  11630. // Check for a previous definition. If current tag and definition
  11631. // are same type, do nothing. If no definition, but disagree with
  11632. // with previous tag type, give a warning, but no fix-it.
  11633. const TagDecl *Redecl = Previous->getDefinition() ?
  11634. Previous->getDefinition() : Previous;
  11635. if (Redecl->getTagKind() == NewTag) {
  11636. return true;
  11637. }
  11638. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11639. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11640. << getRedeclDiagFromTagKind(OldTag);
  11641. Diag(Redecl->getLocation(), diag::note_previous_use);
  11642. // If there is a previous definition, suggest a fix-it.
  11643. if (Previous->getDefinition()) {
  11644. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  11645. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  11646. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  11647. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  11648. }
  11649. return true;
  11650. }
  11651. return false;
  11652. }
  11653. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  11654. /// from an outer enclosing namespace or file scope inside a friend declaration.
  11655. /// This should provide the commented out code in the following snippet:
  11656. /// namespace N {
  11657. /// struct X;
  11658. /// namespace M {
  11659. /// struct Y { friend struct /*N::*/ X; };
  11660. /// }
  11661. /// }
  11662. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  11663. SourceLocation NameLoc) {
  11664. // While the decl is in a namespace, do repeated lookup of that name and see
  11665. // if we get the same namespace back. If we do not, continue until
  11666. // translation unit scope, at which point we have a fully qualified NNS.
  11667. SmallVector<IdentifierInfo *, 4> Namespaces;
  11668. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11669. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  11670. // This tag should be declared in a namespace, which can only be enclosed by
  11671. // other namespaces. Bail if there's an anonymous namespace in the chain.
  11672. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  11673. if (!Namespace || Namespace->isAnonymousNamespace())
  11674. return FixItHint();
  11675. IdentifierInfo *II = Namespace->getIdentifier();
  11676. Namespaces.push_back(II);
  11677. NamedDecl *Lookup = SemaRef.LookupSingleName(
  11678. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  11679. if (Lookup == Namespace)
  11680. break;
  11681. }
  11682. // Once we have all the namespaces, reverse them to go outermost first, and
  11683. // build an NNS.
  11684. SmallString<64> Insertion;
  11685. llvm::raw_svector_ostream OS(Insertion);
  11686. if (DC->isTranslationUnit())
  11687. OS << "::";
  11688. std::reverse(Namespaces.begin(), Namespaces.end());
  11689. for (auto *II : Namespaces)
  11690. OS << II->getName() << "::";
  11691. return FixItHint::CreateInsertion(NameLoc, Insertion);
  11692. }
  11693. /// \brief Determine whether a tag originally declared in context \p OldDC can
  11694. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  11695. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  11696. /// using-declaration).
  11697. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  11698. DeclContext *NewDC) {
  11699. OldDC = OldDC->getRedeclContext();
  11700. NewDC = NewDC->getRedeclContext();
  11701. if (OldDC->Equals(NewDC))
  11702. return true;
  11703. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  11704. // encloses the other).
  11705. if (S.getLangOpts().MSVCCompat &&
  11706. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  11707. return true;
  11708. return false;
  11709. }
  11710. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  11711. /// former case, Name will be non-null. In the later case, Name will be null.
  11712. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  11713. /// reference/declaration/definition of a tag.
  11714. ///
  11715. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  11716. /// trailing-type-specifier) other than one in an alias-declaration.
  11717. ///
  11718. /// \param SkipBody If non-null, will be set to indicate if the caller should
  11719. /// skip the definition of this tag and treat it as if it were a declaration.
  11720. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  11721. SourceLocation KWLoc, CXXScopeSpec &SS,
  11722. IdentifierInfo *Name, SourceLocation NameLoc,
  11723. AttributeList *Attr, AccessSpecifier AS,
  11724. SourceLocation ModulePrivateLoc,
  11725. MultiTemplateParamsArg TemplateParameterLists,
  11726. bool &OwnedDecl, bool &IsDependent,
  11727. SourceLocation ScopedEnumKWLoc,
  11728. bool ScopedEnumUsesClassTag,
  11729. TypeResult UnderlyingType,
  11730. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  11731. SkipBodyInfo *SkipBody) {
  11732. // If this is not a definition, it must have a name.
  11733. IdentifierInfo *OrigName = Name;
  11734. assert((Name != nullptr || TUK == TUK_Definition) &&
  11735. "Nameless record must be a definition!");
  11736. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  11737. OwnedDecl = false;
  11738. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  11739. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  11740. // FIXME: Check member specializations more carefully.
  11741. bool isMemberSpecialization = false;
  11742. bool Invalid = false;
  11743. // We only need to do this matching if we have template parameters
  11744. // or a scope specifier, which also conveniently avoids this work
  11745. // for non-C++ cases.
  11746. if (TemplateParameterLists.size() > 0 ||
  11747. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  11748. if (TemplateParameterList *TemplateParams =
  11749. MatchTemplateParametersToScopeSpecifier(
  11750. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  11751. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  11752. if (Kind == TTK_Enum) {
  11753. Diag(KWLoc, diag::err_enum_template);
  11754. return nullptr;
  11755. }
  11756. if (TemplateParams->size() > 0) {
  11757. // This is a declaration or definition of a class template (which may
  11758. // be a member of another template).
  11759. if (Invalid)
  11760. return nullptr;
  11761. OwnedDecl = false;
  11762. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  11763. SS, Name, NameLoc, Attr,
  11764. TemplateParams, AS,
  11765. ModulePrivateLoc,
  11766. /*FriendLoc*/SourceLocation(),
  11767. TemplateParameterLists.size()-1,
  11768. TemplateParameterLists.data(),
  11769. SkipBody);
  11770. return Result.get();
  11771. } else {
  11772. // The "template<>" header is extraneous.
  11773. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  11774. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  11775. isMemberSpecialization = true;
  11776. }
  11777. }
  11778. }
  11779. // Figure out the underlying type if this a enum declaration. We need to do
  11780. // this early, because it's needed to detect if this is an incompatible
  11781. // redeclaration.
  11782. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  11783. bool EnumUnderlyingIsImplicit = false;
  11784. if (Kind == TTK_Enum) {
  11785. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  11786. // No underlying type explicitly specified, or we failed to parse the
  11787. // type, default to int.
  11788. EnumUnderlying = Context.IntTy.getTypePtr();
  11789. else if (UnderlyingType.get()) {
  11790. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  11791. // integral type; any cv-qualification is ignored.
  11792. TypeSourceInfo *TI = nullptr;
  11793. GetTypeFromParser(UnderlyingType.get(), &TI);
  11794. EnumUnderlying = TI;
  11795. if (CheckEnumUnderlyingType(TI))
  11796. // Recover by falling back to int.
  11797. EnumUnderlying = Context.IntTy.getTypePtr();
  11798. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  11799. UPPC_FixedUnderlyingType))
  11800. EnumUnderlying = Context.IntTy.getTypePtr();
  11801. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11802. if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
  11803. // Microsoft enums are always of int type.
  11804. EnumUnderlying = Context.IntTy.getTypePtr();
  11805. EnumUnderlyingIsImplicit = true;
  11806. }
  11807. }
  11808. }
  11809. DeclContext *SearchDC = CurContext;
  11810. DeclContext *DC = CurContext;
  11811. bool isStdBadAlloc = false;
  11812. bool isStdAlignValT = false;
  11813. RedeclarationKind Redecl = forRedeclarationInCurContext();
  11814. if (TUK == TUK_Friend || TUK == TUK_Reference)
  11815. Redecl = NotForRedeclaration;
  11816. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  11817. /// implemented asks for structural equivalence checking, the returned decl
  11818. /// here is passed back to the parser, allowing the tag body to be parsed.
  11819. auto createTagFromNewDecl = [&]() -> TagDecl * {
  11820. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  11821. // If there is an identifier, use the location of the identifier as the
  11822. // location of the decl, otherwise use the location of the struct/union
  11823. // keyword.
  11824. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  11825. TagDecl *New = nullptr;
  11826. if (Kind == TTK_Enum) {
  11827. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  11828. ScopedEnum, ScopedEnumUsesClassTag,
  11829. !EnumUnderlying.isNull());
  11830. // If this is an undefined enum, bail.
  11831. if (TUK != TUK_Definition && !Invalid)
  11832. return nullptr;
  11833. if (EnumUnderlying) {
  11834. EnumDecl *ED = cast<EnumDecl>(New);
  11835. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  11836. ED->setIntegerTypeSourceInfo(TI);
  11837. else
  11838. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  11839. ED->setPromotionType(ED->getIntegerType());
  11840. }
  11841. } else { // struct/union
  11842. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  11843. nullptr);
  11844. }
  11845. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  11846. // Add alignment attributes if necessary; these attributes are checked
  11847. // when the ASTContext lays out the structure.
  11848. //
  11849. // It is important for implementing the correct semantics that this
  11850. // happen here (in ActOnTag). The #pragma pack stack is
  11851. // maintained as a result of parser callbacks which can occur at
  11852. // many points during the parsing of a struct declaration (because
  11853. // the #pragma tokens are effectively skipped over during the
  11854. // parsing of the struct).
  11855. if (TUK == TUK_Definition) {
  11856. AddAlignmentAttributesForRecord(RD);
  11857. AddMsStructLayoutForRecord(RD);
  11858. }
  11859. }
  11860. New->setLexicalDeclContext(CurContext);
  11861. return New;
  11862. };
  11863. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  11864. if (Name && SS.isNotEmpty()) {
  11865. // We have a nested-name tag ('struct foo::bar').
  11866. // Check for invalid 'foo::'.
  11867. if (SS.isInvalid()) {
  11868. Name = nullptr;
  11869. goto CreateNewDecl;
  11870. }
  11871. // If this is a friend or a reference to a class in a dependent
  11872. // context, don't try to make a decl for it.
  11873. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  11874. DC = computeDeclContext(SS, false);
  11875. if (!DC) {
  11876. IsDependent = true;
  11877. return nullptr;
  11878. }
  11879. } else {
  11880. DC = computeDeclContext(SS, true);
  11881. if (!DC) {
  11882. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  11883. << SS.getRange();
  11884. return nullptr;
  11885. }
  11886. }
  11887. if (RequireCompleteDeclContext(SS, DC))
  11888. return nullptr;
  11889. SearchDC = DC;
  11890. // Look-up name inside 'foo::'.
  11891. LookupQualifiedName(Previous, DC);
  11892. if (Previous.isAmbiguous())
  11893. return nullptr;
  11894. if (Previous.empty()) {
  11895. // Name lookup did not find anything. However, if the
  11896. // nested-name-specifier refers to the current instantiation,
  11897. // and that current instantiation has any dependent base
  11898. // classes, we might find something at instantiation time: treat
  11899. // this as a dependent elaborated-type-specifier.
  11900. // But this only makes any sense for reference-like lookups.
  11901. if (Previous.wasNotFoundInCurrentInstantiation() &&
  11902. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  11903. IsDependent = true;
  11904. return nullptr;
  11905. }
  11906. // A tag 'foo::bar' must already exist.
  11907. Diag(NameLoc, diag::err_not_tag_in_scope)
  11908. << Kind << Name << DC << SS.getRange();
  11909. Name = nullptr;
  11910. Invalid = true;
  11911. goto CreateNewDecl;
  11912. }
  11913. } else if (Name) {
  11914. // C++14 [class.mem]p14:
  11915. // If T is the name of a class, then each of the following shall have a
  11916. // name different from T:
  11917. // -- every member of class T that is itself a type
  11918. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  11919. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  11920. return nullptr;
  11921. // If this is a named struct, check to see if there was a previous forward
  11922. // declaration or definition.
  11923. // FIXME: We're looking into outer scopes here, even when we
  11924. // shouldn't be. Doing so can result in ambiguities that we
  11925. // shouldn't be diagnosing.
  11926. LookupName(Previous, S);
  11927. // When declaring or defining a tag, ignore ambiguities introduced
  11928. // by types using'ed into this scope.
  11929. if (Previous.isAmbiguous() &&
  11930. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  11931. LookupResult::Filter F = Previous.makeFilter();
  11932. while (F.hasNext()) {
  11933. NamedDecl *ND = F.next();
  11934. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  11935. SearchDC->getRedeclContext()))
  11936. F.erase();
  11937. }
  11938. F.done();
  11939. }
  11940. // C++11 [namespace.memdef]p3:
  11941. // If the name in a friend declaration is neither qualified nor
  11942. // a template-id and the declaration is a function or an
  11943. // elaborated-type-specifier, the lookup to determine whether
  11944. // the entity has been previously declared shall not consider
  11945. // any scopes outside the innermost enclosing namespace.
  11946. //
  11947. // MSVC doesn't implement the above rule for types, so a friend tag
  11948. // declaration may be a redeclaration of a type declared in an enclosing
  11949. // scope. They do implement this rule for friend functions.
  11950. //
  11951. // Does it matter that this should be by scope instead of by
  11952. // semantic context?
  11953. if (!Previous.empty() && TUK == TUK_Friend) {
  11954. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  11955. LookupResult::Filter F = Previous.makeFilter();
  11956. bool FriendSawTagOutsideEnclosingNamespace = false;
  11957. while (F.hasNext()) {
  11958. NamedDecl *ND = F.next();
  11959. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11960. if (DC->isFileContext() &&
  11961. !EnclosingNS->Encloses(ND->getDeclContext())) {
  11962. if (getLangOpts().MSVCCompat)
  11963. FriendSawTagOutsideEnclosingNamespace = true;
  11964. else
  11965. F.erase();
  11966. }
  11967. }
  11968. F.done();
  11969. // Diagnose this MSVC extension in the easy case where lookup would have
  11970. // unambiguously found something outside the enclosing namespace.
  11971. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  11972. NamedDecl *ND = Previous.getFoundDecl();
  11973. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  11974. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  11975. }
  11976. }
  11977. // Note: there used to be some attempt at recovery here.
  11978. if (Previous.isAmbiguous())
  11979. return nullptr;
  11980. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  11981. // FIXME: This makes sure that we ignore the contexts associated
  11982. // with C structs, unions, and enums when looking for a matching
  11983. // tag declaration or definition. See the similar lookup tweak
  11984. // in Sema::LookupName; is there a better way to deal with this?
  11985. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  11986. SearchDC = SearchDC->getParent();
  11987. }
  11988. }
  11989. if (Previous.isSingleResult() &&
  11990. Previous.getFoundDecl()->isTemplateParameter()) {
  11991. // Maybe we will complain about the shadowed template parameter.
  11992. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  11993. // Just pretend that we didn't see the previous declaration.
  11994. Previous.clear();
  11995. }
  11996. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  11997. DC->Equals(getStdNamespace())) {
  11998. if (Name->isStr("bad_alloc")) {
  11999. // This is a declaration of or a reference to "std::bad_alloc".
  12000. isStdBadAlloc = true;
  12001. // If std::bad_alloc has been implicitly declared (but made invisible to
  12002. // name lookup), fill in this implicit declaration as the previous
  12003. // declaration, so that the declarations get chained appropriately.
  12004. if (Previous.empty() && StdBadAlloc)
  12005. Previous.addDecl(getStdBadAlloc());
  12006. } else if (Name->isStr("align_val_t")) {
  12007. isStdAlignValT = true;
  12008. if (Previous.empty() && StdAlignValT)
  12009. Previous.addDecl(getStdAlignValT());
  12010. }
  12011. }
  12012. // If we didn't find a previous declaration, and this is a reference
  12013. // (or friend reference), move to the correct scope. In C++, we
  12014. // also need to do a redeclaration lookup there, just in case
  12015. // there's a shadow friend decl.
  12016. if (Name && Previous.empty() &&
  12017. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  12018. if (Invalid) goto CreateNewDecl;
  12019. assert(SS.isEmpty());
  12020. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  12021. // C++ [basic.scope.pdecl]p5:
  12022. // -- for an elaborated-type-specifier of the form
  12023. //
  12024. // class-key identifier
  12025. //
  12026. // if the elaborated-type-specifier is used in the
  12027. // decl-specifier-seq or parameter-declaration-clause of a
  12028. // function defined in namespace scope, the identifier is
  12029. // declared as a class-name in the namespace that contains
  12030. // the declaration; otherwise, except as a friend
  12031. // declaration, the identifier is declared in the smallest
  12032. // non-class, non-function-prototype scope that contains the
  12033. // declaration.
  12034. //
  12035. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  12036. // C structs and unions.
  12037. //
  12038. // It is an error in C++ to declare (rather than define) an enum
  12039. // type, including via an elaborated type specifier. We'll
  12040. // diagnose that later; for now, declare the enum in the same
  12041. // scope as we would have picked for any other tag type.
  12042. //
  12043. // GNU C also supports this behavior as part of its incomplete
  12044. // enum types extension, while GNU C++ does not.
  12045. //
  12046. // Find the context where we'll be declaring the tag.
  12047. // FIXME: We would like to maintain the current DeclContext as the
  12048. // lexical context,
  12049. SearchDC = getTagInjectionContext(SearchDC);
  12050. // Find the scope where we'll be declaring the tag.
  12051. S = getTagInjectionScope(S, getLangOpts());
  12052. } else {
  12053. assert(TUK == TUK_Friend);
  12054. // C++ [namespace.memdef]p3:
  12055. // If a friend declaration in a non-local class first declares a
  12056. // class or function, the friend class or function is a member of
  12057. // the innermost enclosing namespace.
  12058. SearchDC = SearchDC->getEnclosingNamespaceContext();
  12059. }
  12060. // In C++, we need to do a redeclaration lookup to properly
  12061. // diagnose some problems.
  12062. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  12063. // hidden declaration so that we don't get ambiguity errors when using a
  12064. // type declared by an elaborated-type-specifier. In C that is not correct
  12065. // and we should instead merge compatible types found by lookup.
  12066. if (getLangOpts().CPlusPlus) {
  12067. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12068. LookupQualifiedName(Previous, SearchDC);
  12069. } else {
  12070. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12071. LookupName(Previous, S);
  12072. }
  12073. }
  12074. // If we have a known previous declaration to use, then use it.
  12075. if (Previous.empty() && SkipBody && SkipBody->Previous)
  12076. Previous.addDecl(SkipBody->Previous);
  12077. if (!Previous.empty()) {
  12078. NamedDecl *PrevDecl = Previous.getFoundDecl();
  12079. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  12080. // It's okay to have a tag decl in the same scope as a typedef
  12081. // which hides a tag decl in the same scope. Finding this
  12082. // insanity with a redeclaration lookup can only actually happen
  12083. // in C++.
  12084. //
  12085. // This is also okay for elaborated-type-specifiers, which is
  12086. // technically forbidden by the current standard but which is
  12087. // okay according to the likely resolution of an open issue;
  12088. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  12089. if (getLangOpts().CPlusPlus) {
  12090. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12091. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  12092. TagDecl *Tag = TT->getDecl();
  12093. if (Tag->getDeclName() == Name &&
  12094. Tag->getDeclContext()->getRedeclContext()
  12095. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  12096. PrevDecl = Tag;
  12097. Previous.clear();
  12098. Previous.addDecl(Tag);
  12099. Previous.resolveKind();
  12100. }
  12101. }
  12102. }
  12103. }
  12104. // If this is a redeclaration of a using shadow declaration, it must
  12105. // declare a tag in the same context. In MSVC mode, we allow a
  12106. // redefinition if either context is within the other.
  12107. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  12108. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  12109. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  12110. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  12111. !(OldTag && isAcceptableTagRedeclContext(
  12112. *this, OldTag->getDeclContext(), SearchDC))) {
  12113. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  12114. Diag(Shadow->getTargetDecl()->getLocation(),
  12115. diag::note_using_decl_target);
  12116. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  12117. << 0;
  12118. // Recover by ignoring the old declaration.
  12119. Previous.clear();
  12120. goto CreateNewDecl;
  12121. }
  12122. }
  12123. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  12124. // If this is a use of a previous tag, or if the tag is already declared
  12125. // in the same scope (so that the definition/declaration completes or
  12126. // rementions the tag), reuse the decl.
  12127. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  12128. isDeclInScope(DirectPrevDecl, SearchDC, S,
  12129. SS.isNotEmpty() || isMemberSpecialization)) {
  12130. // Make sure that this wasn't declared as an enum and now used as a
  12131. // struct or something similar.
  12132. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  12133. TUK == TUK_Definition, KWLoc,
  12134. Name)) {
  12135. bool SafeToContinue
  12136. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  12137. Kind != TTK_Enum);
  12138. if (SafeToContinue)
  12139. Diag(KWLoc, diag::err_use_with_wrong_tag)
  12140. << Name
  12141. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  12142. PrevTagDecl->getKindName());
  12143. else
  12144. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  12145. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  12146. if (SafeToContinue)
  12147. Kind = PrevTagDecl->getTagKind();
  12148. else {
  12149. // Recover by making this an anonymous redefinition.
  12150. Name = nullptr;
  12151. Previous.clear();
  12152. Invalid = true;
  12153. }
  12154. }
  12155. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  12156. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  12157. // If this is an elaborated-type-specifier for a scoped enumeration,
  12158. // the 'class' keyword is not necessary and not permitted.
  12159. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12160. if (ScopedEnum)
  12161. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  12162. << PrevEnum->isScoped()
  12163. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  12164. return PrevTagDecl;
  12165. }
  12166. QualType EnumUnderlyingTy;
  12167. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12168. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  12169. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  12170. EnumUnderlyingTy = QualType(T, 0);
  12171. // All conflicts with previous declarations are recovered by
  12172. // returning the previous declaration, unless this is a definition,
  12173. // in which case we want the caller to bail out.
  12174. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  12175. ScopedEnum, EnumUnderlyingTy,
  12176. EnumUnderlyingIsImplicit, PrevEnum))
  12177. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  12178. }
  12179. // C++11 [class.mem]p1:
  12180. // A member shall not be declared twice in the member-specification,
  12181. // except that a nested class or member class template can be declared
  12182. // and then later defined.
  12183. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  12184. S->isDeclScope(PrevDecl)) {
  12185. Diag(NameLoc, diag::ext_member_redeclared);
  12186. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  12187. }
  12188. if (!Invalid) {
  12189. // If this is a use, just return the declaration we found, unless
  12190. // we have attributes.
  12191. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12192. if (Attr) {
  12193. // FIXME: Diagnose these attributes. For now, we create a new
  12194. // declaration to hold them.
  12195. } else if (TUK == TUK_Reference &&
  12196. (PrevTagDecl->getFriendObjectKind() ==
  12197. Decl::FOK_Undeclared ||
  12198. PrevDecl->getOwningModule() != getCurrentModule()) &&
  12199. SS.isEmpty()) {
  12200. // This declaration is a reference to an existing entity, but
  12201. // has different visibility from that entity: it either makes
  12202. // a friend visible or it makes a type visible in a new module.
  12203. // In either case, create a new declaration. We only do this if
  12204. // the declaration would have meant the same thing if no prior
  12205. // declaration were found, that is, if it was found in the same
  12206. // scope where we would have injected a declaration.
  12207. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  12208. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  12209. return PrevTagDecl;
  12210. // This is in the injected scope, create a new declaration in
  12211. // that scope.
  12212. S = getTagInjectionScope(S, getLangOpts());
  12213. } else {
  12214. return PrevTagDecl;
  12215. }
  12216. }
  12217. // Diagnose attempts to redefine a tag.
  12218. if (TUK == TUK_Definition) {
  12219. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  12220. // If we're defining a specialization and the previous definition
  12221. // is from an implicit instantiation, don't emit an error
  12222. // here; we'll catch this in the general case below.
  12223. bool IsExplicitSpecializationAfterInstantiation = false;
  12224. if (isMemberSpecialization) {
  12225. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  12226. IsExplicitSpecializationAfterInstantiation =
  12227. RD->getTemplateSpecializationKind() !=
  12228. TSK_ExplicitSpecialization;
  12229. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  12230. IsExplicitSpecializationAfterInstantiation =
  12231. ED->getTemplateSpecializationKind() !=
  12232. TSK_ExplicitSpecialization;
  12233. }
  12234. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  12235. // not keep more that one definition around (merge them). However,
  12236. // ensure the decl passes the structural compatibility check in
  12237. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  12238. NamedDecl *Hidden = nullptr;
  12239. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  12240. // There is a definition of this tag, but it is not visible. We
  12241. // explicitly make use of C++'s one definition rule here, and
  12242. // assume that this definition is identical to the hidden one
  12243. // we already have. Make the existing definition visible and
  12244. // use it in place of this one.
  12245. if (!getLangOpts().CPlusPlus) {
  12246. // Postpone making the old definition visible until after we
  12247. // complete parsing the new one and do the structural
  12248. // comparison.
  12249. SkipBody->CheckSameAsPrevious = true;
  12250. SkipBody->New = createTagFromNewDecl();
  12251. SkipBody->Previous = Hidden;
  12252. } else {
  12253. SkipBody->ShouldSkip = true;
  12254. makeMergedDefinitionVisible(Hidden);
  12255. }
  12256. return Def;
  12257. } else if (!IsExplicitSpecializationAfterInstantiation) {
  12258. // A redeclaration in function prototype scope in C isn't
  12259. // visible elsewhere, so merely issue a warning.
  12260. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  12261. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  12262. else
  12263. Diag(NameLoc, diag::err_redefinition) << Name;
  12264. notePreviousDefinition(Def,
  12265. NameLoc.isValid() ? NameLoc : KWLoc);
  12266. // If this is a redefinition, recover by making this
  12267. // struct be anonymous, which will make any later
  12268. // references get the previous definition.
  12269. Name = nullptr;
  12270. Previous.clear();
  12271. Invalid = true;
  12272. }
  12273. } else {
  12274. // If the type is currently being defined, complain
  12275. // about a nested redefinition.
  12276. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  12277. if (TD->isBeingDefined()) {
  12278. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  12279. Diag(PrevTagDecl->getLocation(),
  12280. diag::note_previous_definition);
  12281. Name = nullptr;
  12282. Previous.clear();
  12283. Invalid = true;
  12284. }
  12285. }
  12286. // Okay, this is definition of a previously declared or referenced
  12287. // tag. We're going to create a new Decl for it.
  12288. }
  12289. // Okay, we're going to make a redeclaration. If this is some kind
  12290. // of reference, make sure we build the redeclaration in the same DC
  12291. // as the original, and ignore the current access specifier.
  12292. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12293. SearchDC = PrevTagDecl->getDeclContext();
  12294. AS = AS_none;
  12295. }
  12296. }
  12297. // If we get here we have (another) forward declaration or we
  12298. // have a definition. Just create a new decl.
  12299. } else {
  12300. // If we get here, this is a definition of a new tag type in a nested
  12301. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  12302. // new decl/type. We set PrevDecl to NULL so that the entities
  12303. // have distinct types.
  12304. Previous.clear();
  12305. }
  12306. // If we get here, we're going to create a new Decl. If PrevDecl
  12307. // is non-NULL, it's a definition of the tag declared by
  12308. // PrevDecl. If it's NULL, we have a new definition.
  12309. // Otherwise, PrevDecl is not a tag, but was found with tag
  12310. // lookup. This is only actually possible in C++, where a few
  12311. // things like templates still live in the tag namespace.
  12312. } else {
  12313. // Use a better diagnostic if an elaborated-type-specifier
  12314. // found the wrong kind of type on the first
  12315. // (non-redeclaration) lookup.
  12316. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  12317. !Previous.isForRedeclaration()) {
  12318. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12319. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  12320. << Kind;
  12321. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  12322. Invalid = true;
  12323. // Otherwise, only diagnose if the declaration is in scope.
  12324. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  12325. SS.isNotEmpty() || isMemberSpecialization)) {
  12326. // do nothing
  12327. // Diagnose implicit declarations introduced by elaborated types.
  12328. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12329. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12330. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  12331. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12332. Invalid = true;
  12333. // Otherwise it's a declaration. Call out a particularly common
  12334. // case here.
  12335. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12336. unsigned Kind = 0;
  12337. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  12338. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  12339. << Name << Kind << TND->getUnderlyingType();
  12340. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12341. Invalid = true;
  12342. // Otherwise, diagnose.
  12343. } else {
  12344. // The tag name clashes with something else in the target scope,
  12345. // issue an error and recover by making this tag be anonymous.
  12346. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  12347. notePreviousDefinition(PrevDecl, NameLoc);
  12348. Name = nullptr;
  12349. Invalid = true;
  12350. }
  12351. // The existing declaration isn't relevant to us; we're in a
  12352. // new scope, so clear out the previous declaration.
  12353. Previous.clear();
  12354. }
  12355. }
  12356. CreateNewDecl:
  12357. TagDecl *PrevDecl = nullptr;
  12358. if (Previous.isSingleResult())
  12359. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  12360. // If there is an identifier, use the location of the identifier as the
  12361. // location of the decl, otherwise use the location of the struct/union
  12362. // keyword.
  12363. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12364. // Otherwise, create a new declaration. If there is a previous
  12365. // declaration of the same entity, the two will be linked via
  12366. // PrevDecl.
  12367. TagDecl *New;
  12368. bool IsForwardReference = false;
  12369. if (Kind == TTK_Enum) {
  12370. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12371. // enum X { A, B, C } D; D should chain to X.
  12372. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  12373. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  12374. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  12375. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  12376. StdAlignValT = cast<EnumDecl>(New);
  12377. // If this is an undefined enum, warn.
  12378. if (TUK != TUK_Definition && !Invalid) {
  12379. TagDecl *Def;
  12380. if (!EnumUnderlyingIsImplicit &&
  12381. (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  12382. cast<EnumDecl>(New)->isFixed()) {
  12383. // C++0x: 7.2p2: opaque-enum-declaration.
  12384. // Conflicts are diagnosed above. Do nothing.
  12385. }
  12386. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  12387. Diag(Loc, diag::ext_forward_ref_enum_def)
  12388. << New;
  12389. Diag(Def->getLocation(), diag::note_previous_definition);
  12390. } else {
  12391. unsigned DiagID = diag::ext_forward_ref_enum;
  12392. if (getLangOpts().MSVCCompat)
  12393. DiagID = diag::ext_ms_forward_ref_enum;
  12394. else if (getLangOpts().CPlusPlus)
  12395. DiagID = diag::err_forward_ref_enum;
  12396. Diag(Loc, DiagID);
  12397. // If this is a forward-declared reference to an enumeration, make a
  12398. // note of it; we won't actually be introducing the declaration into
  12399. // the declaration context.
  12400. if (TUK == TUK_Reference)
  12401. IsForwardReference = true;
  12402. }
  12403. }
  12404. if (EnumUnderlying) {
  12405. EnumDecl *ED = cast<EnumDecl>(New);
  12406. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12407. ED->setIntegerTypeSourceInfo(TI);
  12408. else
  12409. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  12410. ED->setPromotionType(ED->getIntegerType());
  12411. }
  12412. } else {
  12413. // struct/union/class
  12414. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12415. // struct X { int A; } D; D should chain to X.
  12416. if (getLangOpts().CPlusPlus) {
  12417. // FIXME: Look for a way to use RecordDecl for simple structs.
  12418. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12419. cast_or_null<CXXRecordDecl>(PrevDecl));
  12420. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  12421. StdBadAlloc = cast<CXXRecordDecl>(New);
  12422. } else
  12423. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12424. cast_or_null<RecordDecl>(PrevDecl));
  12425. }
  12426. // C++11 [dcl.type]p3:
  12427. // A type-specifier-seq shall not define a class or enumeration [...].
  12428. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  12429. TUK == TUK_Definition) {
  12430. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  12431. << Context.getTagDeclType(New);
  12432. Invalid = true;
  12433. }
  12434. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  12435. DC->getDeclKind() == Decl::Enum) {
  12436. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  12437. << Context.getTagDeclType(New);
  12438. Invalid = true;
  12439. }
  12440. // Maybe add qualifier info.
  12441. if (SS.isNotEmpty()) {
  12442. if (SS.isSet()) {
  12443. // If this is either a declaration or a definition, check the
  12444. // nested-name-specifier against the current context. We don't do this
  12445. // for explicit specializations, because they have similar checking
  12446. // (with more specific diagnostics) in the call to
  12447. // CheckMemberSpecialization, below.
  12448. if (!isMemberSpecialization &&
  12449. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  12450. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  12451. Invalid = true;
  12452. New->setQualifierInfo(SS.getWithLocInContext(Context));
  12453. if (TemplateParameterLists.size() > 0) {
  12454. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  12455. }
  12456. }
  12457. else
  12458. Invalid = true;
  12459. }
  12460. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12461. // Add alignment attributes if necessary; these attributes are checked when
  12462. // the ASTContext lays out the structure.
  12463. //
  12464. // It is important for implementing the correct semantics that this
  12465. // happen here (in ActOnTag). The #pragma pack stack is
  12466. // maintained as a result of parser callbacks which can occur at
  12467. // many points during the parsing of a struct declaration (because
  12468. // the #pragma tokens are effectively skipped over during the
  12469. // parsing of the struct).
  12470. if (TUK == TUK_Definition) {
  12471. AddAlignmentAttributesForRecord(RD);
  12472. AddMsStructLayoutForRecord(RD);
  12473. }
  12474. }
  12475. if (ModulePrivateLoc.isValid()) {
  12476. if (isMemberSpecialization)
  12477. Diag(New->getLocation(), diag::err_module_private_specialization)
  12478. << 2
  12479. << FixItHint::CreateRemoval(ModulePrivateLoc);
  12480. // __module_private__ does not apply to local classes. However, we only
  12481. // diagnose this as an error when the declaration specifiers are
  12482. // freestanding. Here, we just ignore the __module_private__.
  12483. else if (!SearchDC->isFunctionOrMethod())
  12484. New->setModulePrivate();
  12485. }
  12486. // If this is a specialization of a member class (of a class template),
  12487. // check the specialization.
  12488. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  12489. Invalid = true;
  12490. // If we're declaring or defining a tag in function prototype scope in C,
  12491. // note that this type can only be used within the function and add it to
  12492. // the list of decls to inject into the function definition scope.
  12493. if ((Name || Kind == TTK_Enum) &&
  12494. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  12495. if (getLangOpts().CPlusPlus) {
  12496. // C++ [dcl.fct]p6:
  12497. // Types shall not be defined in return or parameter types.
  12498. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  12499. Diag(Loc, diag::err_type_defined_in_param_type)
  12500. << Name;
  12501. Invalid = true;
  12502. }
  12503. } else if (!PrevDecl) {
  12504. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  12505. }
  12506. }
  12507. if (Invalid)
  12508. New->setInvalidDecl();
  12509. // Set the lexical context. If the tag has a C++ scope specifier, the
  12510. // lexical context will be different from the semantic context.
  12511. New->setLexicalDeclContext(CurContext);
  12512. // Mark this as a friend decl if applicable.
  12513. // In Microsoft mode, a friend declaration also acts as a forward
  12514. // declaration so we always pass true to setObjectOfFriendDecl to make
  12515. // the tag name visible.
  12516. if (TUK == TUK_Friend)
  12517. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  12518. // Set the access specifier.
  12519. if (!Invalid && SearchDC->isRecord())
  12520. SetMemberAccessSpecifier(New, PrevDecl, AS);
  12521. if (PrevDecl)
  12522. CheckRedeclarationModuleOwnership(New, PrevDecl);
  12523. if (TUK == TUK_Definition)
  12524. New->startDefinition();
  12525. if (Attr)
  12526. ProcessDeclAttributeList(S, New, Attr);
  12527. AddPragmaAttributes(S, New);
  12528. // If this has an identifier, add it to the scope stack.
  12529. if (TUK == TUK_Friend) {
  12530. // We might be replacing an existing declaration in the lookup tables;
  12531. // if so, borrow its access specifier.
  12532. if (PrevDecl)
  12533. New->setAccess(PrevDecl->getAccess());
  12534. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  12535. DC->makeDeclVisibleInContext(New);
  12536. if (Name) // can be null along some error paths
  12537. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12538. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  12539. } else if (Name) {
  12540. S = getNonFieldDeclScope(S);
  12541. PushOnScopeChains(New, S, !IsForwardReference);
  12542. if (IsForwardReference)
  12543. SearchDC->makeDeclVisibleInContext(New);
  12544. } else {
  12545. CurContext->addDecl(New);
  12546. }
  12547. // If this is the C FILE type, notify the AST context.
  12548. if (IdentifierInfo *II = New->getIdentifier())
  12549. if (!New->isInvalidDecl() &&
  12550. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  12551. II->isStr("FILE"))
  12552. Context.setFILEDecl(New);
  12553. if (PrevDecl)
  12554. mergeDeclAttributes(New, PrevDecl);
  12555. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12556. // record.
  12557. AddPushedVisibilityAttribute(New);
  12558. if (isMemberSpecialization && !New->isInvalidDecl())
  12559. CompleteMemberSpecialization(New, Previous);
  12560. OwnedDecl = true;
  12561. // In C++, don't return an invalid declaration. We can't recover well from
  12562. // the cases where we make the type anonymous.
  12563. if (Invalid && getLangOpts().CPlusPlus) {
  12564. if (New->isBeingDefined())
  12565. if (auto RD = dyn_cast<RecordDecl>(New))
  12566. RD->completeDefinition();
  12567. return nullptr;
  12568. } else {
  12569. return New;
  12570. }
  12571. }
  12572. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  12573. AdjustDeclIfTemplate(TagD);
  12574. TagDecl *Tag = cast<TagDecl>(TagD);
  12575. // Enter the tag context.
  12576. PushDeclContext(S, Tag);
  12577. ActOnDocumentableDecl(TagD);
  12578. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12579. // record.
  12580. AddPushedVisibilityAttribute(Tag);
  12581. }
  12582. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  12583. SkipBodyInfo &SkipBody) {
  12584. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  12585. return false;
  12586. // Make the previous decl visible.
  12587. makeMergedDefinitionVisible(SkipBody.Previous);
  12588. return true;
  12589. }
  12590. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  12591. assert(isa<ObjCContainerDecl>(IDecl) &&
  12592. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  12593. DeclContext *OCD = cast<DeclContext>(IDecl);
  12594. assert(getContainingDC(OCD) == CurContext &&
  12595. "The next DeclContext should be lexically contained in the current one.");
  12596. CurContext = OCD;
  12597. return IDecl;
  12598. }
  12599. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  12600. SourceLocation FinalLoc,
  12601. bool IsFinalSpelledSealed,
  12602. SourceLocation LBraceLoc) {
  12603. AdjustDeclIfTemplate(TagD);
  12604. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  12605. FieldCollector->StartClass();
  12606. if (!Record->getIdentifier())
  12607. return;
  12608. if (FinalLoc.isValid())
  12609. Record->addAttr(new (Context)
  12610. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  12611. // C++ [class]p2:
  12612. // [...] The class-name is also inserted into the scope of the
  12613. // class itself; this is known as the injected-class-name. For
  12614. // purposes of access checking, the injected-class-name is treated
  12615. // as if it were a public member name.
  12616. CXXRecordDecl *InjectedClassName
  12617. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  12618. Record->getLocStart(), Record->getLocation(),
  12619. Record->getIdentifier(),
  12620. /*PrevDecl=*/nullptr,
  12621. /*DelayTypeCreation=*/true);
  12622. Context.getTypeDeclType(InjectedClassName, Record);
  12623. InjectedClassName->setImplicit();
  12624. InjectedClassName->setAccess(AS_public);
  12625. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  12626. InjectedClassName->setDescribedClassTemplate(Template);
  12627. PushOnScopeChains(InjectedClassName, S);
  12628. assert(InjectedClassName->isInjectedClassName() &&
  12629. "Broken injected-class-name");
  12630. }
  12631. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  12632. SourceRange BraceRange) {
  12633. AdjustDeclIfTemplate(TagD);
  12634. TagDecl *Tag = cast<TagDecl>(TagD);
  12635. Tag->setBraceRange(BraceRange);
  12636. // Make sure we "complete" the definition even it is invalid.
  12637. if (Tag->isBeingDefined()) {
  12638. assert(Tag->isInvalidDecl() && "We should already have completed it");
  12639. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12640. RD->completeDefinition();
  12641. }
  12642. if (isa<CXXRecordDecl>(Tag)) {
  12643. FieldCollector->FinishClass();
  12644. }
  12645. // Exit this scope of this tag's definition.
  12646. PopDeclContext();
  12647. if (getCurLexicalContext()->isObjCContainer() &&
  12648. Tag->getDeclContext()->isFileContext())
  12649. Tag->setTopLevelDeclInObjCContainer();
  12650. // Notify the consumer that we've defined a tag.
  12651. if (!Tag->isInvalidDecl())
  12652. Consumer.HandleTagDeclDefinition(Tag);
  12653. }
  12654. void Sema::ActOnObjCContainerFinishDefinition() {
  12655. // Exit this scope of this interface definition.
  12656. PopDeclContext();
  12657. }
  12658. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  12659. assert(DC == CurContext && "Mismatch of container contexts");
  12660. OriginalLexicalContext = DC;
  12661. ActOnObjCContainerFinishDefinition();
  12662. }
  12663. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  12664. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  12665. OriginalLexicalContext = nullptr;
  12666. }
  12667. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  12668. AdjustDeclIfTemplate(TagD);
  12669. TagDecl *Tag = cast<TagDecl>(TagD);
  12670. Tag->setInvalidDecl();
  12671. // Make sure we "complete" the definition even it is invalid.
  12672. if (Tag->isBeingDefined()) {
  12673. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12674. RD->completeDefinition();
  12675. }
  12676. // We're undoing ActOnTagStartDefinition here, not
  12677. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  12678. // the FieldCollector.
  12679. PopDeclContext();
  12680. }
  12681. // Note that FieldName may be null for anonymous bitfields.
  12682. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  12683. IdentifierInfo *FieldName,
  12684. QualType FieldTy, bool IsMsStruct,
  12685. Expr *BitWidth, bool *ZeroWidth) {
  12686. // Default to true; that shouldn't confuse checks for emptiness
  12687. if (ZeroWidth)
  12688. *ZeroWidth = true;
  12689. // C99 6.7.2.1p4 - verify the field type.
  12690. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  12691. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  12692. // Handle incomplete types with specific error.
  12693. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  12694. return ExprError();
  12695. if (FieldName)
  12696. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  12697. << FieldName << FieldTy << BitWidth->getSourceRange();
  12698. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  12699. << FieldTy << BitWidth->getSourceRange();
  12700. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  12701. UPPC_BitFieldWidth))
  12702. return ExprError();
  12703. // If the bit-width is type- or value-dependent, don't try to check
  12704. // it now.
  12705. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  12706. return BitWidth;
  12707. llvm::APSInt Value;
  12708. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  12709. if (ICE.isInvalid())
  12710. return ICE;
  12711. BitWidth = ICE.get();
  12712. if (Value != 0 && ZeroWidth)
  12713. *ZeroWidth = false;
  12714. // Zero-width bitfield is ok for anonymous field.
  12715. if (Value == 0 && FieldName)
  12716. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  12717. if (Value.isSigned() && Value.isNegative()) {
  12718. if (FieldName)
  12719. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  12720. << FieldName << Value.toString(10);
  12721. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  12722. << Value.toString(10);
  12723. }
  12724. if (!FieldTy->isDependentType()) {
  12725. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  12726. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  12727. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  12728. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  12729. // ABI.
  12730. bool CStdConstraintViolation =
  12731. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  12732. bool MSBitfieldViolation =
  12733. Value.ugt(TypeStorageSize) &&
  12734. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  12735. if (CStdConstraintViolation || MSBitfieldViolation) {
  12736. unsigned DiagWidth =
  12737. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  12738. if (FieldName)
  12739. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  12740. << FieldName << (unsigned)Value.getZExtValue()
  12741. << !CStdConstraintViolation << DiagWidth;
  12742. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  12743. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  12744. << DiagWidth;
  12745. }
  12746. // Warn on types where the user might conceivably expect to get all
  12747. // specified bits as value bits: that's all integral types other than
  12748. // 'bool'.
  12749. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  12750. if (FieldName)
  12751. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  12752. << FieldName << (unsigned)Value.getZExtValue()
  12753. << (unsigned)TypeWidth;
  12754. else
  12755. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  12756. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  12757. }
  12758. }
  12759. return BitWidth;
  12760. }
  12761. /// ActOnField - Each field of a C struct/union is passed into this in order
  12762. /// to create a FieldDecl object for it.
  12763. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  12764. Declarator &D, Expr *BitfieldWidth) {
  12765. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  12766. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  12767. /*InitStyle=*/ICIS_NoInit, AS_public);
  12768. return Res;
  12769. }
  12770. /// HandleField - Analyze a field of a C struct or a C++ data member.
  12771. ///
  12772. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  12773. SourceLocation DeclStart,
  12774. Declarator &D, Expr *BitWidth,
  12775. InClassInitStyle InitStyle,
  12776. AccessSpecifier AS) {
  12777. if (D.isDecompositionDeclarator()) {
  12778. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  12779. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  12780. << Decomp.getSourceRange();
  12781. return nullptr;
  12782. }
  12783. IdentifierInfo *II = D.getIdentifier();
  12784. SourceLocation Loc = DeclStart;
  12785. if (II) Loc = D.getIdentifierLoc();
  12786. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12787. QualType T = TInfo->getType();
  12788. if (getLangOpts().CPlusPlus) {
  12789. CheckExtraCXXDefaultArguments(D);
  12790. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12791. UPPC_DataMemberType)) {
  12792. D.setInvalidType();
  12793. T = Context.IntTy;
  12794. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  12795. }
  12796. }
  12797. // TR 18037 does not allow fields to be declared with address spaces.
  12798. if (T.getQualifiers().hasAddressSpace() ||
  12799. T->isDependentAddressSpaceType() ||
  12800. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  12801. Diag(Loc, diag::err_field_with_address_space);
  12802. D.setInvalidType();
  12803. }
  12804. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  12805. // used as structure or union field: image, sampler, event or block types.
  12806. if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
  12807. T->isSamplerT() || T->isBlockPointerType())) {
  12808. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  12809. D.setInvalidType();
  12810. }
  12811. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  12812. if (D.getDeclSpec().isInlineSpecified())
  12813. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  12814. << getLangOpts().CPlusPlus1z;
  12815. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  12816. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  12817. diag::err_invalid_thread)
  12818. << DeclSpec::getSpecifierName(TSCS);
  12819. // Check to see if this name was declared as a member previously
  12820. NamedDecl *PrevDecl = nullptr;
  12821. LookupResult Previous(*this, II, Loc, LookupMemberName,
  12822. ForVisibleRedeclaration);
  12823. LookupName(Previous, S);
  12824. switch (Previous.getResultKind()) {
  12825. case LookupResult::Found:
  12826. case LookupResult::FoundUnresolvedValue:
  12827. PrevDecl = Previous.getAsSingle<NamedDecl>();
  12828. break;
  12829. case LookupResult::FoundOverloaded:
  12830. PrevDecl = Previous.getRepresentativeDecl();
  12831. break;
  12832. case LookupResult::NotFound:
  12833. case LookupResult::NotFoundInCurrentInstantiation:
  12834. case LookupResult::Ambiguous:
  12835. break;
  12836. }
  12837. Previous.suppressDiagnostics();
  12838. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12839. // Maybe we will complain about the shadowed template parameter.
  12840. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12841. // Just pretend that we didn't see the previous declaration.
  12842. PrevDecl = nullptr;
  12843. }
  12844. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  12845. PrevDecl = nullptr;
  12846. bool Mutable
  12847. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  12848. SourceLocation TSSL = D.getLocStart();
  12849. FieldDecl *NewFD
  12850. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  12851. TSSL, AS, PrevDecl, &D);
  12852. if (NewFD->isInvalidDecl())
  12853. Record->setInvalidDecl();
  12854. if (D.getDeclSpec().isModulePrivateSpecified())
  12855. NewFD->setModulePrivate();
  12856. if (NewFD->isInvalidDecl() && PrevDecl) {
  12857. // Don't introduce NewFD into scope; there's already something
  12858. // with the same name in the same scope.
  12859. } else if (II) {
  12860. PushOnScopeChains(NewFD, S);
  12861. } else
  12862. Record->addDecl(NewFD);
  12863. return NewFD;
  12864. }
  12865. /// \brief Build a new FieldDecl and check its well-formedness.
  12866. ///
  12867. /// This routine builds a new FieldDecl given the fields name, type,
  12868. /// record, etc. \p PrevDecl should refer to any previous declaration
  12869. /// with the same name and in the same scope as the field to be
  12870. /// created.
  12871. ///
  12872. /// \returns a new FieldDecl.
  12873. ///
  12874. /// \todo The Declarator argument is a hack. It will be removed once
  12875. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  12876. TypeSourceInfo *TInfo,
  12877. RecordDecl *Record, SourceLocation Loc,
  12878. bool Mutable, Expr *BitWidth,
  12879. InClassInitStyle InitStyle,
  12880. SourceLocation TSSL,
  12881. AccessSpecifier AS, NamedDecl *PrevDecl,
  12882. Declarator *D) {
  12883. IdentifierInfo *II = Name.getAsIdentifierInfo();
  12884. bool InvalidDecl = false;
  12885. if (D) InvalidDecl = D->isInvalidType();
  12886. // If we receive a broken type, recover by assuming 'int' and
  12887. // marking this declaration as invalid.
  12888. if (T.isNull()) {
  12889. InvalidDecl = true;
  12890. T = Context.IntTy;
  12891. }
  12892. QualType EltTy = Context.getBaseElementType(T);
  12893. if (!EltTy->isDependentType()) {
  12894. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  12895. // Fields of incomplete type force their record to be invalid.
  12896. Record->setInvalidDecl();
  12897. InvalidDecl = true;
  12898. } else {
  12899. NamedDecl *Def;
  12900. EltTy->isIncompleteType(&Def);
  12901. if (Def && Def->isInvalidDecl()) {
  12902. Record->setInvalidDecl();
  12903. InvalidDecl = true;
  12904. }
  12905. }
  12906. }
  12907. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  12908. if (BitWidth && getLangOpts().OpenCL) {
  12909. Diag(Loc, diag::err_opencl_bitfields);
  12910. InvalidDecl = true;
  12911. }
  12912. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  12913. // than a variably modified type.
  12914. if (!InvalidDecl && T->isVariablyModifiedType()) {
  12915. bool SizeIsNegative;
  12916. llvm::APSInt Oversized;
  12917. TypeSourceInfo *FixedTInfo =
  12918. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  12919. SizeIsNegative,
  12920. Oversized);
  12921. if (FixedTInfo) {
  12922. Diag(Loc, diag::warn_illegal_constant_array_size);
  12923. TInfo = FixedTInfo;
  12924. T = FixedTInfo->getType();
  12925. } else {
  12926. if (SizeIsNegative)
  12927. Diag(Loc, diag::err_typecheck_negative_array_size);
  12928. else if (Oversized.getBoolValue())
  12929. Diag(Loc, diag::err_array_too_large)
  12930. << Oversized.toString(10);
  12931. else
  12932. Diag(Loc, diag::err_typecheck_field_variable_size);
  12933. InvalidDecl = true;
  12934. }
  12935. }
  12936. // Fields can not have abstract class types
  12937. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  12938. diag::err_abstract_type_in_decl,
  12939. AbstractFieldType))
  12940. InvalidDecl = true;
  12941. bool ZeroWidth = false;
  12942. if (InvalidDecl)
  12943. BitWidth = nullptr;
  12944. // If this is declared as a bit-field, check the bit-field.
  12945. if (BitWidth) {
  12946. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  12947. &ZeroWidth).get();
  12948. if (!BitWidth) {
  12949. InvalidDecl = true;
  12950. BitWidth = nullptr;
  12951. ZeroWidth = false;
  12952. }
  12953. }
  12954. // Check that 'mutable' is consistent with the type of the declaration.
  12955. if (!InvalidDecl && Mutable) {
  12956. unsigned DiagID = 0;
  12957. if (T->isReferenceType())
  12958. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  12959. : diag::err_mutable_reference;
  12960. else if (T.isConstQualified())
  12961. DiagID = diag::err_mutable_const;
  12962. if (DiagID) {
  12963. SourceLocation ErrLoc = Loc;
  12964. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  12965. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  12966. Diag(ErrLoc, DiagID);
  12967. if (DiagID != diag::ext_mutable_reference) {
  12968. Mutable = false;
  12969. InvalidDecl = true;
  12970. }
  12971. }
  12972. }
  12973. // C++11 [class.union]p8 (DR1460):
  12974. // At most one variant member of a union may have a
  12975. // brace-or-equal-initializer.
  12976. if (InitStyle != ICIS_NoInit)
  12977. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  12978. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  12979. BitWidth, Mutable, InitStyle);
  12980. if (InvalidDecl)
  12981. NewFD->setInvalidDecl();
  12982. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  12983. Diag(Loc, diag::err_duplicate_member) << II;
  12984. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12985. NewFD->setInvalidDecl();
  12986. }
  12987. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  12988. if (Record->isUnion()) {
  12989. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12990. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12991. if (RDecl->getDefinition()) {
  12992. // C++ [class.union]p1: An object of a class with a non-trivial
  12993. // constructor, a non-trivial copy constructor, a non-trivial
  12994. // destructor, or a non-trivial copy assignment operator
  12995. // cannot be a member of a union, nor can an array of such
  12996. // objects.
  12997. if (CheckNontrivialField(NewFD))
  12998. NewFD->setInvalidDecl();
  12999. }
  13000. }
  13001. // C++ [class.union]p1: If a union contains a member of reference type,
  13002. // the program is ill-formed, except when compiling with MSVC extensions
  13003. // enabled.
  13004. if (EltTy->isReferenceType()) {
  13005. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  13006. diag::ext_union_member_of_reference_type :
  13007. diag::err_union_member_of_reference_type)
  13008. << NewFD->getDeclName() << EltTy;
  13009. if (!getLangOpts().MicrosoftExt)
  13010. NewFD->setInvalidDecl();
  13011. }
  13012. }
  13013. }
  13014. // FIXME: We need to pass in the attributes given an AST
  13015. // representation, not a parser representation.
  13016. if (D) {
  13017. // FIXME: The current scope is almost... but not entirely... correct here.
  13018. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  13019. if (NewFD->hasAttrs())
  13020. CheckAlignasUnderalignment(NewFD);
  13021. }
  13022. // In auto-retain/release, infer strong retension for fields of
  13023. // retainable type.
  13024. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  13025. NewFD->setInvalidDecl();
  13026. if (T.isObjCGCWeak())
  13027. Diag(Loc, diag::warn_attribute_weak_on_field);
  13028. NewFD->setAccess(AS);
  13029. return NewFD;
  13030. }
  13031. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  13032. assert(FD);
  13033. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  13034. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  13035. return false;
  13036. QualType EltTy = Context.getBaseElementType(FD->getType());
  13037. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13038. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13039. if (RDecl->getDefinition()) {
  13040. // We check for copy constructors before constructors
  13041. // because otherwise we'll never get complaints about
  13042. // copy constructors.
  13043. CXXSpecialMember member = CXXInvalid;
  13044. // We're required to check for any non-trivial constructors. Since the
  13045. // implicit default constructor is suppressed if there are any
  13046. // user-declared constructors, we just need to check that there is a
  13047. // trivial default constructor and a trivial copy constructor. (We don't
  13048. // worry about move constructors here, since this is a C++98 check.)
  13049. if (RDecl->hasNonTrivialCopyConstructor())
  13050. member = CXXCopyConstructor;
  13051. else if (!RDecl->hasTrivialDefaultConstructor())
  13052. member = CXXDefaultConstructor;
  13053. else if (RDecl->hasNonTrivialCopyAssignment())
  13054. member = CXXCopyAssignment;
  13055. else if (RDecl->hasNonTrivialDestructor())
  13056. member = CXXDestructor;
  13057. if (member != CXXInvalid) {
  13058. if (!getLangOpts().CPlusPlus11 &&
  13059. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  13060. // Objective-C++ ARC: it is an error to have a non-trivial field of
  13061. // a union. However, system headers in Objective-C programs
  13062. // occasionally have Objective-C lifetime objects within unions,
  13063. // and rather than cause the program to fail, we make those
  13064. // members unavailable.
  13065. SourceLocation Loc = FD->getLocation();
  13066. if (getSourceManager().isInSystemHeader(Loc)) {
  13067. if (!FD->hasAttr<UnavailableAttr>())
  13068. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13069. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  13070. return false;
  13071. }
  13072. }
  13073. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  13074. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  13075. diag::err_illegal_union_or_anon_struct_member)
  13076. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  13077. DiagnoseNontrivial(RDecl, member);
  13078. return !getLangOpts().CPlusPlus11;
  13079. }
  13080. }
  13081. }
  13082. return false;
  13083. }
  13084. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  13085. /// AST enum value.
  13086. static ObjCIvarDecl::AccessControl
  13087. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  13088. switch (ivarVisibility) {
  13089. default: llvm_unreachable("Unknown visitibility kind");
  13090. case tok::objc_private: return ObjCIvarDecl::Private;
  13091. case tok::objc_public: return ObjCIvarDecl::Public;
  13092. case tok::objc_protected: return ObjCIvarDecl::Protected;
  13093. case tok::objc_package: return ObjCIvarDecl::Package;
  13094. }
  13095. }
  13096. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  13097. /// in order to create an IvarDecl object for it.
  13098. Decl *Sema::ActOnIvar(Scope *S,
  13099. SourceLocation DeclStart,
  13100. Declarator &D, Expr *BitfieldWidth,
  13101. tok::ObjCKeywordKind Visibility) {
  13102. IdentifierInfo *II = D.getIdentifier();
  13103. Expr *BitWidth = (Expr*)BitfieldWidth;
  13104. SourceLocation Loc = DeclStart;
  13105. if (II) Loc = D.getIdentifierLoc();
  13106. // FIXME: Unnamed fields can be handled in various different ways, for
  13107. // example, unnamed unions inject all members into the struct namespace!
  13108. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13109. QualType T = TInfo->getType();
  13110. if (BitWidth) {
  13111. // 6.7.2.1p3, 6.7.2.1p4
  13112. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  13113. if (!BitWidth)
  13114. D.setInvalidType();
  13115. } else {
  13116. // Not a bitfield.
  13117. // validate II.
  13118. }
  13119. if (T->isReferenceType()) {
  13120. Diag(Loc, diag::err_ivar_reference_type);
  13121. D.setInvalidType();
  13122. }
  13123. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13124. // than a variably modified type.
  13125. else if (T->isVariablyModifiedType()) {
  13126. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  13127. D.setInvalidType();
  13128. }
  13129. // Get the visibility (access control) for this ivar.
  13130. ObjCIvarDecl::AccessControl ac =
  13131. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  13132. : ObjCIvarDecl::None;
  13133. // Must set ivar's DeclContext to its enclosing interface.
  13134. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  13135. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  13136. return nullptr;
  13137. ObjCContainerDecl *EnclosingContext;
  13138. if (ObjCImplementationDecl *IMPDecl =
  13139. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13140. if (LangOpts.ObjCRuntime.isFragile()) {
  13141. // Case of ivar declared in an implementation. Context is that of its class.
  13142. EnclosingContext = IMPDecl->getClassInterface();
  13143. assert(EnclosingContext && "Implementation has no class interface!");
  13144. }
  13145. else
  13146. EnclosingContext = EnclosingDecl;
  13147. } else {
  13148. if (ObjCCategoryDecl *CDecl =
  13149. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13150. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  13151. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  13152. return nullptr;
  13153. }
  13154. }
  13155. EnclosingContext = EnclosingDecl;
  13156. }
  13157. // Construct the decl.
  13158. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  13159. DeclStart, Loc, II, T,
  13160. TInfo, ac, (Expr *)BitfieldWidth);
  13161. if (II) {
  13162. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  13163. ForVisibleRedeclaration);
  13164. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  13165. && !isa<TagDecl>(PrevDecl)) {
  13166. Diag(Loc, diag::err_duplicate_member) << II;
  13167. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13168. NewID->setInvalidDecl();
  13169. }
  13170. }
  13171. // Process attributes attached to the ivar.
  13172. ProcessDeclAttributes(S, NewID, D);
  13173. if (D.isInvalidType())
  13174. NewID->setInvalidDecl();
  13175. // In ARC, infer 'retaining' for ivars of retainable type.
  13176. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  13177. NewID->setInvalidDecl();
  13178. if (D.getDeclSpec().isModulePrivateSpecified())
  13179. NewID->setModulePrivate();
  13180. if (II) {
  13181. // FIXME: When interfaces are DeclContexts, we'll need to add
  13182. // these to the interface.
  13183. S->AddDecl(NewID);
  13184. IdResolver.AddDecl(NewID);
  13185. }
  13186. if (LangOpts.ObjCRuntime.isNonFragile() &&
  13187. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  13188. Diag(Loc, diag::warn_ivars_in_interface);
  13189. return NewID;
  13190. }
  13191. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  13192. /// class and class extensions. For every class \@interface and class
  13193. /// extension \@interface, if the last ivar is a bitfield of any type,
  13194. /// then add an implicit `char :0` ivar to the end of that interface.
  13195. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  13196. SmallVectorImpl<Decl *> &AllIvarDecls) {
  13197. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  13198. return;
  13199. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  13200. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  13201. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  13202. return;
  13203. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  13204. if (!ID) {
  13205. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  13206. if (!CD->IsClassExtension())
  13207. return;
  13208. }
  13209. // No need to add this to end of @implementation.
  13210. else
  13211. return;
  13212. }
  13213. // All conditions are met. Add a new bitfield to the tail end of ivars.
  13214. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  13215. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  13216. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  13217. DeclLoc, DeclLoc, nullptr,
  13218. Context.CharTy,
  13219. Context.getTrivialTypeSourceInfo(Context.CharTy,
  13220. DeclLoc),
  13221. ObjCIvarDecl::Private, BW,
  13222. true);
  13223. AllIvarDecls.push_back(Ivar);
  13224. }
  13225. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  13226. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  13227. SourceLocation RBrac, AttributeList *Attr) {
  13228. assert(EnclosingDecl && "missing record or interface decl");
  13229. // If this is an Objective-C @implementation or category and we have
  13230. // new fields here we should reset the layout of the interface since
  13231. // it will now change.
  13232. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  13233. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  13234. switch (DC->getKind()) {
  13235. default: break;
  13236. case Decl::ObjCCategory:
  13237. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  13238. break;
  13239. case Decl::ObjCImplementation:
  13240. Context.
  13241. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  13242. break;
  13243. }
  13244. }
  13245. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  13246. // Start counting up the number of named members; make sure to include
  13247. // members of anonymous structs and unions in the total.
  13248. unsigned NumNamedMembers = 0;
  13249. if (Record) {
  13250. for (const auto *I : Record->decls()) {
  13251. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  13252. if (IFD->getDeclName())
  13253. ++NumNamedMembers;
  13254. }
  13255. }
  13256. // Verify that all the fields are okay.
  13257. SmallVector<FieldDecl*, 32> RecFields;
  13258. bool ObjCFieldLifetimeErrReported = false;
  13259. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  13260. i != end; ++i) {
  13261. FieldDecl *FD = cast<FieldDecl>(*i);
  13262. // Get the type for the field.
  13263. const Type *FDTy = FD->getType().getTypePtr();
  13264. if (!FD->isAnonymousStructOrUnion()) {
  13265. // Remember all fields written by the user.
  13266. RecFields.push_back(FD);
  13267. }
  13268. // If the field is already invalid for some reason, don't emit more
  13269. // diagnostics about it.
  13270. if (FD->isInvalidDecl()) {
  13271. EnclosingDecl->setInvalidDecl();
  13272. continue;
  13273. }
  13274. // C99 6.7.2.1p2:
  13275. // A structure or union shall not contain a member with
  13276. // incomplete or function type (hence, a structure shall not
  13277. // contain an instance of itself, but may contain a pointer to
  13278. // an instance of itself), except that the last member of a
  13279. // structure with more than one named member may have incomplete
  13280. // array type; such a structure (and any union containing,
  13281. // possibly recursively, a member that is such a structure)
  13282. // shall not be a member of a structure or an element of an
  13283. // array.
  13284. bool IsLastField = (i + 1 == Fields.end());
  13285. if (FDTy->isFunctionType()) {
  13286. // Field declared as a function.
  13287. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  13288. << FD->getDeclName();
  13289. FD->setInvalidDecl();
  13290. EnclosingDecl->setInvalidDecl();
  13291. continue;
  13292. } else if (FDTy->isIncompleteArrayType() &&
  13293. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  13294. if (Record) {
  13295. // Flexible array member.
  13296. // Microsoft and g++ is more permissive regarding flexible array.
  13297. // It will accept flexible array in union and also
  13298. // as the sole element of a struct/class.
  13299. unsigned DiagID = 0;
  13300. if (!Record->isUnion() && !IsLastField) {
  13301. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  13302. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  13303. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  13304. FD->setInvalidDecl();
  13305. EnclosingDecl->setInvalidDecl();
  13306. continue;
  13307. } else if (Record->isUnion())
  13308. DiagID = getLangOpts().MicrosoftExt
  13309. ? diag::ext_flexible_array_union_ms
  13310. : getLangOpts().CPlusPlus
  13311. ? diag::ext_flexible_array_union_gnu
  13312. : diag::err_flexible_array_union;
  13313. else if (NumNamedMembers < 1)
  13314. DiagID = getLangOpts().MicrosoftExt
  13315. ? diag::ext_flexible_array_empty_aggregate_ms
  13316. : getLangOpts().CPlusPlus
  13317. ? diag::ext_flexible_array_empty_aggregate_gnu
  13318. : diag::err_flexible_array_empty_aggregate;
  13319. if (DiagID)
  13320. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  13321. << Record->getTagKind();
  13322. // While the layout of types that contain virtual bases is not specified
  13323. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  13324. // virtual bases after the derived members. This would make a flexible
  13325. // array member declared at the end of an object not adjacent to the end
  13326. // of the type.
  13327. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  13328. if (RD->getNumVBases() != 0)
  13329. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  13330. << FD->getDeclName() << Record->getTagKind();
  13331. if (!getLangOpts().C99)
  13332. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  13333. << FD->getDeclName() << Record->getTagKind();
  13334. // If the element type has a non-trivial destructor, we would not
  13335. // implicitly destroy the elements, so disallow it for now.
  13336. //
  13337. // FIXME: GCC allows this. We should probably either implicitly delete
  13338. // the destructor of the containing class, or just allow this.
  13339. QualType BaseElem = Context.getBaseElementType(FD->getType());
  13340. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  13341. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  13342. << FD->getDeclName() << FD->getType();
  13343. FD->setInvalidDecl();
  13344. EnclosingDecl->setInvalidDecl();
  13345. continue;
  13346. }
  13347. // Okay, we have a legal flexible array member at the end of the struct.
  13348. Record->setHasFlexibleArrayMember(true);
  13349. } else {
  13350. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  13351. // unless they are followed by another ivar. That check is done
  13352. // elsewhere, after synthesized ivars are known.
  13353. }
  13354. } else if (!FDTy->isDependentType() &&
  13355. RequireCompleteType(FD->getLocation(), FD->getType(),
  13356. diag::err_field_incomplete)) {
  13357. // Incomplete type
  13358. FD->setInvalidDecl();
  13359. EnclosingDecl->setInvalidDecl();
  13360. continue;
  13361. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  13362. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  13363. // A type which contains a flexible array member is considered to be a
  13364. // flexible array member.
  13365. Record->setHasFlexibleArrayMember(true);
  13366. if (!Record->isUnion()) {
  13367. // If this is a struct/class and this is not the last element, reject
  13368. // it. Note that GCC supports variable sized arrays in the middle of
  13369. // structures.
  13370. if (!IsLastField)
  13371. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  13372. << FD->getDeclName() << FD->getType();
  13373. else {
  13374. // We support flexible arrays at the end of structs in
  13375. // other structs as an extension.
  13376. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  13377. << FD->getDeclName();
  13378. }
  13379. }
  13380. }
  13381. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  13382. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  13383. diag::err_abstract_type_in_decl,
  13384. AbstractIvarType)) {
  13385. // Ivars can not have abstract class types
  13386. FD->setInvalidDecl();
  13387. }
  13388. if (Record && FDTTy->getDecl()->hasObjectMember())
  13389. Record->setHasObjectMember(true);
  13390. if (Record && FDTTy->getDecl()->hasVolatileMember())
  13391. Record->setHasVolatileMember(true);
  13392. } else if (FDTy->isObjCObjectType()) {
  13393. /// A field cannot be an Objective-c object
  13394. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  13395. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  13396. QualType T = Context.getObjCObjectPointerType(FD->getType());
  13397. FD->setType(T);
  13398. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  13399. Record && !ObjCFieldLifetimeErrReported &&
  13400. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  13401. // It's an error in ARC or Weak if a field has lifetime.
  13402. // We don't want to report this in a system header, though,
  13403. // so we just make the field unavailable.
  13404. // FIXME: that's really not sufficient; we need to make the type
  13405. // itself invalid to, say, initialize or copy.
  13406. QualType T = FD->getType();
  13407. if (T.hasNonTrivialObjCLifetime()) {
  13408. SourceLocation loc = FD->getLocation();
  13409. if (getSourceManager().isInSystemHeader(loc)) {
  13410. if (!FD->hasAttr<UnavailableAttr>()) {
  13411. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13412. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  13413. }
  13414. } else {
  13415. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  13416. << T->isBlockPointerType() << Record->getTagKind();
  13417. }
  13418. ObjCFieldLifetimeErrReported = true;
  13419. }
  13420. } else if (getLangOpts().ObjC1 &&
  13421. getLangOpts().getGC() != LangOptions::NonGC &&
  13422. Record && !Record->hasObjectMember()) {
  13423. if (FD->getType()->isObjCObjectPointerType() ||
  13424. FD->getType().isObjCGCStrong())
  13425. Record->setHasObjectMember(true);
  13426. else if (Context.getAsArrayType(FD->getType())) {
  13427. QualType BaseType = Context.getBaseElementType(FD->getType());
  13428. if (BaseType->isRecordType() &&
  13429. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  13430. Record->setHasObjectMember(true);
  13431. else if (BaseType->isObjCObjectPointerType() ||
  13432. BaseType.isObjCGCStrong())
  13433. Record->setHasObjectMember(true);
  13434. }
  13435. }
  13436. if (Record && FD->getType().isVolatileQualified())
  13437. Record->setHasVolatileMember(true);
  13438. // Keep track of the number of named members.
  13439. if (FD->getIdentifier())
  13440. ++NumNamedMembers;
  13441. }
  13442. // Okay, we successfully defined 'Record'.
  13443. if (Record) {
  13444. bool Completed = false;
  13445. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13446. if (!CXXRecord->isInvalidDecl()) {
  13447. // Set access bits correctly on the directly-declared conversions.
  13448. for (CXXRecordDecl::conversion_iterator
  13449. I = CXXRecord->conversion_begin(),
  13450. E = CXXRecord->conversion_end(); I != E; ++I)
  13451. I.setAccess((*I)->getAccess());
  13452. }
  13453. if (!CXXRecord->isDependentType()) {
  13454. if (CXXRecord->hasUserDeclaredDestructor()) {
  13455. // Adjust user-defined destructor exception spec.
  13456. if (getLangOpts().CPlusPlus11)
  13457. AdjustDestructorExceptionSpec(CXXRecord,
  13458. CXXRecord->getDestructor());
  13459. }
  13460. if (!CXXRecord->isInvalidDecl()) {
  13461. // Add any implicitly-declared members to this class.
  13462. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  13463. // If we have virtual base classes, we may end up finding multiple
  13464. // final overriders for a given virtual function. Check for this
  13465. // problem now.
  13466. if (CXXRecord->getNumVBases()) {
  13467. CXXFinalOverriderMap FinalOverriders;
  13468. CXXRecord->getFinalOverriders(FinalOverriders);
  13469. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  13470. MEnd = FinalOverriders.end();
  13471. M != MEnd; ++M) {
  13472. for (OverridingMethods::iterator SO = M->second.begin(),
  13473. SOEnd = M->second.end();
  13474. SO != SOEnd; ++SO) {
  13475. assert(SO->second.size() > 0 &&
  13476. "Virtual function without overridding functions?");
  13477. if (SO->second.size() == 1)
  13478. continue;
  13479. // C++ [class.virtual]p2:
  13480. // In a derived class, if a virtual member function of a base
  13481. // class subobject has more than one final overrider the
  13482. // program is ill-formed.
  13483. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  13484. << (const NamedDecl *)M->first << Record;
  13485. Diag(M->first->getLocation(),
  13486. diag::note_overridden_virtual_function);
  13487. for (OverridingMethods::overriding_iterator
  13488. OM = SO->second.begin(),
  13489. OMEnd = SO->second.end();
  13490. OM != OMEnd; ++OM)
  13491. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  13492. << (const NamedDecl *)M->first << OM->Method->getParent();
  13493. Record->setInvalidDecl();
  13494. }
  13495. }
  13496. CXXRecord->completeDefinition(&FinalOverriders);
  13497. Completed = true;
  13498. }
  13499. }
  13500. }
  13501. }
  13502. if (!Completed)
  13503. Record->completeDefinition();
  13504. // We may have deferred checking for a deleted destructor. Check now.
  13505. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13506. auto *Dtor = CXXRecord->getDestructor();
  13507. if (Dtor && Dtor->isImplicit() &&
  13508. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  13509. CXXRecord->setImplicitDestructorIsDeleted();
  13510. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  13511. }
  13512. }
  13513. if (Record->hasAttrs()) {
  13514. CheckAlignasUnderalignment(Record);
  13515. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  13516. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  13517. IA->getRange(), IA->getBestCase(),
  13518. IA->getSemanticSpelling());
  13519. }
  13520. // Check if the structure/union declaration is a type that can have zero
  13521. // size in C. For C this is a language extension, for C++ it may cause
  13522. // compatibility problems.
  13523. bool CheckForZeroSize;
  13524. if (!getLangOpts().CPlusPlus) {
  13525. CheckForZeroSize = true;
  13526. } else {
  13527. // For C++ filter out types that cannot be referenced in C code.
  13528. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  13529. CheckForZeroSize =
  13530. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  13531. !CXXRecord->isDependentType() &&
  13532. CXXRecord->isCLike();
  13533. }
  13534. if (CheckForZeroSize) {
  13535. bool ZeroSize = true;
  13536. bool IsEmpty = true;
  13537. unsigned NonBitFields = 0;
  13538. for (RecordDecl::field_iterator I = Record->field_begin(),
  13539. E = Record->field_end();
  13540. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  13541. IsEmpty = false;
  13542. if (I->isUnnamedBitfield()) {
  13543. if (I->getBitWidthValue(Context) > 0)
  13544. ZeroSize = false;
  13545. } else {
  13546. ++NonBitFields;
  13547. QualType FieldType = I->getType();
  13548. if (FieldType->isIncompleteType() ||
  13549. !Context.getTypeSizeInChars(FieldType).isZero())
  13550. ZeroSize = false;
  13551. }
  13552. }
  13553. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  13554. // allowed in C++, but warn if its declaration is inside
  13555. // extern "C" block.
  13556. if (ZeroSize) {
  13557. Diag(RecLoc, getLangOpts().CPlusPlus ?
  13558. diag::warn_zero_size_struct_union_in_extern_c :
  13559. diag::warn_zero_size_struct_union_compat)
  13560. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  13561. }
  13562. // Structs without named members are extension in C (C99 6.7.2.1p7),
  13563. // but are accepted by GCC.
  13564. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  13565. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  13566. diag::ext_no_named_members_in_struct_union)
  13567. << Record->isUnion();
  13568. }
  13569. }
  13570. } else {
  13571. ObjCIvarDecl **ClsFields =
  13572. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  13573. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  13574. ID->setEndOfDefinitionLoc(RBrac);
  13575. // Add ivar's to class's DeclContext.
  13576. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13577. ClsFields[i]->setLexicalDeclContext(ID);
  13578. ID->addDecl(ClsFields[i]);
  13579. }
  13580. // Must enforce the rule that ivars in the base classes may not be
  13581. // duplicates.
  13582. if (ID->getSuperClass())
  13583. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  13584. } else if (ObjCImplementationDecl *IMPDecl =
  13585. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13586. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  13587. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  13588. // Ivar declared in @implementation never belongs to the implementation.
  13589. // Only it is in implementation's lexical context.
  13590. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  13591. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  13592. IMPDecl->setIvarLBraceLoc(LBrac);
  13593. IMPDecl->setIvarRBraceLoc(RBrac);
  13594. } else if (ObjCCategoryDecl *CDecl =
  13595. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13596. // case of ivars in class extension; all other cases have been
  13597. // reported as errors elsewhere.
  13598. // FIXME. Class extension does not have a LocEnd field.
  13599. // CDecl->setLocEnd(RBrac);
  13600. // Add ivar's to class extension's DeclContext.
  13601. // Diagnose redeclaration of private ivars.
  13602. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  13603. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13604. if (IDecl) {
  13605. if (const ObjCIvarDecl *ClsIvar =
  13606. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13607. Diag(ClsFields[i]->getLocation(),
  13608. diag::err_duplicate_ivar_declaration);
  13609. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  13610. continue;
  13611. }
  13612. for (const auto *Ext : IDecl->known_extensions()) {
  13613. if (const ObjCIvarDecl *ClsExtIvar
  13614. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13615. Diag(ClsFields[i]->getLocation(),
  13616. diag::err_duplicate_ivar_declaration);
  13617. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  13618. continue;
  13619. }
  13620. }
  13621. }
  13622. ClsFields[i]->setLexicalDeclContext(CDecl);
  13623. CDecl->addDecl(ClsFields[i]);
  13624. }
  13625. CDecl->setIvarLBraceLoc(LBrac);
  13626. CDecl->setIvarRBraceLoc(RBrac);
  13627. }
  13628. }
  13629. if (Attr)
  13630. ProcessDeclAttributeList(S, Record, Attr);
  13631. }
  13632. /// \brief Determine whether the given integral value is representable within
  13633. /// the given type T.
  13634. static bool isRepresentableIntegerValue(ASTContext &Context,
  13635. llvm::APSInt &Value,
  13636. QualType T) {
  13637. assert(T->isIntegralType(Context) && "Integral type required!");
  13638. unsigned BitWidth = Context.getIntWidth(T);
  13639. if (Value.isUnsigned() || Value.isNonNegative()) {
  13640. if (T->isSignedIntegerOrEnumerationType())
  13641. --BitWidth;
  13642. return Value.getActiveBits() <= BitWidth;
  13643. }
  13644. return Value.getMinSignedBits() <= BitWidth;
  13645. }
  13646. // \brief Given an integral type, return the next larger integral type
  13647. // (or a NULL type of no such type exists).
  13648. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  13649. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  13650. // enum checking below.
  13651. assert(T->isIntegralType(Context) && "Integral type required!");
  13652. const unsigned NumTypes = 4;
  13653. QualType SignedIntegralTypes[NumTypes] = {
  13654. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  13655. };
  13656. QualType UnsignedIntegralTypes[NumTypes] = {
  13657. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  13658. Context.UnsignedLongLongTy
  13659. };
  13660. unsigned BitWidth = Context.getTypeSize(T);
  13661. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  13662. : UnsignedIntegralTypes;
  13663. for (unsigned I = 0; I != NumTypes; ++I)
  13664. if (Context.getTypeSize(Types[I]) > BitWidth)
  13665. return Types[I];
  13666. return QualType();
  13667. }
  13668. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  13669. EnumConstantDecl *LastEnumConst,
  13670. SourceLocation IdLoc,
  13671. IdentifierInfo *Id,
  13672. Expr *Val) {
  13673. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13674. llvm::APSInt EnumVal(IntWidth);
  13675. QualType EltTy;
  13676. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  13677. Val = nullptr;
  13678. if (Val)
  13679. Val = DefaultLvalueConversion(Val).get();
  13680. if (Val) {
  13681. if (Enum->isDependentType() || Val->isTypeDependent())
  13682. EltTy = Context.DependentTy;
  13683. else {
  13684. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  13685. !getLangOpts().MSVCCompat) {
  13686. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  13687. // constant-expression in the enumerator-definition shall be a converted
  13688. // constant expression of the underlying type.
  13689. EltTy = Enum->getIntegerType();
  13690. ExprResult Converted =
  13691. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  13692. CCEK_Enumerator);
  13693. if (Converted.isInvalid())
  13694. Val = nullptr;
  13695. else
  13696. Val = Converted.get();
  13697. } else if (!Val->isValueDependent() &&
  13698. !(Val = VerifyIntegerConstantExpression(Val,
  13699. &EnumVal).get())) {
  13700. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  13701. } else {
  13702. if (Enum->isFixed()) {
  13703. EltTy = Enum->getIntegerType();
  13704. // In Obj-C and Microsoft mode, require the enumeration value to be
  13705. // representable in the underlying type of the enumeration. In C++11,
  13706. // we perform a non-narrowing conversion as part of converted constant
  13707. // expression checking.
  13708. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13709. if (getLangOpts().MSVCCompat) {
  13710. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  13711. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  13712. } else
  13713. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  13714. } else
  13715. Val = ImpCastExprToType(Val, EltTy,
  13716. EltTy->isBooleanType() ?
  13717. CK_IntegralToBoolean : CK_IntegralCast)
  13718. .get();
  13719. } else if (getLangOpts().CPlusPlus) {
  13720. // C++11 [dcl.enum]p5:
  13721. // If the underlying type is not fixed, the type of each enumerator
  13722. // is the type of its initializing value:
  13723. // - If an initializer is specified for an enumerator, the
  13724. // initializing value has the same type as the expression.
  13725. EltTy = Val->getType();
  13726. } else {
  13727. // C99 6.7.2.2p2:
  13728. // The expression that defines the value of an enumeration constant
  13729. // shall be an integer constant expression that has a value
  13730. // representable as an int.
  13731. // Complain if the value is not representable in an int.
  13732. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  13733. Diag(IdLoc, diag::ext_enum_value_not_int)
  13734. << EnumVal.toString(10) << Val->getSourceRange()
  13735. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  13736. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  13737. // Force the type of the expression to 'int'.
  13738. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  13739. }
  13740. EltTy = Val->getType();
  13741. }
  13742. }
  13743. }
  13744. }
  13745. if (!Val) {
  13746. if (Enum->isDependentType())
  13747. EltTy = Context.DependentTy;
  13748. else if (!LastEnumConst) {
  13749. // C++0x [dcl.enum]p5:
  13750. // If the underlying type is not fixed, the type of each enumerator
  13751. // is the type of its initializing value:
  13752. // - If no initializer is specified for the first enumerator, the
  13753. // initializing value has an unspecified integral type.
  13754. //
  13755. // GCC uses 'int' for its unspecified integral type, as does
  13756. // C99 6.7.2.2p3.
  13757. if (Enum->isFixed()) {
  13758. EltTy = Enum->getIntegerType();
  13759. }
  13760. else {
  13761. EltTy = Context.IntTy;
  13762. }
  13763. } else {
  13764. // Assign the last value + 1.
  13765. EnumVal = LastEnumConst->getInitVal();
  13766. ++EnumVal;
  13767. EltTy = LastEnumConst->getType();
  13768. // Check for overflow on increment.
  13769. if (EnumVal < LastEnumConst->getInitVal()) {
  13770. // C++0x [dcl.enum]p5:
  13771. // If the underlying type is not fixed, the type of each enumerator
  13772. // is the type of its initializing value:
  13773. //
  13774. // - Otherwise the type of the initializing value is the same as
  13775. // the type of the initializing value of the preceding enumerator
  13776. // unless the incremented value is not representable in that type,
  13777. // in which case the type is an unspecified integral type
  13778. // sufficient to contain the incremented value. If no such type
  13779. // exists, the program is ill-formed.
  13780. QualType T = getNextLargerIntegralType(Context, EltTy);
  13781. if (T.isNull() || Enum->isFixed()) {
  13782. // There is no integral type larger enough to represent this
  13783. // value. Complain, then allow the value to wrap around.
  13784. EnumVal = LastEnumConst->getInitVal();
  13785. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  13786. ++EnumVal;
  13787. if (Enum->isFixed())
  13788. // When the underlying type is fixed, this is ill-formed.
  13789. Diag(IdLoc, diag::err_enumerator_wrapped)
  13790. << EnumVal.toString(10)
  13791. << EltTy;
  13792. else
  13793. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  13794. << EnumVal.toString(10);
  13795. } else {
  13796. EltTy = T;
  13797. }
  13798. // Retrieve the last enumerator's value, extent that type to the
  13799. // type that is supposed to be large enough to represent the incremented
  13800. // value, then increment.
  13801. EnumVal = LastEnumConst->getInitVal();
  13802. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13803. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  13804. ++EnumVal;
  13805. // If we're not in C++, diagnose the overflow of enumerator values,
  13806. // which in C99 means that the enumerator value is not representable in
  13807. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  13808. // permits enumerator values that are representable in some larger
  13809. // integral type.
  13810. if (!getLangOpts().CPlusPlus && !T.isNull())
  13811. Diag(IdLoc, diag::warn_enum_value_overflow);
  13812. } else if (!getLangOpts().CPlusPlus &&
  13813. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13814. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  13815. Diag(IdLoc, diag::ext_enum_value_not_int)
  13816. << EnumVal.toString(10) << 1;
  13817. }
  13818. }
  13819. }
  13820. if (!EltTy->isDependentType()) {
  13821. // Make the enumerator value match the signedness and size of the
  13822. // enumerator's type.
  13823. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  13824. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13825. }
  13826. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  13827. Val, EnumVal);
  13828. }
  13829. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  13830. SourceLocation IILoc) {
  13831. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  13832. !getLangOpts().CPlusPlus)
  13833. return SkipBodyInfo();
  13834. // We have an anonymous enum definition. Look up the first enumerator to
  13835. // determine if we should merge the definition with an existing one and
  13836. // skip the body.
  13837. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  13838. forRedeclarationInCurContext());
  13839. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  13840. if (!PrevECD)
  13841. return SkipBodyInfo();
  13842. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  13843. NamedDecl *Hidden;
  13844. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  13845. SkipBodyInfo Skip;
  13846. Skip.Previous = Hidden;
  13847. return Skip;
  13848. }
  13849. return SkipBodyInfo();
  13850. }
  13851. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  13852. SourceLocation IdLoc, IdentifierInfo *Id,
  13853. AttributeList *Attr,
  13854. SourceLocation EqualLoc, Expr *Val) {
  13855. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  13856. EnumConstantDecl *LastEnumConst =
  13857. cast_or_null<EnumConstantDecl>(lastEnumConst);
  13858. // The scope passed in may not be a decl scope. Zip up the scope tree until
  13859. // we find one that is.
  13860. S = getNonFieldDeclScope(S);
  13861. // Verify that there isn't already something declared with this name in this
  13862. // scope.
  13863. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  13864. ForVisibleRedeclaration);
  13865. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13866. // Maybe we will complain about the shadowed template parameter.
  13867. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  13868. // Just pretend that we didn't see the previous declaration.
  13869. PrevDecl = nullptr;
  13870. }
  13871. // C++ [class.mem]p15:
  13872. // If T is the name of a class, then each of the following shall have a name
  13873. // different from T:
  13874. // - every enumerator of every member of class T that is an unscoped
  13875. // enumerated type
  13876. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  13877. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  13878. DeclarationNameInfo(Id, IdLoc));
  13879. EnumConstantDecl *New =
  13880. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  13881. if (!New)
  13882. return nullptr;
  13883. if (PrevDecl) {
  13884. // When in C++, we may get a TagDecl with the same name; in this case the
  13885. // enum constant will 'hide' the tag.
  13886. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  13887. "Received TagDecl when not in C++!");
  13888. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  13889. if (isa<EnumConstantDecl>(PrevDecl))
  13890. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  13891. else
  13892. Diag(IdLoc, diag::err_redefinition) << Id;
  13893. notePreviousDefinition(PrevDecl, IdLoc);
  13894. return nullptr;
  13895. }
  13896. }
  13897. // Process attributes.
  13898. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  13899. AddPragmaAttributes(S, New);
  13900. // Register this decl in the current scope stack.
  13901. New->setAccess(TheEnumDecl->getAccess());
  13902. PushOnScopeChains(New, S);
  13903. ActOnDocumentableDecl(New);
  13904. return New;
  13905. }
  13906. // Returns true when the enum initial expression does not trigger the
  13907. // duplicate enum warning. A few common cases are exempted as follows:
  13908. // Element2 = Element1
  13909. // Element2 = Element1 + 1
  13910. // Element2 = Element1 - 1
  13911. // Where Element2 and Element1 are from the same enum.
  13912. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  13913. Expr *InitExpr = ECD->getInitExpr();
  13914. if (!InitExpr)
  13915. return true;
  13916. InitExpr = InitExpr->IgnoreImpCasts();
  13917. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  13918. if (!BO->isAdditiveOp())
  13919. return true;
  13920. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  13921. if (!IL)
  13922. return true;
  13923. if (IL->getValue() != 1)
  13924. return true;
  13925. InitExpr = BO->getLHS();
  13926. }
  13927. // This checks if the elements are from the same enum.
  13928. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  13929. if (!DRE)
  13930. return true;
  13931. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  13932. if (!EnumConstant)
  13933. return true;
  13934. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  13935. Enum)
  13936. return true;
  13937. return false;
  13938. }
  13939. namespace {
  13940. struct DupKey {
  13941. int64_t val;
  13942. bool isTombstoneOrEmptyKey;
  13943. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  13944. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  13945. };
  13946. static DupKey GetDupKey(const llvm::APSInt& Val) {
  13947. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  13948. false);
  13949. }
  13950. struct DenseMapInfoDupKey {
  13951. static DupKey getEmptyKey() { return DupKey(0, true); }
  13952. static DupKey getTombstoneKey() { return DupKey(1, true); }
  13953. static unsigned getHashValue(const DupKey Key) {
  13954. return (unsigned)(Key.val * 37);
  13955. }
  13956. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  13957. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  13958. LHS.val == RHS.val;
  13959. }
  13960. };
  13961. } // end anonymous namespace
  13962. // Emits a warning when an element is implicitly set a value that
  13963. // a previous element has already been set to.
  13964. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  13965. EnumDecl *Enum,
  13966. QualType EnumType) {
  13967. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  13968. return;
  13969. // Avoid anonymous enums
  13970. if (!Enum->getIdentifier())
  13971. return;
  13972. // Only check for small enums.
  13973. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  13974. return;
  13975. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  13976. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  13977. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  13978. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  13979. ValueToVectorMap;
  13980. DuplicatesVector DupVector;
  13981. ValueToVectorMap EnumMap;
  13982. // Populate the EnumMap with all values represented by enum constants without
  13983. // an initialier.
  13984. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13985. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  13986. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  13987. // this constant. Skip this enum since it may be ill-formed.
  13988. if (!ECD) {
  13989. return;
  13990. }
  13991. if (ECD->getInitExpr())
  13992. continue;
  13993. DupKey Key = GetDupKey(ECD->getInitVal());
  13994. DeclOrVector &Entry = EnumMap[Key];
  13995. // First time encountering this value.
  13996. if (Entry.isNull())
  13997. Entry = ECD;
  13998. }
  13999. // Create vectors for any values that has duplicates.
  14000. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14001. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  14002. if (!ValidDuplicateEnum(ECD, Enum))
  14003. continue;
  14004. DupKey Key = GetDupKey(ECD->getInitVal());
  14005. DeclOrVector& Entry = EnumMap[Key];
  14006. if (Entry.isNull())
  14007. continue;
  14008. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  14009. // Ensure constants are different.
  14010. if (D == ECD)
  14011. continue;
  14012. // Create new vector and push values onto it.
  14013. ECDVector *Vec = new ECDVector();
  14014. Vec->push_back(D);
  14015. Vec->push_back(ECD);
  14016. // Update entry to point to the duplicates vector.
  14017. Entry = Vec;
  14018. // Store the vector somewhere we can consult later for quick emission of
  14019. // diagnostics.
  14020. DupVector.push_back(Vec);
  14021. continue;
  14022. }
  14023. ECDVector *Vec = Entry.get<ECDVector*>();
  14024. // Make sure constants are not added more than once.
  14025. if (*Vec->begin() == ECD)
  14026. continue;
  14027. Vec->push_back(ECD);
  14028. }
  14029. // Emit diagnostics.
  14030. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  14031. DupVectorEnd = DupVector.end();
  14032. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  14033. ECDVector *Vec = *DupVectorIter;
  14034. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  14035. // Emit warning for one enum constant.
  14036. ECDVector::iterator I = Vec->begin();
  14037. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  14038. << (*I)->getName() << (*I)->getInitVal().toString(10)
  14039. << (*I)->getSourceRange();
  14040. ++I;
  14041. // Emit one note for each of the remaining enum constants with
  14042. // the same value.
  14043. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  14044. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  14045. << (*I)->getName() << (*I)->getInitVal().toString(10)
  14046. << (*I)->getSourceRange();
  14047. delete Vec;
  14048. }
  14049. }
  14050. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  14051. bool AllowMask) const {
  14052. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  14053. assert(ED->isCompleteDefinition() && "expected enum definition");
  14054. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  14055. llvm::APInt &FlagBits = R.first->second;
  14056. if (R.second) {
  14057. for (auto *E : ED->enumerators()) {
  14058. const auto &EVal = E->getInitVal();
  14059. // Only single-bit enumerators introduce new flag values.
  14060. if (EVal.isPowerOf2())
  14061. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  14062. }
  14063. }
  14064. // A value is in a flag enum if either its bits are a subset of the enum's
  14065. // flag bits (the first condition) or we are allowing masks and the same is
  14066. // true of its complement (the second condition). When masks are allowed, we
  14067. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  14068. //
  14069. // While it's true that any value could be used as a mask, the assumption is
  14070. // that a mask will have all of the insignificant bits set. Anything else is
  14071. // likely a logic error.
  14072. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  14073. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  14074. }
  14075. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  14076. Decl *EnumDeclX,
  14077. ArrayRef<Decl *> Elements,
  14078. Scope *S, AttributeList *Attr) {
  14079. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  14080. QualType EnumType = Context.getTypeDeclType(Enum);
  14081. if (Attr)
  14082. ProcessDeclAttributeList(S, Enum, Attr);
  14083. if (Enum->isDependentType()) {
  14084. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14085. EnumConstantDecl *ECD =
  14086. cast_or_null<EnumConstantDecl>(Elements[i]);
  14087. if (!ECD) continue;
  14088. ECD->setType(EnumType);
  14089. }
  14090. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  14091. return;
  14092. }
  14093. // TODO: If the result value doesn't fit in an int, it must be a long or long
  14094. // long value. ISO C does not support this, but GCC does as an extension,
  14095. // emit a warning.
  14096. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14097. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  14098. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  14099. // Verify that all the values are okay, compute the size of the values, and
  14100. // reverse the list.
  14101. unsigned NumNegativeBits = 0;
  14102. unsigned NumPositiveBits = 0;
  14103. // Keep track of whether all elements have type int.
  14104. bool AllElementsInt = true;
  14105. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14106. EnumConstantDecl *ECD =
  14107. cast_or_null<EnumConstantDecl>(Elements[i]);
  14108. if (!ECD) continue; // Already issued a diagnostic.
  14109. const llvm::APSInt &InitVal = ECD->getInitVal();
  14110. // Keep track of the size of positive and negative values.
  14111. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  14112. NumPositiveBits = std::max(NumPositiveBits,
  14113. (unsigned)InitVal.getActiveBits());
  14114. else
  14115. NumNegativeBits = std::max(NumNegativeBits,
  14116. (unsigned)InitVal.getMinSignedBits());
  14117. // Keep track of whether every enum element has type int (very commmon).
  14118. if (AllElementsInt)
  14119. AllElementsInt = ECD->getType() == Context.IntTy;
  14120. }
  14121. // Figure out the type that should be used for this enum.
  14122. QualType BestType;
  14123. unsigned BestWidth;
  14124. // C++0x N3000 [conv.prom]p3:
  14125. // An rvalue of an unscoped enumeration type whose underlying
  14126. // type is not fixed can be converted to an rvalue of the first
  14127. // of the following types that can represent all the values of
  14128. // the enumeration: int, unsigned int, long int, unsigned long
  14129. // int, long long int, or unsigned long long int.
  14130. // C99 6.4.4.3p2:
  14131. // An identifier declared as an enumeration constant has type int.
  14132. // The C99 rule is modified by a gcc extension
  14133. QualType BestPromotionType;
  14134. bool Packed = Enum->hasAttr<PackedAttr>();
  14135. // -fshort-enums is the equivalent to specifying the packed attribute on all
  14136. // enum definitions.
  14137. if (LangOpts.ShortEnums)
  14138. Packed = true;
  14139. if (Enum->isFixed()) {
  14140. BestType = Enum->getIntegerType();
  14141. if (BestType->isPromotableIntegerType())
  14142. BestPromotionType = Context.getPromotedIntegerType(BestType);
  14143. else
  14144. BestPromotionType = BestType;
  14145. BestWidth = Context.getIntWidth(BestType);
  14146. }
  14147. else if (NumNegativeBits) {
  14148. // If there is a negative value, figure out the smallest integer type (of
  14149. // int/long/longlong) that fits.
  14150. // If it's packed, check also if it fits a char or a short.
  14151. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  14152. BestType = Context.SignedCharTy;
  14153. BestWidth = CharWidth;
  14154. } else if (Packed && NumNegativeBits <= ShortWidth &&
  14155. NumPositiveBits < ShortWidth) {
  14156. BestType = Context.ShortTy;
  14157. BestWidth = ShortWidth;
  14158. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  14159. BestType = Context.IntTy;
  14160. BestWidth = IntWidth;
  14161. } else {
  14162. BestWidth = Context.getTargetInfo().getLongWidth();
  14163. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  14164. BestType = Context.LongTy;
  14165. } else {
  14166. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14167. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  14168. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  14169. BestType = Context.LongLongTy;
  14170. }
  14171. }
  14172. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  14173. } else {
  14174. // If there is no negative value, figure out the smallest type that fits
  14175. // all of the enumerator values.
  14176. // If it's packed, check also if it fits a char or a short.
  14177. if (Packed && NumPositiveBits <= CharWidth) {
  14178. BestType = Context.UnsignedCharTy;
  14179. BestPromotionType = Context.IntTy;
  14180. BestWidth = CharWidth;
  14181. } else if (Packed && NumPositiveBits <= ShortWidth) {
  14182. BestType = Context.UnsignedShortTy;
  14183. BestPromotionType = Context.IntTy;
  14184. BestWidth = ShortWidth;
  14185. } else if (NumPositiveBits <= IntWidth) {
  14186. BestType = Context.UnsignedIntTy;
  14187. BestWidth = IntWidth;
  14188. BestPromotionType
  14189. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14190. ? Context.UnsignedIntTy : Context.IntTy;
  14191. } else if (NumPositiveBits <=
  14192. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  14193. BestType = Context.UnsignedLongTy;
  14194. BestPromotionType
  14195. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14196. ? Context.UnsignedLongTy : Context.LongTy;
  14197. } else {
  14198. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14199. assert(NumPositiveBits <= BestWidth &&
  14200. "How could an initializer get larger than ULL?");
  14201. BestType = Context.UnsignedLongLongTy;
  14202. BestPromotionType
  14203. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14204. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  14205. }
  14206. }
  14207. // Loop over all of the enumerator constants, changing their types to match
  14208. // the type of the enum if needed.
  14209. for (auto *D : Elements) {
  14210. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  14211. if (!ECD) continue; // Already issued a diagnostic.
  14212. // Standard C says the enumerators have int type, but we allow, as an
  14213. // extension, the enumerators to be larger than int size. If each
  14214. // enumerator value fits in an int, type it as an int, otherwise type it the
  14215. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  14216. // that X has type 'int', not 'unsigned'.
  14217. // Determine whether the value fits into an int.
  14218. llvm::APSInt InitVal = ECD->getInitVal();
  14219. // If it fits into an integer type, force it. Otherwise force it to match
  14220. // the enum decl type.
  14221. QualType NewTy;
  14222. unsigned NewWidth;
  14223. bool NewSign;
  14224. if (!getLangOpts().CPlusPlus &&
  14225. !Enum->isFixed() &&
  14226. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  14227. NewTy = Context.IntTy;
  14228. NewWidth = IntWidth;
  14229. NewSign = true;
  14230. } else if (ECD->getType() == BestType) {
  14231. // Already the right type!
  14232. if (getLangOpts().CPlusPlus)
  14233. // C++ [dcl.enum]p4: Following the closing brace of an
  14234. // enum-specifier, each enumerator has the type of its
  14235. // enumeration.
  14236. ECD->setType(EnumType);
  14237. continue;
  14238. } else {
  14239. NewTy = BestType;
  14240. NewWidth = BestWidth;
  14241. NewSign = BestType->isSignedIntegerOrEnumerationType();
  14242. }
  14243. // Adjust the APSInt value.
  14244. InitVal = InitVal.extOrTrunc(NewWidth);
  14245. InitVal.setIsSigned(NewSign);
  14246. ECD->setInitVal(InitVal);
  14247. // Adjust the Expr initializer and type.
  14248. if (ECD->getInitExpr() &&
  14249. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  14250. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  14251. CK_IntegralCast,
  14252. ECD->getInitExpr(),
  14253. /*base paths*/ nullptr,
  14254. VK_RValue));
  14255. if (getLangOpts().CPlusPlus)
  14256. // C++ [dcl.enum]p4: Following the closing brace of an
  14257. // enum-specifier, each enumerator has the type of its
  14258. // enumeration.
  14259. ECD->setType(EnumType);
  14260. else
  14261. ECD->setType(NewTy);
  14262. }
  14263. Enum->completeDefinition(BestType, BestPromotionType,
  14264. NumPositiveBits, NumNegativeBits);
  14265. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  14266. if (Enum->isClosedFlag()) {
  14267. for (Decl *D : Elements) {
  14268. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  14269. if (!ECD) continue; // Already issued a diagnostic.
  14270. llvm::APSInt InitVal = ECD->getInitVal();
  14271. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  14272. !IsValueInFlagEnum(Enum, InitVal, true))
  14273. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  14274. << ECD << Enum;
  14275. }
  14276. }
  14277. // Now that the enum type is defined, ensure it's not been underaligned.
  14278. if (Enum->hasAttrs())
  14279. CheckAlignasUnderalignment(Enum);
  14280. }
  14281. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  14282. SourceLocation StartLoc,
  14283. SourceLocation EndLoc) {
  14284. StringLiteral *AsmString = cast<StringLiteral>(expr);
  14285. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  14286. AsmString, StartLoc,
  14287. EndLoc);
  14288. CurContext->addDecl(New);
  14289. return New;
  14290. }
  14291. static void checkModuleImportContext(Sema &S, Module *M,
  14292. SourceLocation ImportLoc, DeclContext *DC,
  14293. bool FromInclude = false) {
  14294. SourceLocation ExternCLoc;
  14295. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  14296. switch (LSD->getLanguage()) {
  14297. case LinkageSpecDecl::lang_c:
  14298. if (ExternCLoc.isInvalid())
  14299. ExternCLoc = LSD->getLocStart();
  14300. break;
  14301. case LinkageSpecDecl::lang_cxx:
  14302. break;
  14303. }
  14304. DC = LSD->getParent();
  14305. }
  14306. while (isa<LinkageSpecDecl>(DC))
  14307. DC = DC->getParent();
  14308. if (!isa<TranslationUnitDecl>(DC)) {
  14309. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  14310. ? diag::ext_module_import_not_at_top_level_noop
  14311. : diag::err_module_import_not_at_top_level_fatal)
  14312. << M->getFullModuleName() << DC;
  14313. S.Diag(cast<Decl>(DC)->getLocStart(),
  14314. diag::note_module_import_not_at_top_level) << DC;
  14315. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  14316. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  14317. << M->getFullModuleName();
  14318. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  14319. }
  14320. }
  14321. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
  14322. SourceLocation ModuleLoc,
  14323. ModuleDeclKind MDK,
  14324. ModuleIdPath Path) {
  14325. assert(getLangOpts().ModulesTS &&
  14326. "should only have module decl in modules TS");
  14327. // A module implementation unit requires that we are not compiling a module
  14328. // of any kind. A module interface unit requires that we are not compiling a
  14329. // module map.
  14330. switch (getLangOpts().getCompilingModule()) {
  14331. case LangOptions::CMK_None:
  14332. // It's OK to compile a module interface as a normal translation unit.
  14333. break;
  14334. case LangOptions::CMK_ModuleInterface:
  14335. if (MDK != ModuleDeclKind::Implementation)
  14336. break;
  14337. // We were asked to compile a module interface unit but this is a module
  14338. // implementation unit. That indicates the 'export' is missing.
  14339. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  14340. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  14341. MDK = ModuleDeclKind::Interface;
  14342. break;
  14343. case LangOptions::CMK_ModuleMap:
  14344. Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
  14345. return nullptr;
  14346. }
  14347. assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
  14348. // FIXME: Most of this work should be done by the preprocessor rather than
  14349. // here, in order to support macro import.
  14350. // Only one module-declaration is permitted per source file.
  14351. if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
  14352. Diag(ModuleLoc, diag::err_module_redeclaration);
  14353. Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
  14354. diag::note_prev_module_declaration);
  14355. return nullptr;
  14356. }
  14357. // Flatten the dots in a module name. Unlike Clang's hierarchical module map
  14358. // modules, the dots here are just another character that can appear in a
  14359. // module name.
  14360. std::string ModuleName;
  14361. for (auto &Piece : Path) {
  14362. if (!ModuleName.empty())
  14363. ModuleName += ".";
  14364. ModuleName += Piece.first->getName();
  14365. }
  14366. // If a module name was explicitly specified on the command line, it must be
  14367. // correct.
  14368. if (!getLangOpts().CurrentModule.empty() &&
  14369. getLangOpts().CurrentModule != ModuleName) {
  14370. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  14371. << SourceRange(Path.front().second, Path.back().second)
  14372. << getLangOpts().CurrentModule;
  14373. return nullptr;
  14374. }
  14375. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  14376. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  14377. Module *Mod;
  14378. switch (MDK) {
  14379. case ModuleDeclKind::Interface: {
  14380. // We can't have parsed or imported a definition of this module or parsed a
  14381. // module map defining it already.
  14382. if (auto *M = Map.findModule(ModuleName)) {
  14383. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  14384. if (M->DefinitionLoc.isValid())
  14385. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  14386. else if (const auto *FE = M->getASTFile())
  14387. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  14388. << FE->getName();
  14389. Mod = M;
  14390. break;
  14391. }
  14392. // Create a Module for the module that we're defining.
  14393. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14394. ModuleScopes.front().Module);
  14395. assert(Mod && "module creation should not fail");
  14396. break;
  14397. }
  14398. case ModuleDeclKind::Partition:
  14399. // FIXME: Check we are in a submodule of the named module.
  14400. return nullptr;
  14401. case ModuleDeclKind::Implementation:
  14402. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  14403. PP.getIdentifierInfo(ModuleName), Path[0].second);
  14404. Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
  14405. /*IsIncludeDirective=*/false);
  14406. if (!Mod) {
  14407. Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
  14408. // Create an empty module interface unit for error recovery.
  14409. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14410. ModuleScopes.front().Module);
  14411. }
  14412. break;
  14413. }
  14414. // Switch from the global module to the named module.
  14415. ModuleScopes.back().Module = Mod;
  14416. ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
  14417. VisibleModules.setVisible(Mod, ModuleLoc);
  14418. // From now on, we have an owning module for all declarations we see.
  14419. // However, those declarations are module-private unless explicitly
  14420. // exported.
  14421. auto *TU = Context.getTranslationUnitDecl();
  14422. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  14423. TU->setLocalOwningModule(Mod);
  14424. // FIXME: Create a ModuleDecl.
  14425. return nullptr;
  14426. }
  14427. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  14428. SourceLocation ImportLoc,
  14429. ModuleIdPath Path) {
  14430. Module *Mod =
  14431. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  14432. /*IsIncludeDirective=*/false);
  14433. if (!Mod)
  14434. return true;
  14435. VisibleModules.setVisible(Mod, ImportLoc);
  14436. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  14437. // FIXME: we should support importing a submodule within a different submodule
  14438. // of the same top-level module. Until we do, make it an error rather than
  14439. // silently ignoring the import.
  14440. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  14441. // warn on a redundant import of the current module?
  14442. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  14443. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  14444. Diag(ImportLoc, getLangOpts().isCompilingModule()
  14445. ? diag::err_module_self_import
  14446. : diag::err_module_import_in_implementation)
  14447. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  14448. SmallVector<SourceLocation, 2> IdentifierLocs;
  14449. Module *ModCheck = Mod;
  14450. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  14451. // If we've run out of module parents, just drop the remaining identifiers.
  14452. // We need the length to be consistent.
  14453. if (!ModCheck)
  14454. break;
  14455. ModCheck = ModCheck->Parent;
  14456. IdentifierLocs.push_back(Path[I].second);
  14457. }
  14458. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14459. ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
  14460. Mod, IdentifierLocs);
  14461. if (!ModuleScopes.empty())
  14462. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  14463. TU->addDecl(Import);
  14464. return Import;
  14465. }
  14466. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14467. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14468. BuildModuleInclude(DirectiveLoc, Mod);
  14469. }
  14470. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14471. // Determine whether we're in the #include buffer for a module. The #includes
  14472. // in that buffer do not qualify as module imports; they're just an
  14473. // implementation detail of us building the module.
  14474. //
  14475. // FIXME: Should we even get ActOnModuleInclude calls for those?
  14476. bool IsInModuleIncludes =
  14477. TUKind == TU_Module &&
  14478. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  14479. bool ShouldAddImport = !IsInModuleIncludes;
  14480. // If this module import was due to an inclusion directive, create an
  14481. // implicit import declaration to capture it in the AST.
  14482. if (ShouldAddImport) {
  14483. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14484. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14485. DirectiveLoc, Mod,
  14486. DirectiveLoc);
  14487. if (!ModuleScopes.empty())
  14488. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  14489. TU->addDecl(ImportD);
  14490. Consumer.HandleImplicitImportDecl(ImportD);
  14491. }
  14492. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  14493. VisibleModules.setVisible(Mod, DirectiveLoc);
  14494. }
  14495. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  14496. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14497. ModuleScopes.push_back({});
  14498. ModuleScopes.back().Module = Mod;
  14499. if (getLangOpts().ModulesLocalVisibility)
  14500. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  14501. VisibleModules.setVisible(Mod, DirectiveLoc);
  14502. // The enclosing context is now part of this module.
  14503. // FIXME: Consider creating a child DeclContext to hold the entities
  14504. // lexically within the module.
  14505. if (getLangOpts().trackLocalOwningModule()) {
  14506. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14507. cast<Decl>(DC)->setModuleOwnershipKind(
  14508. getLangOpts().ModulesLocalVisibility
  14509. ? Decl::ModuleOwnershipKind::VisibleWhenImported
  14510. : Decl::ModuleOwnershipKind::Visible);
  14511. cast<Decl>(DC)->setLocalOwningModule(Mod);
  14512. }
  14513. }
  14514. }
  14515. void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
  14516. if (getLangOpts().ModulesLocalVisibility) {
  14517. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  14518. // Leaving a module hides namespace names, so our visible namespace cache
  14519. // is now out of date.
  14520. VisibleNamespaceCache.clear();
  14521. }
  14522. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  14523. "left the wrong module scope");
  14524. ModuleScopes.pop_back();
  14525. // We got to the end of processing a local module. Create an
  14526. // ImportDecl as we would for an imported module.
  14527. FileID File = getSourceManager().getFileID(EomLoc);
  14528. SourceLocation DirectiveLoc;
  14529. if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
  14530. // We reached the end of a #included module header. Use the #include loc.
  14531. assert(File != getSourceManager().getMainFileID() &&
  14532. "end of submodule in main source file");
  14533. DirectiveLoc = getSourceManager().getIncludeLoc(File);
  14534. } else {
  14535. // We reached an EOM pragma. Use the pragma location.
  14536. DirectiveLoc = EomLoc;
  14537. }
  14538. BuildModuleInclude(DirectiveLoc, Mod);
  14539. // Any further declarations are in whatever module we returned to.
  14540. if (getLangOpts().trackLocalOwningModule()) {
  14541. // The parser guarantees that this is the same context that we entered
  14542. // the module within.
  14543. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14544. cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
  14545. if (!getCurrentModule())
  14546. cast<Decl>(DC)->setModuleOwnershipKind(
  14547. Decl::ModuleOwnershipKind::Unowned);
  14548. }
  14549. }
  14550. }
  14551. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  14552. Module *Mod) {
  14553. // Bail if we're not allowed to implicitly import a module here.
  14554. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
  14555. VisibleModules.isVisible(Mod))
  14556. return;
  14557. // Create the implicit import declaration.
  14558. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14559. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14560. Loc, Mod, Loc);
  14561. TU->addDecl(ImportD);
  14562. Consumer.HandleImplicitImportDecl(ImportD);
  14563. // Make the module visible.
  14564. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  14565. VisibleModules.setVisible(Mod, Loc);
  14566. }
  14567. /// We have parsed the start of an export declaration, including the '{'
  14568. /// (if present).
  14569. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  14570. SourceLocation LBraceLoc) {
  14571. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  14572. // C++ Modules TS draft:
  14573. // An export-declaration shall appear in the purview of a module other than
  14574. // the global module.
  14575. if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
  14576. Diag(ExportLoc, diag::err_export_not_in_module_interface);
  14577. // An export-declaration [...] shall not contain more than one
  14578. // export keyword.
  14579. //
  14580. // The intent here is that an export-declaration cannot appear within another
  14581. // export-declaration.
  14582. if (D->isExported())
  14583. Diag(ExportLoc, diag::err_export_within_export);
  14584. CurContext->addDecl(D);
  14585. PushDeclContext(S, D);
  14586. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  14587. return D;
  14588. }
  14589. /// Complete the definition of an export declaration.
  14590. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  14591. auto *ED = cast<ExportDecl>(D);
  14592. if (RBraceLoc.isValid())
  14593. ED->setRBraceLoc(RBraceLoc);
  14594. // FIXME: Diagnose export of internal-linkage declaration (including
  14595. // anonymous namespace).
  14596. PopDeclContext();
  14597. return D;
  14598. }
  14599. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  14600. IdentifierInfo* AliasName,
  14601. SourceLocation PragmaLoc,
  14602. SourceLocation NameLoc,
  14603. SourceLocation AliasNameLoc) {
  14604. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  14605. LookupOrdinaryName);
  14606. AsmLabelAttr *Attr =
  14607. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  14608. // If a declaration that:
  14609. // 1) declares a function or a variable
  14610. // 2) has external linkage
  14611. // already exists, add a label attribute to it.
  14612. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14613. if (isDeclExternC(PrevDecl))
  14614. PrevDecl->addAttr(Attr);
  14615. else
  14616. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  14617. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  14618. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  14619. } else
  14620. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  14621. }
  14622. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  14623. SourceLocation PragmaLoc,
  14624. SourceLocation NameLoc) {
  14625. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  14626. if (PrevDecl) {
  14627. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  14628. } else {
  14629. (void)WeakUndeclaredIdentifiers.insert(
  14630. std::pair<IdentifierInfo*,WeakInfo>
  14631. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  14632. }
  14633. }
  14634. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  14635. IdentifierInfo* AliasName,
  14636. SourceLocation PragmaLoc,
  14637. SourceLocation NameLoc,
  14638. SourceLocation AliasNameLoc) {
  14639. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  14640. LookupOrdinaryName);
  14641. WeakInfo W = WeakInfo(Name, NameLoc);
  14642. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14643. if (!PrevDecl->hasAttr<AliasAttr>())
  14644. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  14645. DeclApplyPragmaWeak(TUScope, ND, W);
  14646. } else {
  14647. (void)WeakUndeclaredIdentifiers.insert(
  14648. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  14649. }
  14650. }
  14651. Decl *Sema::getObjCDeclContext() const {
  14652. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  14653. }