SemaDecl.cpp 637 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424
  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. static bool isUsingDecl(NamedDecl *D) {
  1280. return isa<UsingShadowDecl>(D) ||
  1281. isa<UnresolvedUsingTypenameDecl>(D) ||
  1282. isa<UnresolvedUsingValueDecl>(D);
  1283. }
  1284. /// Removes using shadow declarations from the lookup results.
  1285. static void RemoveUsingDecls(LookupResult &R) {
  1286. LookupResult::Filter F = R.makeFilter();
  1287. while (F.hasNext())
  1288. if (isUsingDecl(F.next()))
  1289. F.erase();
  1290. F.done();
  1291. }
  1292. /// \brief Check for this common pattern:
  1293. /// @code
  1294. /// class S {
  1295. /// S(const S&); // DO NOT IMPLEMENT
  1296. /// void operator=(const S&); // DO NOT IMPLEMENT
  1297. /// };
  1298. /// @endcode
  1299. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1300. // FIXME: Should check for private access too but access is set after we get
  1301. // the decl here.
  1302. if (D->doesThisDeclarationHaveABody())
  1303. return false;
  1304. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1305. return CD->isCopyConstructor();
  1306. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
  1307. return Method->isCopyAssignmentOperator();
  1308. return false;
  1309. }
  1310. // We need this to handle
  1311. //
  1312. // typedef struct {
  1313. // void *foo() { return 0; }
  1314. // } A;
  1315. //
  1316. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1317. // for example. If 'A', foo will have external linkage. If we have '*A',
  1318. // foo will have no linkage. Since we can't know until we get to the end
  1319. // of the typedef, this function finds out if D might have non-external linkage.
  1320. // Callers should verify at the end of the TU if it D has external linkage or
  1321. // not.
  1322. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1323. const DeclContext *DC = D->getDeclContext();
  1324. while (!DC->isTranslationUnit()) {
  1325. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1326. if (!RD->hasNameForLinkage())
  1327. return true;
  1328. }
  1329. DC = DC->getParent();
  1330. }
  1331. return !D->isExternallyVisible();
  1332. }
  1333. // FIXME: This needs to be refactored; some other isInMainFile users want
  1334. // these semantics.
  1335. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1336. if (S.TUKind != TU_Complete)
  1337. return false;
  1338. return S.SourceMgr.isInMainFile(Loc);
  1339. }
  1340. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1341. assert(D);
  1342. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1343. return false;
  1344. // Ignore all entities declared within templates, and out-of-line definitions
  1345. // of members of class templates.
  1346. if (D->getDeclContext()->isDependentContext() ||
  1347. D->getLexicalDeclContext()->isDependentContext())
  1348. return false;
  1349. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1350. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1351. return false;
  1352. // A non-out-of-line declaration of a member specialization was implicitly
  1353. // instantiated; it's the out-of-line declaration that we're interested in.
  1354. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1355. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1356. return false;
  1357. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1358. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1359. return false;
  1360. } else {
  1361. // 'static inline' functions are defined in headers; don't warn.
  1362. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1363. return false;
  1364. }
  1365. if (FD->doesThisDeclarationHaveABody() &&
  1366. Context.DeclMustBeEmitted(FD))
  1367. return false;
  1368. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1369. // Constants and utility variables are defined in headers with internal
  1370. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1371. // like "inline".)
  1372. if (!isMainFileLoc(*this, VD->getLocation()))
  1373. return false;
  1374. if (Context.DeclMustBeEmitted(VD))
  1375. return false;
  1376. if (VD->isStaticDataMember() &&
  1377. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1378. return false;
  1379. if (VD->isStaticDataMember() &&
  1380. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1381. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1382. return false;
  1383. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1384. return false;
  1385. } else {
  1386. return false;
  1387. }
  1388. // Only warn for unused decls internal to the translation unit.
  1389. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1390. // for inline functions defined in the main source file, for instance.
  1391. return mightHaveNonExternalLinkage(D);
  1392. }
  1393. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1394. if (!D)
  1395. return;
  1396. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1397. const FunctionDecl *First = FD->getFirstDecl();
  1398. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1399. return; // First should already be in the vector.
  1400. }
  1401. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1402. const VarDecl *First = VD->getFirstDecl();
  1403. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1404. return; // First should already be in the vector.
  1405. }
  1406. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1407. UnusedFileScopedDecls.push_back(D);
  1408. }
  1409. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1410. if (D->isInvalidDecl())
  1411. return false;
  1412. if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
  1413. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1414. return false;
  1415. if (isa<LabelDecl>(D))
  1416. return true;
  1417. // Except for labels, we only care about unused decls that are local to
  1418. // functions.
  1419. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1420. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1421. // For dependent types, the diagnostic is deferred.
  1422. WithinFunction =
  1423. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1424. if (!WithinFunction)
  1425. return false;
  1426. if (isa<TypedefNameDecl>(D))
  1427. return true;
  1428. // White-list anything that isn't a local variable.
  1429. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1430. return false;
  1431. // Types of valid local variables should be complete, so this should succeed.
  1432. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1433. // White-list anything with an __attribute__((unused)) type.
  1434. const auto *Ty = VD->getType().getTypePtr();
  1435. // Only look at the outermost level of typedef.
  1436. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1437. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1438. return false;
  1439. }
  1440. // If we failed to complete the type for some reason, or if the type is
  1441. // dependent, don't diagnose the variable.
  1442. if (Ty->isIncompleteType() || Ty->isDependentType())
  1443. return false;
  1444. // Look at the element type to ensure that the warning behaviour is
  1445. // consistent for both scalars and arrays.
  1446. Ty = Ty->getBaseElementTypeUnsafe();
  1447. if (const TagType *TT = Ty->getAs<TagType>()) {
  1448. const TagDecl *Tag = TT->getDecl();
  1449. if (Tag->hasAttr<UnusedAttr>())
  1450. return false;
  1451. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1452. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1453. return false;
  1454. if (const Expr *Init = VD->getInit()) {
  1455. if (const ExprWithCleanups *Cleanups =
  1456. dyn_cast<ExprWithCleanups>(Init))
  1457. Init = Cleanups->getSubExpr();
  1458. const CXXConstructExpr *Construct =
  1459. dyn_cast<CXXConstructExpr>(Init);
  1460. if (Construct && !Construct->isElidable()) {
  1461. CXXConstructorDecl *CD = Construct->getConstructor();
  1462. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
  1463. return false;
  1464. }
  1465. }
  1466. }
  1467. }
  1468. // TODO: __attribute__((unused)) templates?
  1469. }
  1470. return true;
  1471. }
  1472. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1473. FixItHint &Hint) {
  1474. if (isa<LabelDecl>(D)) {
  1475. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1476. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1477. if (AfterColon.isInvalid())
  1478. return;
  1479. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1480. getCharRange(D->getLocStart(), AfterColon));
  1481. }
  1482. }
  1483. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1484. if (D->getTypeForDecl()->isDependentType())
  1485. return;
  1486. for (auto *TmpD : D->decls()) {
  1487. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1488. DiagnoseUnusedDecl(T);
  1489. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1490. DiagnoseUnusedNestedTypedefs(R);
  1491. }
  1492. }
  1493. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1494. /// unless they are marked attr(unused).
  1495. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1496. if (!ShouldDiagnoseUnusedDecl(D))
  1497. return;
  1498. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1499. // typedefs can be referenced later on, so the diagnostics are emitted
  1500. // at end-of-translation-unit.
  1501. UnusedLocalTypedefNameCandidates.insert(TD);
  1502. return;
  1503. }
  1504. FixItHint Hint;
  1505. GenerateFixForUnusedDecl(D, Context, Hint);
  1506. unsigned DiagID;
  1507. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1508. DiagID = diag::warn_unused_exception_param;
  1509. else if (isa<LabelDecl>(D))
  1510. DiagID = diag::warn_unused_label;
  1511. else
  1512. DiagID = diag::warn_unused_variable;
  1513. Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
  1514. }
  1515. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1516. // Verify that we have no forward references left. If so, there was a goto
  1517. // or address of a label taken, but no definition of it. Label fwd
  1518. // definitions are indicated with a null substmt which is also not a resolved
  1519. // MS inline assembly label name.
  1520. bool Diagnose = false;
  1521. if (L->isMSAsmLabel())
  1522. Diagnose = !L->isResolvedMSAsmLabel();
  1523. else
  1524. Diagnose = L->getStmt() == nullptr;
  1525. if (Diagnose)
  1526. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1527. }
  1528. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1529. S->mergeNRVOIntoParent();
  1530. if (S->decl_empty()) return;
  1531. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1532. "Scope shouldn't contain decls!");
  1533. for (auto *TmpD : S->decls()) {
  1534. assert(TmpD && "This decl didn't get pushed??");
  1535. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1536. NamedDecl *D = cast<NamedDecl>(TmpD);
  1537. if (!D->getDeclName()) continue;
  1538. // Diagnose unused variables in this scope.
  1539. if (!S->hasUnrecoverableErrorOccurred()) {
  1540. DiagnoseUnusedDecl(D);
  1541. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1542. DiagnoseUnusedNestedTypedefs(RD);
  1543. }
  1544. // If this was a forward reference to a label, verify it was defined.
  1545. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1546. CheckPoppedLabel(LD, *this);
  1547. // Remove this name from our lexical scope, and warn on it if we haven't
  1548. // already.
  1549. IdResolver.RemoveDecl(D);
  1550. auto ShadowI = ShadowingDecls.find(D);
  1551. if (ShadowI != ShadowingDecls.end()) {
  1552. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1553. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1554. << D << FD << FD->getParent();
  1555. Diag(FD->getLocation(), diag::note_previous_declaration);
  1556. }
  1557. ShadowingDecls.erase(ShadowI);
  1558. }
  1559. }
  1560. }
  1561. /// \brief Look for an Objective-C class in the translation unit.
  1562. ///
  1563. /// \param Id The name of the Objective-C class we're looking for. If
  1564. /// typo-correction fixes this name, the Id will be updated
  1565. /// to the fixed name.
  1566. ///
  1567. /// \param IdLoc The location of the name in the translation unit.
  1568. ///
  1569. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1570. /// if there is no class with the given name.
  1571. ///
  1572. /// \returns The declaration of the named Objective-C class, or NULL if the
  1573. /// class could not be found.
  1574. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1575. SourceLocation IdLoc,
  1576. bool DoTypoCorrection) {
  1577. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1578. // creation from this context.
  1579. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1580. if (!IDecl && DoTypoCorrection) {
  1581. // Perform typo correction at the given location, but only if we
  1582. // find an Objective-C class name.
  1583. if (TypoCorrection C = CorrectTypo(
  1584. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1585. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1586. CTK_ErrorRecovery)) {
  1587. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1588. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1589. Id = IDecl->getIdentifier();
  1590. }
  1591. }
  1592. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1593. // This routine must always return a class definition, if any.
  1594. if (Def && Def->getDefinition())
  1595. Def = Def->getDefinition();
  1596. return Def;
  1597. }
  1598. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1599. /// from S, where a non-field would be declared. This routine copes
  1600. /// with the difference between C and C++ scoping rules in structs and
  1601. /// unions. For example, the following code is well-formed in C but
  1602. /// ill-formed in C++:
  1603. /// @code
  1604. /// struct S6 {
  1605. /// enum { BAR } e;
  1606. /// };
  1607. ///
  1608. /// void test_S6() {
  1609. /// struct S6 a;
  1610. /// a.e = BAR;
  1611. /// }
  1612. /// @endcode
  1613. /// For the declaration of BAR, this routine will return a different
  1614. /// scope. The scope S will be the scope of the unnamed enumeration
  1615. /// within S6. In C++, this routine will return the scope associated
  1616. /// with S6, because the enumeration's scope is a transparent
  1617. /// context but structures can contain non-field names. In C, this
  1618. /// routine will return the translation unit scope, since the
  1619. /// enumeration's scope is a transparent context and structures cannot
  1620. /// contain non-field names.
  1621. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1622. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1623. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1624. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1625. S = S->getParent();
  1626. return S;
  1627. }
  1628. /// \brief Looks up the declaration of "struct objc_super" and
  1629. /// saves it for later use in building builtin declaration of
  1630. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1631. /// pre-existing declaration exists no action takes place.
  1632. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1633. IdentifierInfo *II) {
  1634. if (!II->isStr("objc_msgSendSuper"))
  1635. return;
  1636. ASTContext &Context = ThisSema.Context;
  1637. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1638. SourceLocation(), Sema::LookupTagName);
  1639. ThisSema.LookupName(Result, S);
  1640. if (Result.getResultKind() == LookupResult::Found)
  1641. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1642. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1643. }
  1644. static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
  1645. switch (Error) {
  1646. case ASTContext::GE_None:
  1647. return "";
  1648. case ASTContext::GE_Missing_stdio:
  1649. return "stdio.h";
  1650. case ASTContext::GE_Missing_setjmp:
  1651. return "setjmp.h";
  1652. case ASTContext::GE_Missing_ucontext:
  1653. return "ucontext.h";
  1654. }
  1655. llvm_unreachable("unhandled error kind");
  1656. }
  1657. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1658. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1659. /// if we're creating this built-in in anticipation of redeclaring the
  1660. /// built-in.
  1661. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1662. Scope *S, bool ForRedeclaration,
  1663. SourceLocation Loc) {
  1664. LookupPredefedObjCSuperType(*this, S, II);
  1665. ASTContext::GetBuiltinTypeError Error;
  1666. QualType R = Context.GetBuiltinType(ID, Error);
  1667. if (Error) {
  1668. if (ForRedeclaration)
  1669. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1670. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1671. return nullptr;
  1672. }
  1673. if (!ForRedeclaration &&
  1674. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1675. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1676. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1677. << Context.BuiltinInfo.getName(ID) << R;
  1678. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1679. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1680. Diag(Loc, diag::note_include_header_or_declare)
  1681. << Context.BuiltinInfo.getHeaderName(ID)
  1682. << Context.BuiltinInfo.getName(ID);
  1683. }
  1684. if (R.isNull())
  1685. return nullptr;
  1686. DeclContext *Parent = Context.getTranslationUnitDecl();
  1687. if (getLangOpts().CPlusPlus) {
  1688. LinkageSpecDecl *CLinkageDecl =
  1689. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1690. LinkageSpecDecl::lang_c, false);
  1691. CLinkageDecl->setImplicit();
  1692. Parent->addDecl(CLinkageDecl);
  1693. Parent = CLinkageDecl;
  1694. }
  1695. FunctionDecl *New = FunctionDecl::Create(Context,
  1696. Parent,
  1697. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1698. SC_Extern,
  1699. false,
  1700. R->isFunctionProtoType());
  1701. New->setImplicit();
  1702. // Create Decl objects for each parameter, adding them to the
  1703. // FunctionDecl.
  1704. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1705. SmallVector<ParmVarDecl*, 16> Params;
  1706. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1707. ParmVarDecl *parm =
  1708. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1709. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1710. SC_None, nullptr);
  1711. parm->setScopeInfo(0, i);
  1712. Params.push_back(parm);
  1713. }
  1714. New->setParams(Params);
  1715. }
  1716. AddKnownFunctionAttributes(New);
  1717. RegisterLocallyScopedExternCDecl(New, S);
  1718. // TUScope is the translation-unit scope to insert this function into.
  1719. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1720. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1721. // entirely, but we're not there yet.
  1722. DeclContext *SavedContext = CurContext;
  1723. CurContext = Parent;
  1724. PushOnScopeChains(New, TUScope);
  1725. CurContext = SavedContext;
  1726. return New;
  1727. }
  1728. /// Typedef declarations don't have linkage, but they still denote the same
  1729. /// entity if their types are the same.
  1730. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1731. /// isSameEntity.
  1732. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1733. TypedefNameDecl *Decl,
  1734. LookupResult &Previous) {
  1735. // This is only interesting when modules are enabled.
  1736. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1737. return;
  1738. // Empty sets are uninteresting.
  1739. if (Previous.empty())
  1740. return;
  1741. LookupResult::Filter Filter = Previous.makeFilter();
  1742. while (Filter.hasNext()) {
  1743. NamedDecl *Old = Filter.next();
  1744. // Non-hidden declarations are never ignored.
  1745. if (S.isVisible(Old))
  1746. continue;
  1747. // Declarations of the same entity are not ignored, even if they have
  1748. // different linkages.
  1749. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1750. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1751. Decl->getUnderlyingType()))
  1752. continue;
  1753. // If both declarations give a tag declaration a typedef name for linkage
  1754. // purposes, then they declare the same entity.
  1755. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1756. Decl->getAnonDeclWithTypedefName())
  1757. continue;
  1758. }
  1759. Filter.erase();
  1760. }
  1761. Filter.done();
  1762. }
  1763. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1764. QualType OldType;
  1765. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1766. OldType = OldTypedef->getUnderlyingType();
  1767. else
  1768. OldType = Context.getTypeDeclType(Old);
  1769. QualType NewType = New->getUnderlyingType();
  1770. if (NewType->isVariablyModifiedType()) {
  1771. // Must not redefine a typedef with a variably-modified type.
  1772. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1773. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1774. << Kind << NewType;
  1775. if (Old->getLocation().isValid())
  1776. notePreviousDefinition(Old, New->getLocation());
  1777. New->setInvalidDecl();
  1778. return true;
  1779. }
  1780. if (OldType != NewType &&
  1781. !OldType->isDependentType() &&
  1782. !NewType->isDependentType() &&
  1783. !Context.hasSameType(OldType, NewType)) {
  1784. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1785. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1786. << Kind << NewType << OldType;
  1787. if (Old->getLocation().isValid())
  1788. notePreviousDefinition(Old, New->getLocation());
  1789. New->setInvalidDecl();
  1790. return true;
  1791. }
  1792. return false;
  1793. }
  1794. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1795. /// same name and scope as a previous declaration 'Old'. Figure out
  1796. /// how to resolve this situation, merging decls or emitting
  1797. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1798. ///
  1799. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1800. LookupResult &OldDecls) {
  1801. // If the new decl is known invalid already, don't bother doing any
  1802. // merging checks.
  1803. if (New->isInvalidDecl()) return;
  1804. // Allow multiple definitions for ObjC built-in typedefs.
  1805. // FIXME: Verify the underlying types are equivalent!
  1806. if (getLangOpts().ObjC1) {
  1807. const IdentifierInfo *TypeID = New->getIdentifier();
  1808. switch (TypeID->getLength()) {
  1809. default: break;
  1810. case 2:
  1811. {
  1812. if (!TypeID->isStr("id"))
  1813. break;
  1814. QualType T = New->getUnderlyingType();
  1815. if (!T->isPointerType())
  1816. break;
  1817. if (!T->isVoidPointerType()) {
  1818. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1819. if (!PT->isStructureType())
  1820. break;
  1821. }
  1822. Context.setObjCIdRedefinitionType(T);
  1823. // Install the built-in type for 'id', ignoring the current definition.
  1824. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1825. return;
  1826. }
  1827. case 5:
  1828. if (!TypeID->isStr("Class"))
  1829. break;
  1830. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1831. // Install the built-in type for 'Class', ignoring the current definition.
  1832. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1833. return;
  1834. case 3:
  1835. if (!TypeID->isStr("SEL"))
  1836. break;
  1837. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1838. // Install the built-in type for 'SEL', ignoring the current definition.
  1839. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1840. return;
  1841. }
  1842. // Fall through - the typedef name was not a builtin type.
  1843. }
  1844. // Verify the old decl was also a type.
  1845. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1846. if (!Old) {
  1847. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1848. << New->getDeclName();
  1849. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1850. if (OldD->getLocation().isValid())
  1851. notePreviousDefinition(OldD, New->getLocation());
  1852. return New->setInvalidDecl();
  1853. }
  1854. // If the old declaration is invalid, just give up here.
  1855. if (Old->isInvalidDecl())
  1856. return New->setInvalidDecl();
  1857. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1858. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1859. auto *NewTag = New->getAnonDeclWithTypedefName();
  1860. NamedDecl *Hidden = nullptr;
  1861. if (OldTag && NewTag &&
  1862. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1863. !hasVisibleDefinition(OldTag, &Hidden)) {
  1864. // There is a definition of this tag, but it is not visible. Use it
  1865. // instead of our tag.
  1866. New->setTypeForDecl(OldTD->getTypeForDecl());
  1867. if (OldTD->isModed())
  1868. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1869. OldTD->getUnderlyingType());
  1870. else
  1871. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1872. // Make the old tag definition visible.
  1873. makeMergedDefinitionVisible(Hidden);
  1874. // If this was an unscoped enumeration, yank all of its enumerators
  1875. // out of the scope.
  1876. if (isa<EnumDecl>(NewTag)) {
  1877. Scope *EnumScope = getNonFieldDeclScope(S);
  1878. for (auto *D : NewTag->decls()) {
  1879. auto *ED = cast<EnumConstantDecl>(D);
  1880. assert(EnumScope->isDeclScope(ED));
  1881. EnumScope->RemoveDecl(ED);
  1882. IdResolver.RemoveDecl(ED);
  1883. ED->getLexicalDeclContext()->removeDecl(ED);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. // If the typedef types are not identical, reject them in all languages and
  1889. // with any extensions enabled.
  1890. if (isIncompatibleTypedef(Old, New))
  1891. return;
  1892. // The types match. Link up the redeclaration chain and merge attributes if
  1893. // the old declaration was a typedef.
  1894. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1895. New->setPreviousDecl(Typedef);
  1896. mergeDeclAttributes(New, Old);
  1897. }
  1898. if (getLangOpts().MicrosoftExt)
  1899. return;
  1900. if (getLangOpts().CPlusPlus) {
  1901. // C++ [dcl.typedef]p2:
  1902. // In a given non-class scope, a typedef specifier can be used to
  1903. // redefine the name of any type declared in that scope to refer
  1904. // to the type to which it already refers.
  1905. if (!isa<CXXRecordDecl>(CurContext))
  1906. return;
  1907. // C++0x [dcl.typedef]p4:
  1908. // In a given class scope, a typedef specifier can be used to redefine
  1909. // any class-name declared in that scope that is not also a typedef-name
  1910. // to refer to the type to which it already refers.
  1911. //
  1912. // This wording came in via DR424, which was a correction to the
  1913. // wording in DR56, which accidentally banned code like:
  1914. //
  1915. // struct S {
  1916. // typedef struct A { } A;
  1917. // };
  1918. //
  1919. // in the C++03 standard. We implement the C++0x semantics, which
  1920. // allow the above but disallow
  1921. //
  1922. // struct S {
  1923. // typedef int I;
  1924. // typedef int I;
  1925. // };
  1926. //
  1927. // since that was the intent of DR56.
  1928. if (!isa<TypedefNameDecl>(Old))
  1929. return;
  1930. Diag(New->getLocation(), diag::err_redefinition)
  1931. << New->getDeclName();
  1932. notePreviousDefinition(Old, New->getLocation());
  1933. return New->setInvalidDecl();
  1934. }
  1935. // Modules always permit redefinition of typedefs, as does C11.
  1936. if (getLangOpts().Modules || getLangOpts().C11)
  1937. return;
  1938. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1939. // is normally mapped to an error, but can be controlled with
  1940. // -Wtypedef-redefinition. If either the original or the redefinition is
  1941. // in a system header, don't emit this for compatibility with GCC.
  1942. if (getDiagnostics().getSuppressSystemWarnings() &&
  1943. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  1944. (Old->isImplicit() ||
  1945. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1946. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1947. return;
  1948. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1949. << New->getDeclName();
  1950. notePreviousDefinition(Old, New->getLocation());
  1951. }
  1952. /// DeclhasAttr - returns true if decl Declaration already has the target
  1953. /// attribute.
  1954. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  1955. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  1956. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  1957. for (const auto *i : D->attrs())
  1958. if (i->getKind() == A->getKind()) {
  1959. if (Ann) {
  1960. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  1961. return true;
  1962. continue;
  1963. }
  1964. // FIXME: Don't hardcode this check
  1965. if (OA && isa<OwnershipAttr>(i))
  1966. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  1967. return true;
  1968. }
  1969. return false;
  1970. }
  1971. static bool isAttributeTargetADefinition(Decl *D) {
  1972. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  1973. return VD->isThisDeclarationADefinition();
  1974. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  1975. return TD->isCompleteDefinition() || TD->isBeingDefined();
  1976. return true;
  1977. }
  1978. /// Merge alignment attributes from \p Old to \p New, taking into account the
  1979. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  1980. ///
  1981. /// \return \c true if any attributes were added to \p New.
  1982. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  1983. // Look for alignas attributes on Old, and pick out whichever attribute
  1984. // specifies the strictest alignment requirement.
  1985. AlignedAttr *OldAlignasAttr = nullptr;
  1986. AlignedAttr *OldStrictestAlignAttr = nullptr;
  1987. unsigned OldAlign = 0;
  1988. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  1989. // FIXME: We have no way of representing inherited dependent alignments
  1990. // in a case like:
  1991. // template<int A, int B> struct alignas(A) X;
  1992. // template<int A, int B> struct alignas(B) X {};
  1993. // For now, we just ignore any alignas attributes which are not on the
  1994. // definition in such a case.
  1995. if (I->isAlignmentDependent())
  1996. return false;
  1997. if (I->isAlignas())
  1998. OldAlignasAttr = I;
  1999. unsigned Align = I->getAlignment(S.Context);
  2000. if (Align > OldAlign) {
  2001. OldAlign = Align;
  2002. OldStrictestAlignAttr = I;
  2003. }
  2004. }
  2005. // Look for alignas attributes on New.
  2006. AlignedAttr *NewAlignasAttr = nullptr;
  2007. unsigned NewAlign = 0;
  2008. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2009. if (I->isAlignmentDependent())
  2010. return false;
  2011. if (I->isAlignas())
  2012. NewAlignasAttr = I;
  2013. unsigned Align = I->getAlignment(S.Context);
  2014. if (Align > NewAlign)
  2015. NewAlign = Align;
  2016. }
  2017. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2018. // Both declarations have 'alignas' attributes. We require them to match.
  2019. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2020. // fall short. (If two declarations both have alignas, they must both match
  2021. // every definition, and so must match each other if there is a definition.)
  2022. // If either declaration only contains 'alignas(0)' specifiers, then it
  2023. // specifies the natural alignment for the type.
  2024. if (OldAlign == 0 || NewAlign == 0) {
  2025. QualType Ty;
  2026. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2027. Ty = VD->getType();
  2028. else
  2029. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2030. if (OldAlign == 0)
  2031. OldAlign = S.Context.getTypeAlign(Ty);
  2032. if (NewAlign == 0)
  2033. NewAlign = S.Context.getTypeAlign(Ty);
  2034. }
  2035. if (OldAlign != NewAlign) {
  2036. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2037. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2038. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2039. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2040. }
  2041. }
  2042. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2043. // C++11 [dcl.align]p6:
  2044. // if any declaration of an entity has an alignment-specifier,
  2045. // every defining declaration of that entity shall specify an
  2046. // equivalent alignment.
  2047. // C11 6.7.5/7:
  2048. // If the definition of an object does not have an alignment
  2049. // specifier, any other declaration of that object shall also
  2050. // have no alignment specifier.
  2051. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2052. << OldAlignasAttr;
  2053. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2054. << OldAlignasAttr;
  2055. }
  2056. bool AnyAdded = false;
  2057. // Ensure we have an attribute representing the strictest alignment.
  2058. if (OldAlign > NewAlign) {
  2059. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2060. Clone->setInherited(true);
  2061. New->addAttr(Clone);
  2062. AnyAdded = true;
  2063. }
  2064. // Ensure we have an alignas attribute if the old declaration had one.
  2065. if (OldAlignasAttr && !NewAlignasAttr &&
  2066. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2067. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2068. Clone->setInherited(true);
  2069. New->addAttr(Clone);
  2070. AnyAdded = true;
  2071. }
  2072. return AnyAdded;
  2073. }
  2074. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2075. const InheritableAttr *Attr,
  2076. Sema::AvailabilityMergeKind AMK) {
  2077. // This function copies an attribute Attr from a previous declaration to the
  2078. // new declaration D if the new declaration doesn't itself have that attribute
  2079. // yet or if that attribute allows duplicates.
  2080. // If you're adding a new attribute that requires logic different from
  2081. // "use explicit attribute on decl if present, else use attribute from
  2082. // previous decl", for example if the attribute needs to be consistent
  2083. // between redeclarations, you need to call a custom merge function here.
  2084. InheritableAttr *NewAttr = nullptr;
  2085. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2086. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2087. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  2088. AA->isImplicit(), AA->getIntroduced(),
  2089. AA->getDeprecated(),
  2090. AA->getObsoleted(), AA->getUnavailable(),
  2091. AA->getMessage(), AA->getStrict(),
  2092. AA->getReplacement(), AMK,
  2093. AttrSpellingListIndex);
  2094. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2095. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2096. AttrSpellingListIndex);
  2097. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2098. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2099. AttrSpellingListIndex);
  2100. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2101. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2102. AttrSpellingListIndex);
  2103. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2104. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2105. AttrSpellingListIndex);
  2106. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2107. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2108. FA->getFormatIdx(), FA->getFirstArg(),
  2109. AttrSpellingListIndex);
  2110. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2111. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2112. AttrSpellingListIndex);
  2113. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2114. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2115. AttrSpellingListIndex,
  2116. IA->getSemanticSpelling());
  2117. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2118. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2119. &S.Context.Idents.get(AA->getSpelling()),
  2120. AttrSpellingListIndex);
  2121. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2122. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2123. isa<CUDAGlobalAttr>(Attr))) {
  2124. // CUDA target attributes are part of function signature for
  2125. // overloading purposes and must not be merged.
  2126. return false;
  2127. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2128. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2129. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2130. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2131. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2132. NewAttr = S.mergeInternalLinkageAttr(
  2133. D, InternalLinkageA->getRange(),
  2134. &S.Context.Idents.get(InternalLinkageA->getSpelling()),
  2135. AttrSpellingListIndex);
  2136. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2137. NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
  2138. &S.Context.Idents.get(CommonA->getSpelling()),
  2139. AttrSpellingListIndex);
  2140. else if (isa<AlignedAttr>(Attr))
  2141. // AlignedAttrs are handled separately, because we need to handle all
  2142. // such attributes on a declaration at the same time.
  2143. NewAttr = nullptr;
  2144. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2145. (AMK == Sema::AMK_Override ||
  2146. AMK == Sema::AMK_ProtocolImplementation))
  2147. NewAttr = nullptr;
  2148. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2149. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2150. UA->getGuid());
  2151. else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
  2152. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2153. if (NewAttr) {
  2154. NewAttr->setInherited(true);
  2155. D->addAttr(NewAttr);
  2156. if (isa<MSInheritanceAttr>(NewAttr))
  2157. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2158. return true;
  2159. }
  2160. return false;
  2161. }
  2162. static const NamedDecl *getDefinition(const Decl *D) {
  2163. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2164. return TD->getDefinition();
  2165. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2166. const VarDecl *Def = VD->getDefinition();
  2167. if (Def)
  2168. return Def;
  2169. return VD->getActingDefinition();
  2170. }
  2171. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2172. return FD->getDefinition();
  2173. return nullptr;
  2174. }
  2175. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2176. for (const auto *Attribute : D->attrs())
  2177. if (Attribute->getKind() == Kind)
  2178. return true;
  2179. return false;
  2180. }
  2181. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2182. /// there are no new attributes in this declaration.
  2183. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2184. if (!New->hasAttrs())
  2185. return;
  2186. const NamedDecl *Def = getDefinition(Old);
  2187. if (!Def || Def == New)
  2188. return;
  2189. AttrVec &NewAttributes = New->getAttrs();
  2190. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2191. const Attr *NewAttribute = NewAttributes[I];
  2192. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2193. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2194. Sema::SkipBodyInfo SkipBody;
  2195. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2196. // If we're skipping this definition, drop the "alias" attribute.
  2197. if (SkipBody.ShouldSkip) {
  2198. NewAttributes.erase(NewAttributes.begin() + I);
  2199. --E;
  2200. continue;
  2201. }
  2202. } else {
  2203. VarDecl *VD = cast<VarDecl>(New);
  2204. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2205. VarDecl::TentativeDefinition
  2206. ? diag::err_alias_after_tentative
  2207. : diag::err_redefinition;
  2208. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2209. if (Diag == diag::err_redefinition)
  2210. S.notePreviousDefinition(Def, VD->getLocation());
  2211. else
  2212. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2213. VD->setInvalidDecl();
  2214. }
  2215. ++I;
  2216. continue;
  2217. }
  2218. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2219. // Tentative definitions are only interesting for the alias check above.
  2220. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2221. ++I;
  2222. continue;
  2223. }
  2224. }
  2225. if (hasAttribute(Def, NewAttribute->getKind())) {
  2226. ++I;
  2227. continue; // regular attr merging will take care of validating this.
  2228. }
  2229. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2230. // C's _Noreturn is allowed to be added to a function after it is defined.
  2231. ++I;
  2232. continue;
  2233. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2234. if (AA->isAlignas()) {
  2235. // C++11 [dcl.align]p6:
  2236. // if any declaration of an entity has an alignment-specifier,
  2237. // every defining declaration of that entity shall specify an
  2238. // equivalent alignment.
  2239. // C11 6.7.5/7:
  2240. // If the definition of an object does not have an alignment
  2241. // specifier, any other declaration of that object shall also
  2242. // have no alignment specifier.
  2243. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2244. << AA;
  2245. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2246. << AA;
  2247. NewAttributes.erase(NewAttributes.begin() + I);
  2248. --E;
  2249. continue;
  2250. }
  2251. }
  2252. S.Diag(NewAttribute->getLocation(),
  2253. diag::warn_attribute_precede_definition);
  2254. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2255. NewAttributes.erase(NewAttributes.begin() + I);
  2256. --E;
  2257. }
  2258. }
  2259. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2260. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2261. AvailabilityMergeKind AMK) {
  2262. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2263. UsedAttr *NewAttr = OldAttr->clone(Context);
  2264. NewAttr->setInherited(true);
  2265. New->addAttr(NewAttr);
  2266. }
  2267. if (!Old->hasAttrs() && !New->hasAttrs())
  2268. return;
  2269. // Attributes declared post-definition are currently ignored.
  2270. checkNewAttributesAfterDef(*this, New, Old);
  2271. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2272. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2273. if (OldA->getLabel() != NewA->getLabel()) {
  2274. // This redeclaration changes __asm__ label.
  2275. Diag(New->getLocation(), diag::err_different_asm_label);
  2276. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2277. }
  2278. } else if (Old->isUsed()) {
  2279. // This redeclaration adds an __asm__ label to a declaration that has
  2280. // already been ODR-used.
  2281. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2282. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2283. }
  2284. }
  2285. // Re-declaration cannot add abi_tag's.
  2286. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2287. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2288. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2289. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2290. NewTag) == OldAbiTagAttr->tags_end()) {
  2291. Diag(NewAbiTagAttr->getLocation(),
  2292. diag::err_new_abi_tag_on_redeclaration)
  2293. << NewTag;
  2294. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2295. }
  2296. }
  2297. } else {
  2298. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2299. Diag(Old->getLocation(), diag::note_previous_declaration);
  2300. }
  2301. }
  2302. if (!Old->hasAttrs())
  2303. return;
  2304. bool foundAny = New->hasAttrs();
  2305. // Ensure that any moving of objects within the allocated map is done before
  2306. // we process them.
  2307. if (!foundAny) New->setAttrs(AttrVec());
  2308. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2309. // Ignore deprecated/unavailable/availability attributes if requested.
  2310. AvailabilityMergeKind LocalAMK = AMK_None;
  2311. if (isa<DeprecatedAttr>(I) ||
  2312. isa<UnavailableAttr>(I) ||
  2313. isa<AvailabilityAttr>(I)) {
  2314. switch (AMK) {
  2315. case AMK_None:
  2316. continue;
  2317. case AMK_Redeclaration:
  2318. case AMK_Override:
  2319. case AMK_ProtocolImplementation:
  2320. LocalAMK = AMK;
  2321. break;
  2322. }
  2323. }
  2324. // Already handled.
  2325. if (isa<UsedAttr>(I))
  2326. continue;
  2327. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2328. foundAny = true;
  2329. }
  2330. if (mergeAlignedAttrs(*this, New, Old))
  2331. foundAny = true;
  2332. if (!foundAny) New->dropAttrs();
  2333. }
  2334. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2335. /// to the new one.
  2336. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2337. const ParmVarDecl *oldDecl,
  2338. Sema &S) {
  2339. // C++11 [dcl.attr.depend]p2:
  2340. // The first declaration of a function shall specify the
  2341. // carries_dependency attribute for its declarator-id if any declaration
  2342. // of the function specifies the carries_dependency attribute.
  2343. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2344. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2345. S.Diag(CDA->getLocation(),
  2346. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2347. // Find the first declaration of the parameter.
  2348. // FIXME: Should we build redeclaration chains for function parameters?
  2349. const FunctionDecl *FirstFD =
  2350. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2351. const ParmVarDecl *FirstVD =
  2352. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2353. S.Diag(FirstVD->getLocation(),
  2354. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2355. }
  2356. if (!oldDecl->hasAttrs())
  2357. return;
  2358. bool foundAny = newDecl->hasAttrs();
  2359. // Ensure that any moving of objects within the allocated map is
  2360. // done before we process them.
  2361. if (!foundAny) newDecl->setAttrs(AttrVec());
  2362. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2363. if (!DeclHasAttr(newDecl, I)) {
  2364. InheritableAttr *newAttr =
  2365. cast<InheritableParamAttr>(I->clone(S.Context));
  2366. newAttr->setInherited(true);
  2367. newDecl->addAttr(newAttr);
  2368. foundAny = true;
  2369. }
  2370. }
  2371. if (!foundAny) newDecl->dropAttrs();
  2372. }
  2373. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2374. const ParmVarDecl *OldParam,
  2375. Sema &S) {
  2376. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2377. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2378. if (*Oldnullability != *Newnullability) {
  2379. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2380. << DiagNullabilityKind(
  2381. *Newnullability,
  2382. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2383. != 0))
  2384. << DiagNullabilityKind(
  2385. *Oldnullability,
  2386. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2387. != 0));
  2388. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2389. }
  2390. } else {
  2391. QualType NewT = NewParam->getType();
  2392. NewT = S.Context.getAttributedType(
  2393. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2394. NewT, NewT);
  2395. NewParam->setType(NewT);
  2396. }
  2397. }
  2398. }
  2399. namespace {
  2400. /// Used in MergeFunctionDecl to keep track of function parameters in
  2401. /// C.
  2402. struct GNUCompatibleParamWarning {
  2403. ParmVarDecl *OldParm;
  2404. ParmVarDecl *NewParm;
  2405. QualType PromotedType;
  2406. };
  2407. } // end anonymous namespace
  2408. /// getSpecialMember - get the special member enum for a method.
  2409. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2410. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2411. if (Ctor->isDefaultConstructor())
  2412. return Sema::CXXDefaultConstructor;
  2413. if (Ctor->isCopyConstructor())
  2414. return Sema::CXXCopyConstructor;
  2415. if (Ctor->isMoveConstructor())
  2416. return Sema::CXXMoveConstructor;
  2417. } else if (isa<CXXDestructorDecl>(MD)) {
  2418. return Sema::CXXDestructor;
  2419. } else if (MD->isCopyAssignmentOperator()) {
  2420. return Sema::CXXCopyAssignment;
  2421. } else if (MD->isMoveAssignmentOperator()) {
  2422. return Sema::CXXMoveAssignment;
  2423. }
  2424. return Sema::CXXInvalid;
  2425. }
  2426. // Determine whether the previous declaration was a definition, implicit
  2427. // declaration, or a declaration.
  2428. template <typename T>
  2429. static std::pair<diag::kind, SourceLocation>
  2430. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2431. diag::kind PrevDiag;
  2432. SourceLocation OldLocation = Old->getLocation();
  2433. if (Old->isThisDeclarationADefinition())
  2434. PrevDiag = diag::note_previous_definition;
  2435. else if (Old->isImplicit()) {
  2436. PrevDiag = diag::note_previous_implicit_declaration;
  2437. if (OldLocation.isInvalid())
  2438. OldLocation = New->getLocation();
  2439. } else
  2440. PrevDiag = diag::note_previous_declaration;
  2441. return std::make_pair(PrevDiag, OldLocation);
  2442. }
  2443. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2444. /// only extern inline functions can be redefined, and even then only in
  2445. /// GNU89 mode.
  2446. static bool canRedefineFunction(const FunctionDecl *FD,
  2447. const LangOptions& LangOpts) {
  2448. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2449. !LangOpts.CPlusPlus &&
  2450. FD->isInlineSpecified() &&
  2451. FD->getStorageClass() == SC_Extern);
  2452. }
  2453. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2454. const AttributedType *AT = T->getAs<AttributedType>();
  2455. while (AT && !AT->isCallingConv())
  2456. AT = AT->getModifiedType()->getAs<AttributedType>();
  2457. return AT;
  2458. }
  2459. template <typename T>
  2460. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2461. const DeclContext *DC = Old->getDeclContext();
  2462. if (DC->isRecord())
  2463. return false;
  2464. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2465. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2466. return true;
  2467. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2468. return true;
  2469. return false;
  2470. }
  2471. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2472. static bool isExternC(VarTemplateDecl *) { return false; }
  2473. /// \brief Check whether a redeclaration of an entity introduced by a
  2474. /// using-declaration is valid, given that we know it's not an overload
  2475. /// (nor a hidden tag declaration).
  2476. template<typename ExpectedDecl>
  2477. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2478. ExpectedDecl *New) {
  2479. // C++11 [basic.scope.declarative]p4:
  2480. // Given a set of declarations in a single declarative region, each of
  2481. // which specifies the same unqualified name,
  2482. // -- they shall all refer to the same entity, or all refer to functions
  2483. // and function templates; or
  2484. // -- exactly one declaration shall declare a class name or enumeration
  2485. // name that is not a typedef name and the other declarations shall all
  2486. // refer to the same variable or enumerator, or all refer to functions
  2487. // and function templates; in this case the class name or enumeration
  2488. // name is hidden (3.3.10).
  2489. // C++11 [namespace.udecl]p14:
  2490. // If a function declaration in namespace scope or block scope has the
  2491. // same name and the same parameter-type-list as a function introduced
  2492. // by a using-declaration, and the declarations do not declare the same
  2493. // function, the program is ill-formed.
  2494. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2495. if (Old &&
  2496. !Old->getDeclContext()->getRedeclContext()->Equals(
  2497. New->getDeclContext()->getRedeclContext()) &&
  2498. !(isExternC(Old) && isExternC(New)))
  2499. Old = nullptr;
  2500. if (!Old) {
  2501. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2502. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2503. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2504. return true;
  2505. }
  2506. return false;
  2507. }
  2508. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2509. const FunctionDecl *B) {
  2510. assert(A->getNumParams() == B->getNumParams());
  2511. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2512. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2513. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2514. if (AttrA == AttrB)
  2515. return true;
  2516. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2517. };
  2518. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2519. }
  2520. /// MergeFunctionDecl - We just parsed a function 'New' from
  2521. /// declarator D which has the same name and scope as a previous
  2522. /// declaration 'Old'. Figure out how to resolve this situation,
  2523. /// merging decls or emitting diagnostics as appropriate.
  2524. ///
  2525. /// In C++, New and Old must be declarations that are not
  2526. /// overloaded. Use IsOverload to determine whether New and Old are
  2527. /// overloaded, and to select the Old declaration that New should be
  2528. /// merged with.
  2529. ///
  2530. /// Returns true if there was an error, false otherwise.
  2531. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2532. Scope *S, bool MergeTypeWithOld) {
  2533. // Verify the old decl was also a function.
  2534. FunctionDecl *Old = OldD->getAsFunction();
  2535. if (!Old) {
  2536. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2537. if (New->getFriendObjectKind()) {
  2538. Diag(New->getLocation(), diag::err_using_decl_friend);
  2539. Diag(Shadow->getTargetDecl()->getLocation(),
  2540. diag::note_using_decl_target);
  2541. Diag(Shadow->getUsingDecl()->getLocation(),
  2542. diag::note_using_decl) << 0;
  2543. return true;
  2544. }
  2545. // Check whether the two declarations might declare the same function.
  2546. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2547. return true;
  2548. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2549. } else {
  2550. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2551. << New->getDeclName();
  2552. notePreviousDefinition(OldD, New->getLocation());
  2553. return true;
  2554. }
  2555. }
  2556. // If the old declaration is invalid, just give up here.
  2557. if (Old->isInvalidDecl())
  2558. return true;
  2559. diag::kind PrevDiag;
  2560. SourceLocation OldLocation;
  2561. std::tie(PrevDiag, OldLocation) =
  2562. getNoteDiagForInvalidRedeclaration(Old, New);
  2563. // Don't complain about this if we're in GNU89 mode and the old function
  2564. // is an extern inline function.
  2565. // Don't complain about specializations. They are not supposed to have
  2566. // storage classes.
  2567. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2568. New->getStorageClass() == SC_Static &&
  2569. Old->hasExternalFormalLinkage() &&
  2570. !New->getTemplateSpecializationInfo() &&
  2571. !canRedefineFunction(Old, getLangOpts())) {
  2572. if (getLangOpts().MicrosoftExt) {
  2573. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2574. Diag(OldLocation, PrevDiag);
  2575. } else {
  2576. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2577. Diag(OldLocation, PrevDiag);
  2578. return true;
  2579. }
  2580. }
  2581. if (New->hasAttr<InternalLinkageAttr>() &&
  2582. !Old->hasAttr<InternalLinkageAttr>()) {
  2583. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2584. << New->getDeclName();
  2585. notePreviousDefinition(Old, New->getLocation());
  2586. New->dropAttr<InternalLinkageAttr>();
  2587. }
  2588. if (!getLangOpts().CPlusPlus) {
  2589. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2590. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2591. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2592. << New << OldOvl;
  2593. // Try our best to find a decl that actually has the overloadable
  2594. // attribute for the note. In most cases (e.g. programs with only one
  2595. // broken declaration/definition), this won't matter.
  2596. //
  2597. // FIXME: We could do this if we juggled some extra state in
  2598. // OverloadableAttr, rather than just removing it.
  2599. const Decl *DiagOld = Old;
  2600. if (OldOvl) {
  2601. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2602. const auto *A = D->getAttr<OverloadableAttr>();
  2603. return A && !A->isImplicit();
  2604. });
  2605. // If we've implicitly added *all* of the overloadable attrs to this
  2606. // chain, emitting a "previous redecl" note is pointless.
  2607. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2608. }
  2609. if (DiagOld)
  2610. Diag(DiagOld->getLocation(),
  2611. diag::note_attribute_overloadable_prev_overload)
  2612. << OldOvl;
  2613. if (OldOvl)
  2614. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2615. else
  2616. New->dropAttr<OverloadableAttr>();
  2617. }
  2618. }
  2619. // If a function is first declared with a calling convention, but is later
  2620. // declared or defined without one, all following decls assume the calling
  2621. // convention of the first.
  2622. //
  2623. // It's OK if a function is first declared without a calling convention,
  2624. // but is later declared or defined with the default calling convention.
  2625. //
  2626. // To test if either decl has an explicit calling convention, we look for
  2627. // AttributedType sugar nodes on the type as written. If they are missing or
  2628. // were canonicalized away, we assume the calling convention was implicit.
  2629. //
  2630. // Note also that we DO NOT return at this point, because we still have
  2631. // other tests to run.
  2632. QualType OldQType = Context.getCanonicalType(Old->getType());
  2633. QualType NewQType = Context.getCanonicalType(New->getType());
  2634. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2635. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2636. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2637. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2638. bool RequiresAdjustment = false;
  2639. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2640. FunctionDecl *First = Old->getFirstDecl();
  2641. const FunctionType *FT =
  2642. First->getType().getCanonicalType()->castAs<FunctionType>();
  2643. FunctionType::ExtInfo FI = FT->getExtInfo();
  2644. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2645. if (!NewCCExplicit) {
  2646. // Inherit the CC from the previous declaration if it was specified
  2647. // there but not here.
  2648. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2649. RequiresAdjustment = true;
  2650. } else {
  2651. // Calling conventions aren't compatible, so complain.
  2652. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2653. Diag(New->getLocation(), diag::err_cconv_change)
  2654. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2655. << !FirstCCExplicit
  2656. << (!FirstCCExplicit ? "" :
  2657. FunctionType::getNameForCallConv(FI.getCC()));
  2658. // Put the note on the first decl, since it is the one that matters.
  2659. Diag(First->getLocation(), diag::note_previous_declaration);
  2660. return true;
  2661. }
  2662. }
  2663. // FIXME: diagnose the other way around?
  2664. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2665. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2666. RequiresAdjustment = true;
  2667. }
  2668. // Merge regparm attribute.
  2669. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2670. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2671. if (NewTypeInfo.getHasRegParm()) {
  2672. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2673. << NewType->getRegParmType()
  2674. << OldType->getRegParmType();
  2675. Diag(OldLocation, diag::note_previous_declaration);
  2676. return true;
  2677. }
  2678. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2679. RequiresAdjustment = true;
  2680. }
  2681. // Merge ns_returns_retained attribute.
  2682. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2683. if (NewTypeInfo.getProducesResult()) {
  2684. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2685. << "'ns_returns_retained'";
  2686. Diag(OldLocation, diag::note_previous_declaration);
  2687. return true;
  2688. }
  2689. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2690. RequiresAdjustment = true;
  2691. }
  2692. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2693. NewTypeInfo.getNoCallerSavedRegs()) {
  2694. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2695. AnyX86NoCallerSavedRegistersAttr *Attr =
  2696. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2697. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2698. Diag(OldLocation, diag::note_previous_declaration);
  2699. return true;
  2700. }
  2701. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2702. RequiresAdjustment = true;
  2703. }
  2704. if (RequiresAdjustment) {
  2705. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2706. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2707. New->setType(QualType(AdjustedType, 0));
  2708. NewQType = Context.getCanonicalType(New->getType());
  2709. NewType = cast<FunctionType>(NewQType);
  2710. }
  2711. // If this redeclaration makes the function inline, we may need to add it to
  2712. // UndefinedButUsed.
  2713. if (!Old->isInlined() && New->isInlined() &&
  2714. !New->hasAttr<GNUInlineAttr>() &&
  2715. !getLangOpts().GNUInline &&
  2716. Old->isUsed(false) &&
  2717. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2718. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2719. SourceLocation()));
  2720. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2721. // about it.
  2722. if (New->hasAttr<GNUInlineAttr>() &&
  2723. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2724. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2725. }
  2726. // If pass_object_size params don't match up perfectly, this isn't a valid
  2727. // redeclaration.
  2728. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2729. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2730. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2731. << New->getDeclName();
  2732. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2733. return true;
  2734. }
  2735. if (getLangOpts().CPlusPlus) {
  2736. // C++1z [over.load]p2
  2737. // Certain function declarations cannot be overloaded:
  2738. // -- Function declarations that differ only in the return type,
  2739. // the exception specification, or both cannot be overloaded.
  2740. // Check the exception specifications match. This may recompute the type of
  2741. // both Old and New if it resolved exception specifications, so grab the
  2742. // types again after this. Because this updates the type, we do this before
  2743. // any of the other checks below, which may update the "de facto" NewQType
  2744. // but do not necessarily update the type of New.
  2745. if (CheckEquivalentExceptionSpec(Old, New))
  2746. return true;
  2747. OldQType = Context.getCanonicalType(Old->getType());
  2748. NewQType = Context.getCanonicalType(New->getType());
  2749. // Go back to the type source info to compare the declared return types,
  2750. // per C++1y [dcl.type.auto]p13:
  2751. // Redeclarations or specializations of a function or function template
  2752. // with a declared return type that uses a placeholder type shall also
  2753. // use that placeholder, not a deduced type.
  2754. QualType OldDeclaredReturnType =
  2755. (Old->getTypeSourceInfo()
  2756. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2757. : OldType)->getReturnType();
  2758. QualType NewDeclaredReturnType =
  2759. (New->getTypeSourceInfo()
  2760. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2761. : NewType)->getReturnType();
  2762. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2763. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2764. New->isLocalExternDecl())) {
  2765. QualType ResQT;
  2766. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2767. OldDeclaredReturnType->isObjCObjectPointerType())
  2768. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2769. if (ResQT.isNull()) {
  2770. if (New->isCXXClassMember() && New->isOutOfLine())
  2771. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2772. << New << New->getReturnTypeSourceRange();
  2773. else
  2774. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2775. << New->getReturnTypeSourceRange();
  2776. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2777. << Old->getReturnTypeSourceRange();
  2778. return true;
  2779. }
  2780. else
  2781. NewQType = ResQT;
  2782. }
  2783. QualType OldReturnType = OldType->getReturnType();
  2784. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2785. if (OldReturnType != NewReturnType) {
  2786. // If this function has a deduced return type and has already been
  2787. // defined, copy the deduced value from the old declaration.
  2788. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2789. if (OldAT && OldAT->isDeduced()) {
  2790. New->setType(
  2791. SubstAutoType(New->getType(),
  2792. OldAT->isDependentType() ? Context.DependentTy
  2793. : OldAT->getDeducedType()));
  2794. NewQType = Context.getCanonicalType(
  2795. SubstAutoType(NewQType,
  2796. OldAT->isDependentType() ? Context.DependentTy
  2797. : OldAT->getDeducedType()));
  2798. }
  2799. }
  2800. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2801. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2802. if (OldMethod && NewMethod) {
  2803. // Preserve triviality.
  2804. NewMethod->setTrivial(OldMethod->isTrivial());
  2805. // MSVC allows explicit template specialization at class scope:
  2806. // 2 CXXMethodDecls referring to the same function will be injected.
  2807. // We don't want a redeclaration error.
  2808. bool IsClassScopeExplicitSpecialization =
  2809. OldMethod->isFunctionTemplateSpecialization() &&
  2810. NewMethod->isFunctionTemplateSpecialization();
  2811. bool isFriend = NewMethod->getFriendObjectKind();
  2812. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2813. !IsClassScopeExplicitSpecialization) {
  2814. // -- Member function declarations with the same name and the
  2815. // same parameter types cannot be overloaded if any of them
  2816. // is a static member function declaration.
  2817. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2818. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2819. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2820. return true;
  2821. }
  2822. // C++ [class.mem]p1:
  2823. // [...] A member shall not be declared twice in the
  2824. // member-specification, except that a nested class or member
  2825. // class template can be declared and then later defined.
  2826. if (!inTemplateInstantiation()) {
  2827. unsigned NewDiag;
  2828. if (isa<CXXConstructorDecl>(OldMethod))
  2829. NewDiag = diag::err_constructor_redeclared;
  2830. else if (isa<CXXDestructorDecl>(NewMethod))
  2831. NewDiag = diag::err_destructor_redeclared;
  2832. else if (isa<CXXConversionDecl>(NewMethod))
  2833. NewDiag = diag::err_conv_function_redeclared;
  2834. else
  2835. NewDiag = diag::err_member_redeclared;
  2836. Diag(New->getLocation(), NewDiag);
  2837. } else {
  2838. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2839. << New << New->getType();
  2840. }
  2841. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2842. return true;
  2843. // Complain if this is an explicit declaration of a special
  2844. // member that was initially declared implicitly.
  2845. //
  2846. // As an exception, it's okay to befriend such methods in order
  2847. // to permit the implicit constructor/destructor/operator calls.
  2848. } else if (OldMethod->isImplicit()) {
  2849. if (isFriend) {
  2850. NewMethod->setImplicit();
  2851. } else {
  2852. Diag(NewMethod->getLocation(),
  2853. diag::err_definition_of_implicitly_declared_member)
  2854. << New << getSpecialMember(OldMethod);
  2855. return true;
  2856. }
  2857. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2858. Diag(NewMethod->getLocation(),
  2859. diag::err_definition_of_explicitly_defaulted_member)
  2860. << getSpecialMember(OldMethod);
  2861. return true;
  2862. }
  2863. }
  2864. // C++11 [dcl.attr.noreturn]p1:
  2865. // The first declaration of a function shall specify the noreturn
  2866. // attribute if any declaration of that function specifies the noreturn
  2867. // attribute.
  2868. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2869. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2870. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2871. Diag(Old->getFirstDecl()->getLocation(),
  2872. diag::note_noreturn_missing_first_decl);
  2873. }
  2874. // C++11 [dcl.attr.depend]p2:
  2875. // The first declaration of a function shall specify the
  2876. // carries_dependency attribute for its declarator-id if any declaration
  2877. // of the function specifies the carries_dependency attribute.
  2878. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2879. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2880. Diag(CDA->getLocation(),
  2881. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2882. Diag(Old->getFirstDecl()->getLocation(),
  2883. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2884. }
  2885. // (C++98 8.3.5p3):
  2886. // All declarations for a function shall agree exactly in both the
  2887. // return type and the parameter-type-list.
  2888. // We also want to respect all the extended bits except noreturn.
  2889. // noreturn should now match unless the old type info didn't have it.
  2890. QualType OldQTypeForComparison = OldQType;
  2891. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2892. auto *OldType = OldQType->castAs<FunctionProtoType>();
  2893. const FunctionType *OldTypeForComparison
  2894. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2895. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2896. assert(OldQTypeForComparison.isCanonical());
  2897. }
  2898. if (haveIncompatibleLanguageLinkages(Old, New)) {
  2899. // As a special case, retain the language linkage from previous
  2900. // declarations of a friend function as an extension.
  2901. //
  2902. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  2903. // and is useful because there's otherwise no way to specify language
  2904. // linkage within class scope.
  2905. //
  2906. // Check cautiously as the friend object kind isn't yet complete.
  2907. if (New->getFriendObjectKind() != Decl::FOK_None) {
  2908. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  2909. Diag(OldLocation, PrevDiag);
  2910. } else {
  2911. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  2912. Diag(OldLocation, PrevDiag);
  2913. return true;
  2914. }
  2915. }
  2916. if (OldQTypeForComparison == NewQType)
  2917. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2918. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2919. New->isLocalExternDecl()) {
  2920. // It's OK if we couldn't merge types for a local function declaraton
  2921. // if either the old or new type is dependent. We'll merge the types
  2922. // when we instantiate the function.
  2923. return false;
  2924. }
  2925. // Fall through for conflicting redeclarations and redefinitions.
  2926. }
  2927. // C: Function types need to be compatible, not identical. This handles
  2928. // duplicate function decls like "void f(int); void f(enum X);" properly.
  2929. if (!getLangOpts().CPlusPlus &&
  2930. Context.typesAreCompatible(OldQType, NewQType)) {
  2931. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  2932. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  2933. const FunctionProtoType *OldProto = nullptr;
  2934. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  2935. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  2936. // The old declaration provided a function prototype, but the
  2937. // new declaration does not. Merge in the prototype.
  2938. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  2939. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  2940. NewQType =
  2941. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  2942. OldProto->getExtProtoInfo());
  2943. New->setType(NewQType);
  2944. New->setHasInheritedPrototype();
  2945. // Synthesize parameters with the same types.
  2946. SmallVector<ParmVarDecl*, 16> Params;
  2947. for (const auto &ParamType : OldProto->param_types()) {
  2948. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  2949. SourceLocation(), nullptr,
  2950. ParamType, /*TInfo=*/nullptr,
  2951. SC_None, nullptr);
  2952. Param->setScopeInfo(0, Params.size());
  2953. Param->setImplicit();
  2954. Params.push_back(Param);
  2955. }
  2956. New->setParams(Params);
  2957. }
  2958. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  2959. }
  2960. // GNU C permits a K&R definition to follow a prototype declaration
  2961. // if the declared types of the parameters in the K&R definition
  2962. // match the types in the prototype declaration, even when the
  2963. // promoted types of the parameters from the K&R definition differ
  2964. // from the types in the prototype. GCC then keeps the types from
  2965. // the prototype.
  2966. //
  2967. // If a variadic prototype is followed by a non-variadic K&R definition,
  2968. // the K&R definition becomes variadic. This is sort of an edge case, but
  2969. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  2970. // C99 6.9.1p8.
  2971. if (!getLangOpts().CPlusPlus &&
  2972. Old->hasPrototype() && !New->hasPrototype() &&
  2973. New->getType()->getAs<FunctionProtoType>() &&
  2974. Old->getNumParams() == New->getNumParams()) {
  2975. SmallVector<QualType, 16> ArgTypes;
  2976. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  2977. const FunctionProtoType *OldProto
  2978. = Old->getType()->getAs<FunctionProtoType>();
  2979. const FunctionProtoType *NewProto
  2980. = New->getType()->getAs<FunctionProtoType>();
  2981. // Determine whether this is the GNU C extension.
  2982. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  2983. NewProto->getReturnType());
  2984. bool LooseCompatible = !MergedReturn.isNull();
  2985. for (unsigned Idx = 0, End = Old->getNumParams();
  2986. LooseCompatible && Idx != End; ++Idx) {
  2987. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  2988. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  2989. if (Context.typesAreCompatible(OldParm->getType(),
  2990. NewProto->getParamType(Idx))) {
  2991. ArgTypes.push_back(NewParm->getType());
  2992. } else if (Context.typesAreCompatible(OldParm->getType(),
  2993. NewParm->getType(),
  2994. /*CompareUnqualified=*/true)) {
  2995. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  2996. NewProto->getParamType(Idx) };
  2997. Warnings.push_back(Warn);
  2998. ArgTypes.push_back(NewParm->getType());
  2999. } else
  3000. LooseCompatible = false;
  3001. }
  3002. if (LooseCompatible) {
  3003. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3004. Diag(Warnings[Warn].NewParm->getLocation(),
  3005. diag::ext_param_promoted_not_compatible_with_prototype)
  3006. << Warnings[Warn].PromotedType
  3007. << Warnings[Warn].OldParm->getType();
  3008. if (Warnings[Warn].OldParm->getLocation().isValid())
  3009. Diag(Warnings[Warn].OldParm->getLocation(),
  3010. diag::note_previous_declaration);
  3011. }
  3012. if (MergeTypeWithOld)
  3013. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3014. OldProto->getExtProtoInfo()));
  3015. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3016. }
  3017. // Fall through to diagnose conflicting types.
  3018. }
  3019. // A function that has already been declared has been redeclared or
  3020. // defined with a different type; show an appropriate diagnostic.
  3021. // If the previous declaration was an implicitly-generated builtin
  3022. // declaration, then at the very least we should use a specialized note.
  3023. unsigned BuiltinID;
  3024. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3025. // If it's actually a library-defined builtin function like 'malloc'
  3026. // or 'printf', just warn about the incompatible redeclaration.
  3027. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3028. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3029. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3030. << Old << Old->getType();
  3031. // If this is a global redeclaration, just forget hereafter
  3032. // about the "builtin-ness" of the function.
  3033. //
  3034. // Doing this for local extern declarations is problematic. If
  3035. // the builtin declaration remains visible, a second invalid
  3036. // local declaration will produce a hard error; if it doesn't
  3037. // remain visible, a single bogus local redeclaration (which is
  3038. // actually only a warning) could break all the downstream code.
  3039. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3040. New->getIdentifier()->revertBuiltin();
  3041. return false;
  3042. }
  3043. PrevDiag = diag::note_previous_builtin_declaration;
  3044. }
  3045. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3046. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3047. return true;
  3048. }
  3049. /// \brief Completes the merge of two function declarations that are
  3050. /// known to be compatible.
  3051. ///
  3052. /// This routine handles the merging of attributes and other
  3053. /// properties of function declarations from the old declaration to
  3054. /// the new declaration, once we know that New is in fact a
  3055. /// redeclaration of Old.
  3056. ///
  3057. /// \returns false
  3058. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3059. Scope *S, bool MergeTypeWithOld) {
  3060. // Merge the attributes
  3061. mergeDeclAttributes(New, Old);
  3062. // Merge "pure" flag.
  3063. if (Old->isPure())
  3064. New->setPure();
  3065. // Merge "used" flag.
  3066. if (Old->getMostRecentDecl()->isUsed(false))
  3067. New->setIsUsed();
  3068. // Merge attributes from the parameters. These can mismatch with K&R
  3069. // declarations.
  3070. if (New->getNumParams() == Old->getNumParams())
  3071. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3072. ParmVarDecl *NewParam = New->getParamDecl(i);
  3073. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3074. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3075. mergeParamDeclTypes(NewParam, OldParam, *this);
  3076. }
  3077. if (getLangOpts().CPlusPlus)
  3078. return MergeCXXFunctionDecl(New, Old, S);
  3079. // Merge the function types so the we get the composite types for the return
  3080. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3081. // was visible.
  3082. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3083. if (!Merged.isNull() && MergeTypeWithOld)
  3084. New->setType(Merged);
  3085. return false;
  3086. }
  3087. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3088. ObjCMethodDecl *oldMethod) {
  3089. // Merge the attributes, including deprecated/unavailable
  3090. AvailabilityMergeKind MergeKind =
  3091. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3092. ? AMK_ProtocolImplementation
  3093. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3094. : AMK_Override;
  3095. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3096. // Merge attributes from the parameters.
  3097. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3098. oe = oldMethod->param_end();
  3099. for (ObjCMethodDecl::param_iterator
  3100. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3101. ni != ne && oi != oe; ++ni, ++oi)
  3102. mergeParamDeclAttributes(*ni, *oi, *this);
  3103. CheckObjCMethodOverride(newMethod, oldMethod);
  3104. }
  3105. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3106. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3107. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3108. ? diag::err_redefinition_different_type
  3109. : diag::err_redeclaration_different_type)
  3110. << New->getDeclName() << New->getType() << Old->getType();
  3111. diag::kind PrevDiag;
  3112. SourceLocation OldLocation;
  3113. std::tie(PrevDiag, OldLocation)
  3114. = getNoteDiagForInvalidRedeclaration(Old, New);
  3115. S.Diag(OldLocation, PrevDiag);
  3116. New->setInvalidDecl();
  3117. }
  3118. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3119. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3120. /// emitting diagnostics as appropriate.
  3121. ///
  3122. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3123. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3124. /// is attached.
  3125. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3126. bool MergeTypeWithOld) {
  3127. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3128. return;
  3129. QualType MergedT;
  3130. if (getLangOpts().CPlusPlus) {
  3131. if (New->getType()->isUndeducedType()) {
  3132. // We don't know what the new type is until the initializer is attached.
  3133. return;
  3134. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3135. // These could still be something that needs exception specs checked.
  3136. return MergeVarDeclExceptionSpecs(New, Old);
  3137. }
  3138. // C++ [basic.link]p10:
  3139. // [...] the types specified by all declarations referring to a given
  3140. // object or function shall be identical, except that declarations for an
  3141. // array object can specify array types that differ by the presence or
  3142. // absence of a major array bound (8.3.4).
  3143. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3144. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3145. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3146. // We are merging a variable declaration New into Old. If it has an array
  3147. // bound, and that bound differs from Old's bound, we should diagnose the
  3148. // mismatch.
  3149. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3150. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3151. PrevVD = PrevVD->getPreviousDecl()) {
  3152. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3153. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3154. continue;
  3155. if (!Context.hasSameType(NewArray, PrevVDTy))
  3156. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3157. }
  3158. }
  3159. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3160. if (Context.hasSameType(OldArray->getElementType(),
  3161. NewArray->getElementType()))
  3162. MergedT = New->getType();
  3163. }
  3164. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3165. // has no array bound, it should not inherit one from Old, if Old is not
  3166. // visible.
  3167. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3168. if (Context.hasSameType(OldArray->getElementType(),
  3169. NewArray->getElementType()))
  3170. MergedT = Old->getType();
  3171. }
  3172. }
  3173. else if (New->getType()->isObjCObjectPointerType() &&
  3174. Old->getType()->isObjCObjectPointerType()) {
  3175. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3176. Old->getType());
  3177. }
  3178. } else {
  3179. // C 6.2.7p2:
  3180. // All declarations that refer to the same object or function shall have
  3181. // compatible type.
  3182. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3183. }
  3184. if (MergedT.isNull()) {
  3185. // It's OK if we couldn't merge types if either type is dependent, for a
  3186. // block-scope variable. In other cases (static data members of class
  3187. // templates, variable templates, ...), we require the types to be
  3188. // equivalent.
  3189. // FIXME: The C++ standard doesn't say anything about this.
  3190. if ((New->getType()->isDependentType() ||
  3191. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3192. // If the old type was dependent, we can't merge with it, so the new type
  3193. // becomes dependent for now. We'll reproduce the original type when we
  3194. // instantiate the TypeSourceInfo for the variable.
  3195. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3196. New->setType(Context.DependentTy);
  3197. return;
  3198. }
  3199. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3200. }
  3201. // Don't actually update the type on the new declaration if the old
  3202. // declaration was an extern declaration in a different scope.
  3203. if (MergeTypeWithOld)
  3204. New->setType(MergedT);
  3205. }
  3206. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3207. LookupResult &Previous) {
  3208. // C11 6.2.7p4:
  3209. // For an identifier with internal or external linkage declared
  3210. // in a scope in which a prior declaration of that identifier is
  3211. // visible, if the prior declaration specifies internal or
  3212. // external linkage, the type of the identifier at the later
  3213. // declaration becomes the composite type.
  3214. //
  3215. // If the variable isn't visible, we do not merge with its type.
  3216. if (Previous.isShadowed())
  3217. return false;
  3218. if (S.getLangOpts().CPlusPlus) {
  3219. // C++11 [dcl.array]p3:
  3220. // If there is a preceding declaration of the entity in the same
  3221. // scope in which the bound was specified, an omitted array bound
  3222. // is taken to be the same as in that earlier declaration.
  3223. return NewVD->isPreviousDeclInSameBlockScope() ||
  3224. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3225. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3226. } else {
  3227. // If the old declaration was function-local, don't merge with its
  3228. // type unless we're in the same function.
  3229. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3230. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3231. }
  3232. }
  3233. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3234. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3235. /// situation, merging decls or emitting diagnostics as appropriate.
  3236. ///
  3237. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3238. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3239. /// definitions here, since the initializer hasn't been attached.
  3240. ///
  3241. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3242. // If the new decl is already invalid, don't do any other checking.
  3243. if (New->isInvalidDecl())
  3244. return;
  3245. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3246. return;
  3247. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3248. // Verify the old decl was also a variable or variable template.
  3249. VarDecl *Old = nullptr;
  3250. VarTemplateDecl *OldTemplate = nullptr;
  3251. if (Previous.isSingleResult()) {
  3252. if (NewTemplate) {
  3253. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3254. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3255. if (auto *Shadow =
  3256. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3257. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3258. return New->setInvalidDecl();
  3259. } else {
  3260. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3261. if (auto *Shadow =
  3262. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3263. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3264. return New->setInvalidDecl();
  3265. }
  3266. }
  3267. if (!Old) {
  3268. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3269. << New->getDeclName();
  3270. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3271. New->getLocation());
  3272. return New->setInvalidDecl();
  3273. }
  3274. // Ensure the template parameters are compatible.
  3275. if (NewTemplate &&
  3276. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3277. OldTemplate->getTemplateParameters(),
  3278. /*Complain=*/true, TPL_TemplateMatch))
  3279. return New->setInvalidDecl();
  3280. // C++ [class.mem]p1:
  3281. // A member shall not be declared twice in the member-specification [...]
  3282. //
  3283. // Here, we need only consider static data members.
  3284. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3285. Diag(New->getLocation(), diag::err_duplicate_member)
  3286. << New->getIdentifier();
  3287. Diag(Old->getLocation(), diag::note_previous_declaration);
  3288. New->setInvalidDecl();
  3289. }
  3290. mergeDeclAttributes(New, Old);
  3291. // Warn if an already-declared variable is made a weak_import in a subsequent
  3292. // declaration
  3293. if (New->hasAttr<WeakImportAttr>() &&
  3294. Old->getStorageClass() == SC_None &&
  3295. !Old->hasAttr<WeakImportAttr>()) {
  3296. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3297. notePreviousDefinition(Old, New->getLocation());
  3298. // Remove weak_import attribute on new declaration.
  3299. New->dropAttr<WeakImportAttr>();
  3300. }
  3301. if (New->hasAttr<InternalLinkageAttr>() &&
  3302. !Old->hasAttr<InternalLinkageAttr>()) {
  3303. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3304. << New->getDeclName();
  3305. notePreviousDefinition(Old, New->getLocation());
  3306. New->dropAttr<InternalLinkageAttr>();
  3307. }
  3308. // Merge the types.
  3309. VarDecl *MostRecent = Old->getMostRecentDecl();
  3310. if (MostRecent != Old) {
  3311. MergeVarDeclTypes(New, MostRecent,
  3312. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3313. if (New->isInvalidDecl())
  3314. return;
  3315. }
  3316. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3317. if (New->isInvalidDecl())
  3318. return;
  3319. diag::kind PrevDiag;
  3320. SourceLocation OldLocation;
  3321. std::tie(PrevDiag, OldLocation) =
  3322. getNoteDiagForInvalidRedeclaration(Old, New);
  3323. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3324. if (New->getStorageClass() == SC_Static &&
  3325. !New->isStaticDataMember() &&
  3326. Old->hasExternalFormalLinkage()) {
  3327. if (getLangOpts().MicrosoftExt) {
  3328. Diag(New->getLocation(), diag::ext_static_non_static)
  3329. << New->getDeclName();
  3330. Diag(OldLocation, PrevDiag);
  3331. } else {
  3332. Diag(New->getLocation(), diag::err_static_non_static)
  3333. << New->getDeclName();
  3334. Diag(OldLocation, PrevDiag);
  3335. return New->setInvalidDecl();
  3336. }
  3337. }
  3338. // C99 6.2.2p4:
  3339. // For an identifier declared with the storage-class specifier
  3340. // extern in a scope in which a prior declaration of that
  3341. // identifier is visible,23) if the prior declaration specifies
  3342. // internal or external linkage, the linkage of the identifier at
  3343. // the later declaration is the same as the linkage specified at
  3344. // the prior declaration. If no prior declaration is visible, or
  3345. // if the prior declaration specifies no linkage, then the
  3346. // identifier has external linkage.
  3347. if (New->hasExternalStorage() && Old->hasLinkage())
  3348. /* Okay */;
  3349. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3350. !New->isStaticDataMember() &&
  3351. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3352. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3353. Diag(OldLocation, PrevDiag);
  3354. return New->setInvalidDecl();
  3355. }
  3356. // Check if extern is followed by non-extern and vice-versa.
  3357. if (New->hasExternalStorage() &&
  3358. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3359. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3360. Diag(OldLocation, PrevDiag);
  3361. return New->setInvalidDecl();
  3362. }
  3363. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3364. !New->hasExternalStorage()) {
  3365. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3366. Diag(OldLocation, PrevDiag);
  3367. return New->setInvalidDecl();
  3368. }
  3369. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3370. // FIXME: The test for external storage here seems wrong? We still
  3371. // need to check for mismatches.
  3372. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3373. // Don't complain about out-of-line definitions of static members.
  3374. !(Old->getLexicalDeclContext()->isRecord() &&
  3375. !New->getLexicalDeclContext()->isRecord())) {
  3376. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3377. Diag(OldLocation, PrevDiag);
  3378. return New->setInvalidDecl();
  3379. }
  3380. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3381. if (VarDecl *Def = Old->getDefinition()) {
  3382. // C++1z [dcl.fcn.spec]p4:
  3383. // If the definition of a variable appears in a translation unit before
  3384. // its first declaration as inline, the program is ill-formed.
  3385. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3386. Diag(Def->getLocation(), diag::note_previous_definition);
  3387. }
  3388. }
  3389. // If this redeclaration makes the function inline, we may need to add it to
  3390. // UndefinedButUsed.
  3391. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3392. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3393. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3394. SourceLocation()));
  3395. if (New->getTLSKind() != Old->getTLSKind()) {
  3396. if (!Old->getTLSKind()) {
  3397. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3398. Diag(OldLocation, PrevDiag);
  3399. } else if (!New->getTLSKind()) {
  3400. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3401. Diag(OldLocation, PrevDiag);
  3402. } else {
  3403. // Do not allow redeclaration to change the variable between requiring
  3404. // static and dynamic initialization.
  3405. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3406. // declaration to determine the kind. Do we need to be compatible here?
  3407. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3408. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3409. Diag(OldLocation, PrevDiag);
  3410. }
  3411. }
  3412. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3413. if (getLangOpts().CPlusPlus &&
  3414. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3415. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3416. Old->getCanonicalDecl()->isConstexpr()) {
  3417. // This definition won't be a definition any more once it's been merged.
  3418. Diag(New->getLocation(),
  3419. diag::warn_deprecated_redundant_constexpr_static_def);
  3420. } else if (VarDecl *Def = Old->getDefinition()) {
  3421. if (checkVarDeclRedefinition(Def, New))
  3422. return;
  3423. }
  3424. }
  3425. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3426. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3427. Diag(OldLocation, PrevDiag);
  3428. New->setInvalidDecl();
  3429. return;
  3430. }
  3431. // Merge "used" flag.
  3432. if (Old->getMostRecentDecl()->isUsed(false))
  3433. New->setIsUsed();
  3434. // Keep a chain of previous declarations.
  3435. New->setPreviousDecl(Old);
  3436. if (NewTemplate)
  3437. NewTemplate->setPreviousDecl(OldTemplate);
  3438. // Inherit access appropriately.
  3439. New->setAccess(Old->getAccess());
  3440. if (NewTemplate)
  3441. NewTemplate->setAccess(New->getAccess());
  3442. if (Old->isInline())
  3443. New->setImplicitlyInline();
  3444. }
  3445. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3446. SourceManager &SrcMgr = getSourceManager();
  3447. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3448. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3449. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3450. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3451. auto &HSI = PP.getHeaderSearchInfo();
  3452. StringRef HdrFilename =
  3453. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3454. auto noteFromModuleOrInclude = [&](Module *Mod,
  3455. SourceLocation IncLoc) -> bool {
  3456. // Redefinition errors with modules are common with non modular mapped
  3457. // headers, example: a non-modular header H in module A that also gets
  3458. // included directly in a TU. Pointing twice to the same header/definition
  3459. // is confusing, try to get better diagnostics when modules is on.
  3460. if (IncLoc.isValid()) {
  3461. if (Mod) {
  3462. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3463. << HdrFilename.str() << Mod->getFullModuleName();
  3464. if (!Mod->DefinitionLoc.isInvalid())
  3465. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3466. << Mod->getFullModuleName();
  3467. } else {
  3468. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3469. << HdrFilename.str();
  3470. }
  3471. return true;
  3472. }
  3473. return false;
  3474. };
  3475. // Is it the same file and same offset? Provide more information on why
  3476. // this leads to a redefinition error.
  3477. bool EmittedDiag = false;
  3478. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3479. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3480. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3481. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3482. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3483. // If the header has no guards, emit a note suggesting one.
  3484. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3485. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3486. if (EmittedDiag)
  3487. return;
  3488. }
  3489. // Redefinition coming from different files or couldn't do better above.
  3490. Diag(Old->getLocation(), diag::note_previous_definition);
  3491. }
  3492. /// We've just determined that \p Old and \p New both appear to be definitions
  3493. /// of the same variable. Either diagnose or fix the problem.
  3494. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3495. if (!hasVisibleDefinition(Old) &&
  3496. (New->getFormalLinkage() == InternalLinkage ||
  3497. New->isInline() ||
  3498. New->getDescribedVarTemplate() ||
  3499. New->getNumTemplateParameterLists() ||
  3500. New->getDeclContext()->isDependentContext())) {
  3501. // The previous definition is hidden, and multiple definitions are
  3502. // permitted (in separate TUs). Demote this to a declaration.
  3503. New->demoteThisDefinitionToDeclaration();
  3504. // Make the canonical definition visible.
  3505. if (auto *OldTD = Old->getDescribedVarTemplate())
  3506. makeMergedDefinitionVisible(OldTD);
  3507. makeMergedDefinitionVisible(Old);
  3508. return false;
  3509. } else {
  3510. Diag(New->getLocation(), diag::err_redefinition) << New;
  3511. notePreviousDefinition(Old, New->getLocation());
  3512. New->setInvalidDecl();
  3513. return true;
  3514. }
  3515. }
  3516. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3517. /// no declarator (e.g. "struct foo;") is parsed.
  3518. Decl *
  3519. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3520. RecordDecl *&AnonRecord) {
  3521. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3522. AnonRecord);
  3523. }
  3524. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3525. // disambiguate entities defined in different scopes.
  3526. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3527. // compatibility.
  3528. // We will pick our mangling number depending on which version of MSVC is being
  3529. // targeted.
  3530. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3531. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3532. ? S->getMSCurManglingNumber()
  3533. : S->getMSLastManglingNumber();
  3534. }
  3535. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3536. if (!Context.getLangOpts().CPlusPlus)
  3537. return;
  3538. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3539. // If this tag is the direct child of a class, number it if
  3540. // it is anonymous.
  3541. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3542. return;
  3543. MangleNumberingContext &MCtx =
  3544. Context.getManglingNumberContext(Tag->getParent());
  3545. Context.setManglingNumber(
  3546. Tag, MCtx.getManglingNumber(
  3547. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3548. return;
  3549. }
  3550. // If this tag isn't a direct child of a class, number it if it is local.
  3551. Decl *ManglingContextDecl;
  3552. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3553. Tag->getDeclContext(), ManglingContextDecl)) {
  3554. Context.setManglingNumber(
  3555. Tag, MCtx->getManglingNumber(
  3556. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3557. }
  3558. }
  3559. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3560. TypedefNameDecl *NewTD) {
  3561. if (TagFromDeclSpec->isInvalidDecl())
  3562. return;
  3563. // Do nothing if the tag already has a name for linkage purposes.
  3564. if (TagFromDeclSpec->hasNameForLinkage())
  3565. return;
  3566. // A well-formed anonymous tag must always be a TUK_Definition.
  3567. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3568. // The type must match the tag exactly; no qualifiers allowed.
  3569. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3570. Context.getTagDeclType(TagFromDeclSpec))) {
  3571. if (getLangOpts().CPlusPlus)
  3572. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3573. return;
  3574. }
  3575. // If we've already computed linkage for the anonymous tag, then
  3576. // adding a typedef name for the anonymous decl can change that
  3577. // linkage, which might be a serious problem. Diagnose this as
  3578. // unsupported and ignore the typedef name. TODO: we should
  3579. // pursue this as a language defect and establish a formal rule
  3580. // for how to handle it.
  3581. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3582. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3583. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3584. tagLoc = getLocForEndOfToken(tagLoc);
  3585. llvm::SmallString<40> textToInsert;
  3586. textToInsert += ' ';
  3587. textToInsert += NewTD->getIdentifier()->getName();
  3588. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3589. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3590. return;
  3591. }
  3592. // Otherwise, set this is the anon-decl typedef for the tag.
  3593. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3594. }
  3595. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3596. switch (T) {
  3597. case DeclSpec::TST_class:
  3598. return 0;
  3599. case DeclSpec::TST_struct:
  3600. return 1;
  3601. case DeclSpec::TST_interface:
  3602. return 2;
  3603. case DeclSpec::TST_union:
  3604. return 3;
  3605. case DeclSpec::TST_enum:
  3606. return 4;
  3607. default:
  3608. llvm_unreachable("unexpected type specifier");
  3609. }
  3610. }
  3611. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3612. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3613. /// parameters to cope with template friend declarations.
  3614. Decl *
  3615. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3616. MultiTemplateParamsArg TemplateParams,
  3617. bool IsExplicitInstantiation,
  3618. RecordDecl *&AnonRecord) {
  3619. Decl *TagD = nullptr;
  3620. TagDecl *Tag = nullptr;
  3621. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3622. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3623. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3624. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3625. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3626. TagD = DS.getRepAsDecl();
  3627. if (!TagD) // We probably had an error
  3628. return nullptr;
  3629. // Note that the above type specs guarantee that the
  3630. // type rep is a Decl, whereas in many of the others
  3631. // it's a Type.
  3632. if (isa<TagDecl>(TagD))
  3633. Tag = cast<TagDecl>(TagD);
  3634. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3635. Tag = CTD->getTemplatedDecl();
  3636. }
  3637. if (Tag) {
  3638. handleTagNumbering(Tag, S);
  3639. Tag->setFreeStanding();
  3640. if (Tag->isInvalidDecl())
  3641. return Tag;
  3642. }
  3643. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3644. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3645. // or incomplete types shall not be restrict-qualified."
  3646. if (TypeQuals & DeclSpec::TQ_restrict)
  3647. Diag(DS.getRestrictSpecLoc(),
  3648. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3649. << DS.getSourceRange();
  3650. }
  3651. if (DS.isInlineSpecified())
  3652. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3653. << getLangOpts().CPlusPlus1z;
  3654. if (DS.isConstexprSpecified()) {
  3655. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3656. // and definitions of functions and variables.
  3657. if (Tag)
  3658. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3659. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3660. else
  3661. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3662. // Don't emit warnings after this error.
  3663. return TagD;
  3664. }
  3665. if (DS.isConceptSpecified()) {
  3666. // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
  3667. // either a function concept and its definition or a variable concept and
  3668. // its initializer.
  3669. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  3670. return TagD;
  3671. }
  3672. DiagnoseFunctionSpecifiers(DS);
  3673. if (DS.isFriendSpecified()) {
  3674. // If we're dealing with a decl but not a TagDecl, assume that
  3675. // whatever routines created it handled the friendship aspect.
  3676. if (TagD && !Tag)
  3677. return nullptr;
  3678. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3679. }
  3680. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3681. bool IsExplicitSpecialization =
  3682. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3683. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3684. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3685. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3686. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3687. // nested-name-specifier unless it is an explicit instantiation
  3688. // or an explicit specialization.
  3689. //
  3690. // FIXME: We allow class template partial specializations here too, per the
  3691. // obvious intent of DR1819.
  3692. //
  3693. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3694. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3695. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3696. return nullptr;
  3697. }
  3698. // Track whether this decl-specifier declares anything.
  3699. bool DeclaresAnything = true;
  3700. // Handle anonymous struct definitions.
  3701. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3702. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3703. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3704. if (getLangOpts().CPlusPlus ||
  3705. Record->getDeclContext()->isRecord()) {
  3706. // If CurContext is a DeclContext that can contain statements,
  3707. // RecursiveASTVisitor won't visit the decls that
  3708. // BuildAnonymousStructOrUnion() will put into CurContext.
  3709. // Also store them here so that they can be part of the
  3710. // DeclStmt that gets created in this case.
  3711. // FIXME: Also return the IndirectFieldDecls created by
  3712. // BuildAnonymousStructOr union, for the same reason?
  3713. if (CurContext->isFunctionOrMethod())
  3714. AnonRecord = Record;
  3715. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3716. Context.getPrintingPolicy());
  3717. }
  3718. DeclaresAnything = false;
  3719. }
  3720. }
  3721. // C11 6.7.2.1p2:
  3722. // A struct-declaration that does not declare an anonymous structure or
  3723. // anonymous union shall contain a struct-declarator-list.
  3724. //
  3725. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3726. // did not permit a struct-declaration without a struct-declarator-list.
  3727. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3728. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3729. // Check for Microsoft C extension: anonymous struct/union member.
  3730. // Handle 2 kinds of anonymous struct/union:
  3731. // struct STRUCT;
  3732. // union UNION;
  3733. // and
  3734. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3735. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3736. if ((Tag && Tag->getDeclName()) ||
  3737. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3738. RecordDecl *Record = nullptr;
  3739. if (Tag)
  3740. Record = dyn_cast<RecordDecl>(Tag);
  3741. else if (const RecordType *RT =
  3742. DS.getRepAsType().get()->getAsStructureType())
  3743. Record = RT->getDecl();
  3744. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3745. Record = UT->getDecl();
  3746. if (Record && getLangOpts().MicrosoftExt) {
  3747. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3748. << Record->isUnion() << DS.getSourceRange();
  3749. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3750. }
  3751. DeclaresAnything = false;
  3752. }
  3753. }
  3754. // Skip all the checks below if we have a type error.
  3755. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3756. (TagD && TagD->isInvalidDecl()))
  3757. return TagD;
  3758. if (getLangOpts().CPlusPlus &&
  3759. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3760. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3761. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3762. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3763. DeclaresAnything = false;
  3764. if (!DS.isMissingDeclaratorOk()) {
  3765. // Customize diagnostic for a typedef missing a name.
  3766. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3767. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3768. << DS.getSourceRange();
  3769. else
  3770. DeclaresAnything = false;
  3771. }
  3772. if (DS.isModulePrivateSpecified() &&
  3773. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3774. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3775. << Tag->getTagKind()
  3776. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3777. ActOnDocumentableDecl(TagD);
  3778. // C 6.7/2:
  3779. // A declaration [...] shall declare at least a declarator [...], a tag,
  3780. // or the members of an enumeration.
  3781. // C++ [dcl.dcl]p3:
  3782. // [If there are no declarators], and except for the declaration of an
  3783. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3784. // names into the program, or shall redeclare a name introduced by a
  3785. // previous declaration.
  3786. if (!DeclaresAnything) {
  3787. // In C, we allow this as a (popular) extension / bug. Don't bother
  3788. // producing further diagnostics for redundant qualifiers after this.
  3789. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3790. return TagD;
  3791. }
  3792. // C++ [dcl.stc]p1:
  3793. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3794. // init-declarator-list of the declaration shall not be empty.
  3795. // C++ [dcl.fct.spec]p1:
  3796. // If a cv-qualifier appears in a decl-specifier-seq, the
  3797. // init-declarator-list of the declaration shall not be empty.
  3798. //
  3799. // Spurious qualifiers here appear to be valid in C.
  3800. unsigned DiagID = diag::warn_standalone_specifier;
  3801. if (getLangOpts().CPlusPlus)
  3802. DiagID = diag::ext_standalone_specifier;
  3803. // Note that a linkage-specification sets a storage class, but
  3804. // 'extern "C" struct foo;' is actually valid and not theoretically
  3805. // useless.
  3806. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3807. if (SCS == DeclSpec::SCS_mutable)
  3808. // Since mutable is not a viable storage class specifier in C, there is
  3809. // no reason to treat it as an extension. Instead, diagnose as an error.
  3810. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3811. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3812. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3813. << DeclSpec::getSpecifierName(SCS);
  3814. }
  3815. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3816. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3817. << DeclSpec::getSpecifierName(TSCS);
  3818. if (DS.getTypeQualifiers()) {
  3819. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3820. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3821. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3822. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3823. // Restrict is covered above.
  3824. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3825. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3826. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3827. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3828. }
  3829. // Warn about ignored type attributes, for example:
  3830. // __attribute__((aligned)) struct A;
  3831. // Attributes should be placed after tag to apply to type declaration.
  3832. if (!DS.getAttributes().empty()) {
  3833. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3834. if (TypeSpecType == DeclSpec::TST_class ||
  3835. TypeSpecType == DeclSpec::TST_struct ||
  3836. TypeSpecType == DeclSpec::TST_interface ||
  3837. TypeSpecType == DeclSpec::TST_union ||
  3838. TypeSpecType == DeclSpec::TST_enum) {
  3839. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3840. attrs = attrs->getNext())
  3841. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3842. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3843. }
  3844. }
  3845. return TagD;
  3846. }
  3847. /// We are trying to inject an anonymous member into the given scope;
  3848. /// check if there's an existing declaration that can't be overloaded.
  3849. ///
  3850. /// \return true if this is a forbidden redeclaration
  3851. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3852. Scope *S,
  3853. DeclContext *Owner,
  3854. DeclarationName Name,
  3855. SourceLocation NameLoc,
  3856. bool IsUnion) {
  3857. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3858. Sema::ForRedeclaration);
  3859. if (!SemaRef.LookupName(R, S)) return false;
  3860. // Pick a representative declaration.
  3861. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3862. assert(PrevDecl && "Expected a non-null Decl");
  3863. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3864. return false;
  3865. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3866. << IsUnion << Name;
  3867. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3868. return true;
  3869. }
  3870. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3871. /// anonymous struct or union AnonRecord into the owning context Owner
  3872. /// and scope S. This routine will be invoked just after we realize
  3873. /// that an unnamed union or struct is actually an anonymous union or
  3874. /// struct, e.g.,
  3875. ///
  3876. /// @code
  3877. /// union {
  3878. /// int i;
  3879. /// float f;
  3880. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3881. /// // f into the surrounding scope.x
  3882. /// @endcode
  3883. ///
  3884. /// This routine is recursive, injecting the names of nested anonymous
  3885. /// structs/unions into the owning context and scope as well.
  3886. static bool
  3887. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3888. RecordDecl *AnonRecord, AccessSpecifier AS,
  3889. SmallVectorImpl<NamedDecl *> &Chaining) {
  3890. bool Invalid = false;
  3891. // Look every FieldDecl and IndirectFieldDecl with a name.
  3892. for (auto *D : AnonRecord->decls()) {
  3893. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3894. cast<NamedDecl>(D)->getDeclName()) {
  3895. ValueDecl *VD = cast<ValueDecl>(D);
  3896. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3897. VD->getLocation(),
  3898. AnonRecord->isUnion())) {
  3899. // C++ [class.union]p2:
  3900. // The names of the members of an anonymous union shall be
  3901. // distinct from the names of any other entity in the
  3902. // scope in which the anonymous union is declared.
  3903. Invalid = true;
  3904. } else {
  3905. // C++ [class.union]p2:
  3906. // For the purpose of name lookup, after the anonymous union
  3907. // definition, the members of the anonymous union are
  3908. // considered to have been defined in the scope in which the
  3909. // anonymous union is declared.
  3910. unsigned OldChainingSize = Chaining.size();
  3911. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  3912. Chaining.append(IF->chain_begin(), IF->chain_end());
  3913. else
  3914. Chaining.push_back(VD);
  3915. assert(Chaining.size() >= 2);
  3916. NamedDecl **NamedChain =
  3917. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  3918. for (unsigned i = 0; i < Chaining.size(); i++)
  3919. NamedChain[i] = Chaining[i];
  3920. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  3921. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  3922. VD->getType(), {NamedChain, Chaining.size()});
  3923. for (const auto *Attr : VD->attrs())
  3924. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  3925. IndirectField->setAccess(AS);
  3926. IndirectField->setImplicit();
  3927. SemaRef.PushOnScopeChains(IndirectField, S);
  3928. // That includes picking up the appropriate access specifier.
  3929. if (AS != AS_none) IndirectField->setAccess(AS);
  3930. Chaining.resize(OldChainingSize);
  3931. }
  3932. }
  3933. }
  3934. return Invalid;
  3935. }
  3936. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  3937. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  3938. /// illegal input values are mapped to SC_None.
  3939. static StorageClass
  3940. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  3941. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  3942. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  3943. "Parser allowed 'typedef' as storage class VarDecl.");
  3944. switch (StorageClassSpec) {
  3945. case DeclSpec::SCS_unspecified: return SC_None;
  3946. case DeclSpec::SCS_extern:
  3947. if (DS.isExternInLinkageSpec())
  3948. return SC_None;
  3949. return SC_Extern;
  3950. case DeclSpec::SCS_static: return SC_Static;
  3951. case DeclSpec::SCS_auto: return SC_Auto;
  3952. case DeclSpec::SCS_register: return SC_Register;
  3953. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  3954. // Illegal SCSs map to None: error reporting is up to the caller.
  3955. case DeclSpec::SCS_mutable: // Fall through.
  3956. case DeclSpec::SCS_typedef: return SC_None;
  3957. }
  3958. llvm_unreachable("unknown storage class specifier");
  3959. }
  3960. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  3961. assert(Record->hasInClassInitializer());
  3962. for (const auto *I : Record->decls()) {
  3963. const auto *FD = dyn_cast<FieldDecl>(I);
  3964. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  3965. FD = IFD->getAnonField();
  3966. if (FD && FD->hasInClassInitializer())
  3967. return FD->getLocation();
  3968. }
  3969. llvm_unreachable("couldn't find in-class initializer");
  3970. }
  3971. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3972. SourceLocation DefaultInitLoc) {
  3973. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3974. return;
  3975. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  3976. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  3977. }
  3978. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  3979. CXXRecordDecl *AnonUnion) {
  3980. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  3981. return;
  3982. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  3983. }
  3984. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  3985. /// anonymous structure or union. Anonymous unions are a C++ feature
  3986. /// (C++ [class.union]) and a C11 feature; anonymous structures
  3987. /// are a C11 feature and GNU C++ extension.
  3988. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  3989. AccessSpecifier AS,
  3990. RecordDecl *Record,
  3991. const PrintingPolicy &Policy) {
  3992. DeclContext *Owner = Record->getDeclContext();
  3993. // Diagnose whether this anonymous struct/union is an extension.
  3994. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  3995. Diag(Record->getLocation(), diag::ext_anonymous_union);
  3996. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  3997. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  3998. else if (!Record->isUnion() && !getLangOpts().C11)
  3999. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4000. // C and C++ require different kinds of checks for anonymous
  4001. // structs/unions.
  4002. bool Invalid = false;
  4003. if (getLangOpts().CPlusPlus) {
  4004. const char *PrevSpec = nullptr;
  4005. unsigned DiagID;
  4006. if (Record->isUnion()) {
  4007. // C++ [class.union]p6:
  4008. // Anonymous unions declared in a named namespace or in the
  4009. // global namespace shall be declared static.
  4010. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4011. (isa<TranslationUnitDecl>(Owner) ||
  4012. (isa<NamespaceDecl>(Owner) &&
  4013. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  4014. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4015. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4016. // Recover by adding 'static'.
  4017. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4018. PrevSpec, DiagID, Policy);
  4019. }
  4020. // C++ [class.union]p6:
  4021. // A storage class is not allowed in a declaration of an
  4022. // anonymous union in a class scope.
  4023. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4024. isa<RecordDecl>(Owner)) {
  4025. Diag(DS.getStorageClassSpecLoc(),
  4026. diag::err_anonymous_union_with_storage_spec)
  4027. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4028. // Recover by removing the storage specifier.
  4029. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4030. SourceLocation(),
  4031. PrevSpec, DiagID, Context.getPrintingPolicy());
  4032. }
  4033. }
  4034. // Ignore const/volatile/restrict qualifiers.
  4035. if (DS.getTypeQualifiers()) {
  4036. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4037. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4038. << Record->isUnion() << "const"
  4039. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4040. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4041. Diag(DS.getVolatileSpecLoc(),
  4042. diag::ext_anonymous_struct_union_qualified)
  4043. << Record->isUnion() << "volatile"
  4044. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4045. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4046. Diag(DS.getRestrictSpecLoc(),
  4047. diag::ext_anonymous_struct_union_qualified)
  4048. << Record->isUnion() << "restrict"
  4049. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4050. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4051. Diag(DS.getAtomicSpecLoc(),
  4052. diag::ext_anonymous_struct_union_qualified)
  4053. << Record->isUnion() << "_Atomic"
  4054. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4055. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4056. Diag(DS.getUnalignedSpecLoc(),
  4057. diag::ext_anonymous_struct_union_qualified)
  4058. << Record->isUnion() << "__unaligned"
  4059. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4060. DS.ClearTypeQualifiers();
  4061. }
  4062. // C++ [class.union]p2:
  4063. // The member-specification of an anonymous union shall only
  4064. // define non-static data members. [Note: nested types and
  4065. // functions cannot be declared within an anonymous union. ]
  4066. for (auto *Mem : Record->decls()) {
  4067. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4068. // C++ [class.union]p3:
  4069. // An anonymous union shall not have private or protected
  4070. // members (clause 11).
  4071. assert(FD->getAccess() != AS_none);
  4072. if (FD->getAccess() != AS_public) {
  4073. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4074. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4075. Invalid = true;
  4076. }
  4077. // C++ [class.union]p1
  4078. // An object of a class with a non-trivial constructor, a non-trivial
  4079. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4080. // assignment operator cannot be a member of a union, nor can an
  4081. // array of such objects.
  4082. if (CheckNontrivialField(FD))
  4083. Invalid = true;
  4084. } else if (Mem->isImplicit()) {
  4085. // Any implicit members are fine.
  4086. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4087. // This is a type that showed up in an
  4088. // elaborated-type-specifier inside the anonymous struct or
  4089. // union, but which actually declares a type outside of the
  4090. // anonymous struct or union. It's okay.
  4091. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4092. if (!MemRecord->isAnonymousStructOrUnion() &&
  4093. MemRecord->getDeclName()) {
  4094. // Visual C++ allows type definition in anonymous struct or union.
  4095. if (getLangOpts().MicrosoftExt)
  4096. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4097. << Record->isUnion();
  4098. else {
  4099. // This is a nested type declaration.
  4100. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4101. << Record->isUnion();
  4102. Invalid = true;
  4103. }
  4104. } else {
  4105. // This is an anonymous type definition within another anonymous type.
  4106. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4107. // not part of standard C++.
  4108. Diag(MemRecord->getLocation(),
  4109. diag::ext_anonymous_record_with_anonymous_type)
  4110. << Record->isUnion();
  4111. }
  4112. } else if (isa<AccessSpecDecl>(Mem)) {
  4113. // Any access specifier is fine.
  4114. } else if (isa<StaticAssertDecl>(Mem)) {
  4115. // In C++1z, static_assert declarations are also fine.
  4116. } else {
  4117. // We have something that isn't a non-static data
  4118. // member. Complain about it.
  4119. unsigned DK = diag::err_anonymous_record_bad_member;
  4120. if (isa<TypeDecl>(Mem))
  4121. DK = diag::err_anonymous_record_with_type;
  4122. else if (isa<FunctionDecl>(Mem))
  4123. DK = diag::err_anonymous_record_with_function;
  4124. else if (isa<VarDecl>(Mem))
  4125. DK = diag::err_anonymous_record_with_static;
  4126. // Visual C++ allows type definition in anonymous struct or union.
  4127. if (getLangOpts().MicrosoftExt &&
  4128. DK == diag::err_anonymous_record_with_type)
  4129. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4130. << Record->isUnion();
  4131. else {
  4132. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4133. Invalid = true;
  4134. }
  4135. }
  4136. }
  4137. // C++11 [class.union]p8 (DR1460):
  4138. // At most one variant member of a union may have a
  4139. // brace-or-equal-initializer.
  4140. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4141. Owner->isRecord())
  4142. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4143. cast<CXXRecordDecl>(Record));
  4144. }
  4145. if (!Record->isUnion() && !Owner->isRecord()) {
  4146. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4147. << getLangOpts().CPlusPlus;
  4148. Invalid = true;
  4149. }
  4150. // Mock up a declarator.
  4151. Declarator Dc(DS, Declarator::MemberContext);
  4152. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4153. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4154. // Create a declaration for this anonymous struct/union.
  4155. NamedDecl *Anon = nullptr;
  4156. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4157. Anon = FieldDecl::Create(Context, OwningClass,
  4158. DS.getLocStart(),
  4159. Record->getLocation(),
  4160. /*IdentifierInfo=*/nullptr,
  4161. Context.getTypeDeclType(Record),
  4162. TInfo,
  4163. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4164. /*InitStyle=*/ICIS_NoInit);
  4165. Anon->setAccess(AS);
  4166. if (getLangOpts().CPlusPlus)
  4167. FieldCollector->Add(cast<FieldDecl>(Anon));
  4168. } else {
  4169. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4170. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4171. if (SCSpec == DeclSpec::SCS_mutable) {
  4172. // mutable can only appear on non-static class members, so it's always
  4173. // an error here
  4174. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4175. Invalid = true;
  4176. SC = SC_None;
  4177. }
  4178. Anon = VarDecl::Create(Context, Owner,
  4179. DS.getLocStart(),
  4180. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4181. Context.getTypeDeclType(Record),
  4182. TInfo, SC);
  4183. // Default-initialize the implicit variable. This initialization will be
  4184. // trivial in almost all cases, except if a union member has an in-class
  4185. // initializer:
  4186. // union { int n = 0; };
  4187. ActOnUninitializedDecl(Anon);
  4188. }
  4189. Anon->setImplicit();
  4190. // Mark this as an anonymous struct/union type.
  4191. Record->setAnonymousStructOrUnion(true);
  4192. // Add the anonymous struct/union object to the current
  4193. // context. We'll be referencing this object when we refer to one of
  4194. // its members.
  4195. Owner->addDecl(Anon);
  4196. // Inject the members of the anonymous struct/union into the owning
  4197. // context and into the identifier resolver chain for name lookup
  4198. // purposes.
  4199. SmallVector<NamedDecl*, 2> Chain;
  4200. Chain.push_back(Anon);
  4201. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4202. Invalid = true;
  4203. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4204. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4205. Decl *ManglingContextDecl;
  4206. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4207. NewVD->getDeclContext(), ManglingContextDecl)) {
  4208. Context.setManglingNumber(
  4209. NewVD, MCtx->getManglingNumber(
  4210. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4211. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4212. }
  4213. }
  4214. }
  4215. if (Invalid)
  4216. Anon->setInvalidDecl();
  4217. return Anon;
  4218. }
  4219. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4220. /// Microsoft C anonymous structure.
  4221. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4222. /// Example:
  4223. ///
  4224. /// struct A { int a; };
  4225. /// struct B { struct A; int b; };
  4226. ///
  4227. /// void foo() {
  4228. /// B var;
  4229. /// var.a = 3;
  4230. /// }
  4231. ///
  4232. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4233. RecordDecl *Record) {
  4234. assert(Record && "expected a record!");
  4235. // Mock up a declarator.
  4236. Declarator Dc(DS, Declarator::TypeNameContext);
  4237. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4238. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4239. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4240. QualType RecTy = Context.getTypeDeclType(Record);
  4241. // Create a declaration for this anonymous struct.
  4242. NamedDecl *Anon = FieldDecl::Create(Context,
  4243. ParentDecl,
  4244. DS.getLocStart(),
  4245. DS.getLocStart(),
  4246. /*IdentifierInfo=*/nullptr,
  4247. RecTy,
  4248. TInfo,
  4249. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4250. /*InitStyle=*/ICIS_NoInit);
  4251. Anon->setImplicit();
  4252. // Add the anonymous struct object to the current context.
  4253. CurContext->addDecl(Anon);
  4254. // Inject the members of the anonymous struct into the current
  4255. // context and into the identifier resolver chain for name lookup
  4256. // purposes.
  4257. SmallVector<NamedDecl*, 2> Chain;
  4258. Chain.push_back(Anon);
  4259. RecordDecl *RecordDef = Record->getDefinition();
  4260. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4261. diag::err_field_incomplete) ||
  4262. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4263. AS_none, Chain)) {
  4264. Anon->setInvalidDecl();
  4265. ParentDecl->setInvalidDecl();
  4266. }
  4267. return Anon;
  4268. }
  4269. /// GetNameForDeclarator - Determine the full declaration name for the
  4270. /// given Declarator.
  4271. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4272. return GetNameFromUnqualifiedId(D.getName());
  4273. }
  4274. /// \brief Retrieves the declaration name from a parsed unqualified-id.
  4275. DeclarationNameInfo
  4276. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4277. DeclarationNameInfo NameInfo;
  4278. NameInfo.setLoc(Name.StartLocation);
  4279. switch (Name.getKind()) {
  4280. case UnqualifiedId::IK_ImplicitSelfParam:
  4281. case UnqualifiedId::IK_Identifier:
  4282. NameInfo.setName(Name.Identifier);
  4283. NameInfo.setLoc(Name.StartLocation);
  4284. return NameInfo;
  4285. case UnqualifiedId::IK_DeductionGuideName: {
  4286. // C++ [temp.deduct.guide]p3:
  4287. // The simple-template-id shall name a class template specialization.
  4288. // The template-name shall be the same identifier as the template-name
  4289. // of the simple-template-id.
  4290. // These together intend to imply that the template-name shall name a
  4291. // class template.
  4292. // FIXME: template<typename T> struct X {};
  4293. // template<typename T> using Y = X<T>;
  4294. // Y(int) -> Y<int>;
  4295. // satisfies these rules but does not name a class template.
  4296. TemplateName TN = Name.TemplateName.get().get();
  4297. auto *Template = TN.getAsTemplateDecl();
  4298. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4299. Diag(Name.StartLocation,
  4300. diag::err_deduction_guide_name_not_class_template)
  4301. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4302. if (Template)
  4303. Diag(Template->getLocation(), diag::note_template_decl_here);
  4304. return DeclarationNameInfo();
  4305. }
  4306. NameInfo.setName(
  4307. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4308. NameInfo.setLoc(Name.StartLocation);
  4309. return NameInfo;
  4310. }
  4311. case UnqualifiedId::IK_OperatorFunctionId:
  4312. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4313. Name.OperatorFunctionId.Operator));
  4314. NameInfo.setLoc(Name.StartLocation);
  4315. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4316. = Name.OperatorFunctionId.SymbolLocations[0];
  4317. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4318. = Name.EndLocation.getRawEncoding();
  4319. return NameInfo;
  4320. case UnqualifiedId::IK_LiteralOperatorId:
  4321. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4322. Name.Identifier));
  4323. NameInfo.setLoc(Name.StartLocation);
  4324. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4325. return NameInfo;
  4326. case UnqualifiedId::IK_ConversionFunctionId: {
  4327. TypeSourceInfo *TInfo;
  4328. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4329. if (Ty.isNull())
  4330. return DeclarationNameInfo();
  4331. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4332. Context.getCanonicalType(Ty)));
  4333. NameInfo.setLoc(Name.StartLocation);
  4334. NameInfo.setNamedTypeInfo(TInfo);
  4335. return NameInfo;
  4336. }
  4337. case UnqualifiedId::IK_ConstructorName: {
  4338. TypeSourceInfo *TInfo;
  4339. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4340. if (Ty.isNull())
  4341. return DeclarationNameInfo();
  4342. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4343. Context.getCanonicalType(Ty)));
  4344. NameInfo.setLoc(Name.StartLocation);
  4345. NameInfo.setNamedTypeInfo(TInfo);
  4346. return NameInfo;
  4347. }
  4348. case UnqualifiedId::IK_ConstructorTemplateId: {
  4349. // In well-formed code, we can only have a constructor
  4350. // template-id that refers to the current context, so go there
  4351. // to find the actual type being constructed.
  4352. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4353. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4354. return DeclarationNameInfo();
  4355. // Determine the type of the class being constructed.
  4356. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4357. // FIXME: Check two things: that the template-id names the same type as
  4358. // CurClassType, and that the template-id does not occur when the name
  4359. // was qualified.
  4360. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4361. Context.getCanonicalType(CurClassType)));
  4362. NameInfo.setLoc(Name.StartLocation);
  4363. // FIXME: should we retrieve TypeSourceInfo?
  4364. NameInfo.setNamedTypeInfo(nullptr);
  4365. return NameInfo;
  4366. }
  4367. case UnqualifiedId::IK_DestructorName: {
  4368. TypeSourceInfo *TInfo;
  4369. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4370. if (Ty.isNull())
  4371. return DeclarationNameInfo();
  4372. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4373. Context.getCanonicalType(Ty)));
  4374. NameInfo.setLoc(Name.StartLocation);
  4375. NameInfo.setNamedTypeInfo(TInfo);
  4376. return NameInfo;
  4377. }
  4378. case UnqualifiedId::IK_TemplateId: {
  4379. TemplateName TName = Name.TemplateId->Template.get();
  4380. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4381. return Context.getNameForTemplate(TName, TNameLoc);
  4382. }
  4383. } // switch (Name.getKind())
  4384. llvm_unreachable("Unknown name kind");
  4385. }
  4386. static QualType getCoreType(QualType Ty) {
  4387. do {
  4388. if (Ty->isPointerType() || Ty->isReferenceType())
  4389. Ty = Ty->getPointeeType();
  4390. else if (Ty->isArrayType())
  4391. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4392. else
  4393. return Ty.withoutLocalFastQualifiers();
  4394. } while (true);
  4395. }
  4396. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4397. /// and Definition have "nearly" matching parameters. This heuristic is
  4398. /// used to improve diagnostics in the case where an out-of-line function
  4399. /// definition doesn't match any declaration within the class or namespace.
  4400. /// Also sets Params to the list of indices to the parameters that differ
  4401. /// between the declaration and the definition. If hasSimilarParameters
  4402. /// returns true and Params is empty, then all of the parameters match.
  4403. static bool hasSimilarParameters(ASTContext &Context,
  4404. FunctionDecl *Declaration,
  4405. FunctionDecl *Definition,
  4406. SmallVectorImpl<unsigned> &Params) {
  4407. Params.clear();
  4408. if (Declaration->param_size() != Definition->param_size())
  4409. return false;
  4410. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4411. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4412. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4413. // The parameter types are identical
  4414. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4415. continue;
  4416. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4417. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4418. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4419. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4420. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4421. (DeclTyName && DeclTyName == DefTyName))
  4422. Params.push_back(Idx);
  4423. else // The two parameters aren't even close
  4424. return false;
  4425. }
  4426. return true;
  4427. }
  4428. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4429. /// declarator needs to be rebuilt in the current instantiation.
  4430. /// Any bits of declarator which appear before the name are valid for
  4431. /// consideration here. That's specifically the type in the decl spec
  4432. /// and the base type in any member-pointer chunks.
  4433. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4434. DeclarationName Name) {
  4435. // The types we specifically need to rebuild are:
  4436. // - typenames, typeofs, and decltypes
  4437. // - types which will become injected class names
  4438. // Of course, we also need to rebuild any type referencing such a
  4439. // type. It's safest to just say "dependent", but we call out a
  4440. // few cases here.
  4441. DeclSpec &DS = D.getMutableDeclSpec();
  4442. switch (DS.getTypeSpecType()) {
  4443. case DeclSpec::TST_typename:
  4444. case DeclSpec::TST_typeofType:
  4445. case DeclSpec::TST_underlyingType:
  4446. case DeclSpec::TST_atomic: {
  4447. // Grab the type from the parser.
  4448. TypeSourceInfo *TSI = nullptr;
  4449. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4450. if (T.isNull() || !T->isDependentType()) break;
  4451. // Make sure there's a type source info. This isn't really much
  4452. // of a waste; most dependent types should have type source info
  4453. // attached already.
  4454. if (!TSI)
  4455. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4456. // Rebuild the type in the current instantiation.
  4457. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4458. if (!TSI) return true;
  4459. // Store the new type back in the decl spec.
  4460. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4461. DS.UpdateTypeRep(LocType);
  4462. break;
  4463. }
  4464. case DeclSpec::TST_decltype:
  4465. case DeclSpec::TST_typeofExpr: {
  4466. Expr *E = DS.getRepAsExpr();
  4467. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4468. if (Result.isInvalid()) return true;
  4469. DS.UpdateExprRep(Result.get());
  4470. break;
  4471. }
  4472. default:
  4473. // Nothing to do for these decl specs.
  4474. break;
  4475. }
  4476. // It doesn't matter what order we do this in.
  4477. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4478. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4479. // The only type information in the declarator which can come
  4480. // before the declaration name is the base type of a member
  4481. // pointer.
  4482. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4483. continue;
  4484. // Rebuild the scope specifier in-place.
  4485. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4486. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4487. return true;
  4488. }
  4489. return false;
  4490. }
  4491. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4492. D.setFunctionDefinitionKind(FDK_Declaration);
  4493. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4494. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4495. Dcl && Dcl->getDeclContext()->isFileContext())
  4496. Dcl->setTopLevelDeclInObjCContainer();
  4497. if (getLangOpts().OpenCL)
  4498. setCurrentOpenCLExtensionForDecl(Dcl);
  4499. return Dcl;
  4500. }
  4501. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4502. /// If T is the name of a class, then each of the following shall have a
  4503. /// name different from T:
  4504. /// - every static data member of class T;
  4505. /// - every member function of class T
  4506. /// - every member of class T that is itself a type;
  4507. /// \returns true if the declaration name violates these rules.
  4508. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4509. DeclarationNameInfo NameInfo) {
  4510. DeclarationName Name = NameInfo.getName();
  4511. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4512. while (Record && Record->isAnonymousStructOrUnion())
  4513. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4514. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4515. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4516. return true;
  4517. }
  4518. return false;
  4519. }
  4520. /// \brief Diagnose a declaration whose declarator-id has the given
  4521. /// nested-name-specifier.
  4522. ///
  4523. /// \param SS The nested-name-specifier of the declarator-id.
  4524. ///
  4525. /// \param DC The declaration context to which the nested-name-specifier
  4526. /// resolves.
  4527. ///
  4528. /// \param Name The name of the entity being declared.
  4529. ///
  4530. /// \param Loc The location of the name of the entity being declared.
  4531. ///
  4532. /// \returns true if we cannot safely recover from this error, false otherwise.
  4533. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4534. DeclarationName Name,
  4535. SourceLocation Loc) {
  4536. DeclContext *Cur = CurContext;
  4537. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4538. Cur = Cur->getParent();
  4539. // If the user provided a superfluous scope specifier that refers back to the
  4540. // class in which the entity is already declared, diagnose and ignore it.
  4541. //
  4542. // class X {
  4543. // void X::f();
  4544. // };
  4545. //
  4546. // Note, it was once ill-formed to give redundant qualification in all
  4547. // contexts, but that rule was removed by DR482.
  4548. if (Cur->Equals(DC)) {
  4549. if (Cur->isRecord()) {
  4550. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4551. : diag::err_member_extra_qualification)
  4552. << Name << FixItHint::CreateRemoval(SS.getRange());
  4553. SS.clear();
  4554. } else {
  4555. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4556. }
  4557. return false;
  4558. }
  4559. // Check whether the qualifying scope encloses the scope of the original
  4560. // declaration.
  4561. if (!Cur->Encloses(DC)) {
  4562. if (Cur->isRecord())
  4563. Diag(Loc, diag::err_member_qualification)
  4564. << Name << SS.getRange();
  4565. else if (isa<TranslationUnitDecl>(DC))
  4566. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4567. << Name << SS.getRange();
  4568. else if (isa<FunctionDecl>(Cur))
  4569. Diag(Loc, diag::err_invalid_declarator_in_function)
  4570. << Name << SS.getRange();
  4571. else if (isa<BlockDecl>(Cur))
  4572. Diag(Loc, diag::err_invalid_declarator_in_block)
  4573. << Name << SS.getRange();
  4574. else
  4575. Diag(Loc, diag::err_invalid_declarator_scope)
  4576. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4577. return true;
  4578. }
  4579. if (Cur->isRecord()) {
  4580. // Cannot qualify members within a class.
  4581. Diag(Loc, diag::err_member_qualification)
  4582. << Name << SS.getRange();
  4583. SS.clear();
  4584. // C++ constructors and destructors with incorrect scopes can break
  4585. // our AST invariants by having the wrong underlying types. If
  4586. // that's the case, then drop this declaration entirely.
  4587. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4588. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4589. !Context.hasSameType(Name.getCXXNameType(),
  4590. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4591. return true;
  4592. return false;
  4593. }
  4594. // C++11 [dcl.meaning]p1:
  4595. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4596. // not begin with a decltype-specifer"
  4597. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4598. while (SpecLoc.getPrefix())
  4599. SpecLoc = SpecLoc.getPrefix();
  4600. if (dyn_cast_or_null<DecltypeType>(
  4601. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4602. Diag(Loc, diag::err_decltype_in_declarator)
  4603. << SpecLoc.getTypeLoc().getSourceRange();
  4604. return false;
  4605. }
  4606. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4607. MultiTemplateParamsArg TemplateParamLists) {
  4608. // TODO: consider using NameInfo for diagnostic.
  4609. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4610. DeclarationName Name = NameInfo.getName();
  4611. // All of these full declarators require an identifier. If it doesn't have
  4612. // one, the ParsedFreeStandingDeclSpec action should be used.
  4613. if (D.isDecompositionDeclarator()) {
  4614. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4615. } else if (!Name) {
  4616. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4617. Diag(D.getDeclSpec().getLocStart(),
  4618. diag::err_declarator_need_ident)
  4619. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4620. return nullptr;
  4621. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4622. return nullptr;
  4623. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4624. // we find one that is.
  4625. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4626. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4627. S = S->getParent();
  4628. DeclContext *DC = CurContext;
  4629. if (D.getCXXScopeSpec().isInvalid())
  4630. D.setInvalidType();
  4631. else if (D.getCXXScopeSpec().isSet()) {
  4632. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4633. UPPC_DeclarationQualifier))
  4634. return nullptr;
  4635. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4636. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4637. if (!DC || isa<EnumDecl>(DC)) {
  4638. // If we could not compute the declaration context, it's because the
  4639. // declaration context is dependent but does not refer to a class,
  4640. // class template, or class template partial specialization. Complain
  4641. // and return early, to avoid the coming semantic disaster.
  4642. Diag(D.getIdentifierLoc(),
  4643. diag::err_template_qualified_declarator_no_match)
  4644. << D.getCXXScopeSpec().getScopeRep()
  4645. << D.getCXXScopeSpec().getRange();
  4646. return nullptr;
  4647. }
  4648. bool IsDependentContext = DC->isDependentContext();
  4649. if (!IsDependentContext &&
  4650. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4651. return nullptr;
  4652. // If a class is incomplete, do not parse entities inside it.
  4653. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4654. Diag(D.getIdentifierLoc(),
  4655. diag::err_member_def_undefined_record)
  4656. << Name << DC << D.getCXXScopeSpec().getRange();
  4657. return nullptr;
  4658. }
  4659. if (!D.getDeclSpec().isFriendSpecified()) {
  4660. if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
  4661. Name, D.getIdentifierLoc())) {
  4662. if (DC->isRecord())
  4663. return nullptr;
  4664. D.setInvalidType();
  4665. }
  4666. }
  4667. // Check whether we need to rebuild the type of the given
  4668. // declaration in the current instantiation.
  4669. if (EnteringContext && IsDependentContext &&
  4670. TemplateParamLists.size() != 0) {
  4671. ContextRAII SavedContext(*this, DC);
  4672. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4673. D.setInvalidType();
  4674. }
  4675. }
  4676. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4677. QualType R = TInfo->getType();
  4678. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4679. UPPC_DeclarationType))
  4680. D.setInvalidType();
  4681. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4682. ForRedeclaration);
  4683. // See if this is a redefinition of a variable in the same scope.
  4684. if (!D.getCXXScopeSpec().isSet()) {
  4685. bool IsLinkageLookup = false;
  4686. bool CreateBuiltins = false;
  4687. // If the declaration we're planning to build will be a function
  4688. // or object with linkage, then look for another declaration with
  4689. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4690. //
  4691. // If the declaration we're planning to build will be declared with
  4692. // external linkage in the translation unit, create any builtin with
  4693. // the same name.
  4694. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4695. /* Do nothing*/;
  4696. else if (CurContext->isFunctionOrMethod() &&
  4697. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4698. R->isFunctionType())) {
  4699. IsLinkageLookup = true;
  4700. CreateBuiltins =
  4701. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4702. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4703. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4704. CreateBuiltins = true;
  4705. if (IsLinkageLookup)
  4706. Previous.clear(LookupRedeclarationWithLinkage);
  4707. LookupName(Previous, S, CreateBuiltins);
  4708. } else { // Something like "int foo::x;"
  4709. LookupQualifiedName(Previous, DC);
  4710. // C++ [dcl.meaning]p1:
  4711. // When the declarator-id is qualified, the declaration shall refer to a
  4712. // previously declared member of the class or namespace to which the
  4713. // qualifier refers (or, in the case of a namespace, of an element of the
  4714. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4715. // thereof; [...]
  4716. //
  4717. // Note that we already checked the context above, and that we do not have
  4718. // enough information to make sure that Previous contains the declaration
  4719. // we want to match. For example, given:
  4720. //
  4721. // class X {
  4722. // void f();
  4723. // void f(float);
  4724. // };
  4725. //
  4726. // void X::f(int) { } // ill-formed
  4727. //
  4728. // In this case, Previous will point to the overload set
  4729. // containing the two f's declared in X, but neither of them
  4730. // matches.
  4731. // C++ [dcl.meaning]p1:
  4732. // [...] the member shall not merely have been introduced by a
  4733. // using-declaration in the scope of the class or namespace nominated by
  4734. // the nested-name-specifier of the declarator-id.
  4735. RemoveUsingDecls(Previous);
  4736. }
  4737. if (Previous.isSingleResult() &&
  4738. Previous.getFoundDecl()->isTemplateParameter()) {
  4739. // Maybe we will complain about the shadowed template parameter.
  4740. if (!D.isInvalidType())
  4741. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4742. Previous.getFoundDecl());
  4743. // Just pretend that we didn't see the previous declaration.
  4744. Previous.clear();
  4745. }
  4746. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4747. // Forget that the previous declaration is the injected-class-name.
  4748. Previous.clear();
  4749. // In C++, the previous declaration we find might be a tag type
  4750. // (class or enum). In this case, the new declaration will hide the
  4751. // tag type. Note that this applies to functions, function templates, and
  4752. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4753. if (Previous.isSingleTagDecl() &&
  4754. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4755. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4756. Previous.clear();
  4757. // Check that there are no default arguments other than in the parameters
  4758. // of a function declaration (C++ only).
  4759. if (getLangOpts().CPlusPlus)
  4760. CheckExtraCXXDefaultArguments(D);
  4761. if (D.getDeclSpec().isConceptSpecified()) {
  4762. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  4763. // applied only to the definition of a function template or variable
  4764. // template, declared in namespace scope
  4765. if (!TemplateParamLists.size()) {
  4766. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4767. diag:: err_concept_wrong_decl_kind);
  4768. return nullptr;
  4769. }
  4770. if (!DC->getRedeclContext()->isFileContext()) {
  4771. Diag(D.getIdentifierLoc(),
  4772. diag::err_concept_decls_may_only_appear_in_namespace_scope);
  4773. return nullptr;
  4774. }
  4775. }
  4776. NamedDecl *New;
  4777. bool AddToScope = true;
  4778. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4779. if (TemplateParamLists.size()) {
  4780. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4781. return nullptr;
  4782. }
  4783. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4784. } else if (R->isFunctionType()) {
  4785. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4786. TemplateParamLists,
  4787. AddToScope);
  4788. } else {
  4789. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4790. AddToScope);
  4791. }
  4792. if (!New)
  4793. return nullptr;
  4794. // If this has an identifier and is not a function template specialization,
  4795. // add it to the scope stack.
  4796. if (New->getDeclName() && AddToScope) {
  4797. // Only make a locally-scoped extern declaration visible if it is the first
  4798. // declaration of this entity. Qualified lookup for such an entity should
  4799. // only find this declaration if there is no visible declaration of it.
  4800. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4801. PushOnScopeChains(New, S, AddToContext);
  4802. if (!AddToContext)
  4803. CurContext->addHiddenDecl(New);
  4804. }
  4805. if (isInOpenMPDeclareTargetContext())
  4806. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4807. return New;
  4808. }
  4809. /// Helper method to turn variable array types into constant array
  4810. /// types in certain situations which would otherwise be errors (for
  4811. /// GCC compatibility).
  4812. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4813. ASTContext &Context,
  4814. bool &SizeIsNegative,
  4815. llvm::APSInt &Oversized) {
  4816. // This method tries to turn a variable array into a constant
  4817. // array even when the size isn't an ICE. This is necessary
  4818. // for compatibility with code that depends on gcc's buggy
  4819. // constant expression folding, like struct {char x[(int)(char*)2];}
  4820. SizeIsNegative = false;
  4821. Oversized = 0;
  4822. if (T->isDependentType())
  4823. return QualType();
  4824. QualifierCollector Qs;
  4825. const Type *Ty = Qs.strip(T);
  4826. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4827. QualType Pointee = PTy->getPointeeType();
  4828. QualType FixedType =
  4829. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4830. Oversized);
  4831. if (FixedType.isNull()) return FixedType;
  4832. FixedType = Context.getPointerType(FixedType);
  4833. return Qs.apply(Context, FixedType);
  4834. }
  4835. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4836. QualType Inner = PTy->getInnerType();
  4837. QualType FixedType =
  4838. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4839. Oversized);
  4840. if (FixedType.isNull()) return FixedType;
  4841. FixedType = Context.getParenType(FixedType);
  4842. return Qs.apply(Context, FixedType);
  4843. }
  4844. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4845. if (!VLATy)
  4846. return QualType();
  4847. // FIXME: We should probably handle this case
  4848. if (VLATy->getElementType()->isVariablyModifiedType())
  4849. return QualType();
  4850. llvm::APSInt Res;
  4851. if (!VLATy->getSizeExpr() ||
  4852. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4853. return QualType();
  4854. // Check whether the array size is negative.
  4855. if (Res.isSigned() && Res.isNegative()) {
  4856. SizeIsNegative = true;
  4857. return QualType();
  4858. }
  4859. // Check whether the array is too large to be addressed.
  4860. unsigned ActiveSizeBits
  4861. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4862. Res);
  4863. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4864. Oversized = Res;
  4865. return QualType();
  4866. }
  4867. return Context.getConstantArrayType(VLATy->getElementType(),
  4868. Res, ArrayType::Normal, 0);
  4869. }
  4870. static void
  4871. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4872. SrcTL = SrcTL.getUnqualifiedLoc();
  4873. DstTL = DstTL.getUnqualifiedLoc();
  4874. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4875. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4876. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4877. DstPTL.getPointeeLoc());
  4878. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4879. return;
  4880. }
  4881. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4882. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4883. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4884. DstPTL.getInnerLoc());
  4885. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4886. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4887. return;
  4888. }
  4889. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4890. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4891. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4892. TypeLoc DstElemTL = DstATL.getElementLoc();
  4893. DstElemTL.initializeFullCopy(SrcElemTL);
  4894. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4895. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4896. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4897. }
  4898. /// Helper method to turn variable array types into constant array
  4899. /// types in certain situations which would otherwise be errors (for
  4900. /// GCC compatibility).
  4901. static TypeSourceInfo*
  4902. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4903. ASTContext &Context,
  4904. bool &SizeIsNegative,
  4905. llvm::APSInt &Oversized) {
  4906. QualType FixedTy
  4907. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4908. SizeIsNegative, Oversized);
  4909. if (FixedTy.isNull())
  4910. return nullptr;
  4911. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4912. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4913. FixedTInfo->getTypeLoc());
  4914. return FixedTInfo;
  4915. }
  4916. /// \brief Register the given locally-scoped extern "C" declaration so
  4917. /// that it can be found later for redeclarations. We include any extern "C"
  4918. /// declaration that is not visible in the translation unit here, not just
  4919. /// function-scope declarations.
  4920. void
  4921. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4922. if (!getLangOpts().CPlusPlus &&
  4923. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4924. // Don't need to track declarations in the TU in C.
  4925. return;
  4926. // Note that we have a locally-scoped external with this name.
  4927. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  4928. }
  4929. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  4930. // FIXME: We can have multiple results via __attribute__((overloadable)).
  4931. auto Result = Context.getExternCContextDecl()->lookup(Name);
  4932. return Result.empty() ? nullptr : *Result.begin();
  4933. }
  4934. /// \brief Diagnose function specifiers on a declaration of an identifier that
  4935. /// does not identify a function.
  4936. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  4937. // FIXME: We should probably indicate the identifier in question to avoid
  4938. // confusion for constructs like "virtual int a(), b;"
  4939. if (DS.isVirtualSpecified())
  4940. Diag(DS.getVirtualSpecLoc(),
  4941. diag::err_virtual_non_function);
  4942. if (DS.isExplicitSpecified())
  4943. Diag(DS.getExplicitSpecLoc(),
  4944. diag::err_explicit_non_function);
  4945. if (DS.isNoreturnSpecified())
  4946. Diag(DS.getNoreturnSpecLoc(),
  4947. diag::err_noreturn_non_function);
  4948. }
  4949. NamedDecl*
  4950. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  4951. TypeSourceInfo *TInfo, LookupResult &Previous) {
  4952. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  4953. if (D.getCXXScopeSpec().isSet()) {
  4954. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  4955. << D.getCXXScopeSpec().getRange();
  4956. D.setInvalidType();
  4957. // Pretend we didn't see the scope specifier.
  4958. DC = CurContext;
  4959. Previous.clear();
  4960. }
  4961. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  4962. if (D.getDeclSpec().isInlineSpecified())
  4963. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  4964. << getLangOpts().CPlusPlus1z;
  4965. if (D.getDeclSpec().isConstexprSpecified())
  4966. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  4967. << 1;
  4968. if (D.getDeclSpec().isConceptSpecified())
  4969. Diag(D.getDeclSpec().getConceptSpecLoc(),
  4970. diag::err_concept_wrong_decl_kind);
  4971. if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
  4972. if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
  4973. Diag(D.getName().StartLocation,
  4974. diag::err_deduction_guide_invalid_specifier)
  4975. << "typedef";
  4976. else
  4977. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  4978. << D.getName().getSourceRange();
  4979. return nullptr;
  4980. }
  4981. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  4982. if (!NewTD) return nullptr;
  4983. // Handle attributes prior to checking for duplicates in MergeVarDecl
  4984. ProcessDeclAttributes(S, NewTD, D);
  4985. CheckTypedefForVariablyModifiedType(S, NewTD);
  4986. bool Redeclaration = D.isRedeclaration();
  4987. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  4988. D.setRedeclaration(Redeclaration);
  4989. return ND;
  4990. }
  4991. void
  4992. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  4993. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  4994. // then it shall have block scope.
  4995. // Note that variably modified types must be fixed before merging the decl so
  4996. // that redeclarations will match.
  4997. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  4998. QualType T = TInfo->getType();
  4999. if (T->isVariablyModifiedType()) {
  5000. getCurFunction()->setHasBranchProtectedScope();
  5001. if (S->getFnParent() == nullptr) {
  5002. bool SizeIsNegative;
  5003. llvm::APSInt Oversized;
  5004. TypeSourceInfo *FixedTInfo =
  5005. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5006. SizeIsNegative,
  5007. Oversized);
  5008. if (FixedTInfo) {
  5009. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5010. NewTD->setTypeSourceInfo(FixedTInfo);
  5011. } else {
  5012. if (SizeIsNegative)
  5013. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5014. else if (T->isVariableArrayType())
  5015. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5016. else if (Oversized.getBoolValue())
  5017. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5018. << Oversized.toString(10);
  5019. else
  5020. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5021. NewTD->setInvalidDecl();
  5022. }
  5023. }
  5024. }
  5025. }
  5026. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5027. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5028. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5029. NamedDecl*
  5030. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5031. LookupResult &Previous, bool &Redeclaration) {
  5032. // Find the shadowed declaration before filtering for scope.
  5033. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5034. // Merge the decl with the existing one if appropriate. If the decl is
  5035. // in an outer scope, it isn't the same thing.
  5036. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5037. /*AllowInlineNamespace*/false);
  5038. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5039. if (!Previous.empty()) {
  5040. Redeclaration = true;
  5041. MergeTypedefNameDecl(S, NewTD, Previous);
  5042. }
  5043. if (ShadowedDecl && !Redeclaration)
  5044. CheckShadow(NewTD, ShadowedDecl, Previous);
  5045. // If this is the C FILE type, notify the AST context.
  5046. if (IdentifierInfo *II = NewTD->getIdentifier())
  5047. if (!NewTD->isInvalidDecl() &&
  5048. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5049. if (II->isStr("FILE"))
  5050. Context.setFILEDecl(NewTD);
  5051. else if (II->isStr("jmp_buf"))
  5052. Context.setjmp_bufDecl(NewTD);
  5053. else if (II->isStr("sigjmp_buf"))
  5054. Context.setsigjmp_bufDecl(NewTD);
  5055. else if (II->isStr("ucontext_t"))
  5056. Context.setucontext_tDecl(NewTD);
  5057. }
  5058. return NewTD;
  5059. }
  5060. /// \brief Determines whether the given declaration is an out-of-scope
  5061. /// previous declaration.
  5062. ///
  5063. /// This routine should be invoked when name lookup has found a
  5064. /// previous declaration (PrevDecl) that is not in the scope where a
  5065. /// new declaration by the same name is being introduced. If the new
  5066. /// declaration occurs in a local scope, previous declarations with
  5067. /// linkage may still be considered previous declarations (C99
  5068. /// 6.2.2p4-5, C++ [basic.link]p6).
  5069. ///
  5070. /// \param PrevDecl the previous declaration found by name
  5071. /// lookup
  5072. ///
  5073. /// \param DC the context in which the new declaration is being
  5074. /// declared.
  5075. ///
  5076. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5077. /// for a new delcaration with the same name.
  5078. static bool
  5079. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5080. ASTContext &Context) {
  5081. if (!PrevDecl)
  5082. return false;
  5083. if (!PrevDecl->hasLinkage())
  5084. return false;
  5085. if (Context.getLangOpts().CPlusPlus) {
  5086. // C++ [basic.link]p6:
  5087. // If there is a visible declaration of an entity with linkage
  5088. // having the same name and type, ignoring entities declared
  5089. // outside the innermost enclosing namespace scope, the block
  5090. // scope declaration declares that same entity and receives the
  5091. // linkage of the previous declaration.
  5092. DeclContext *OuterContext = DC->getRedeclContext();
  5093. if (!OuterContext->isFunctionOrMethod())
  5094. // This rule only applies to block-scope declarations.
  5095. return false;
  5096. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5097. if (PrevOuterContext->isRecord())
  5098. // We found a member function: ignore it.
  5099. return false;
  5100. // Find the innermost enclosing namespace for the new and
  5101. // previous declarations.
  5102. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5103. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5104. // The previous declaration is in a different namespace, so it
  5105. // isn't the same function.
  5106. if (!OuterContext->Equals(PrevOuterContext))
  5107. return false;
  5108. }
  5109. return true;
  5110. }
  5111. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  5112. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5113. if (!SS.isSet()) return;
  5114. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  5115. }
  5116. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5117. QualType type = decl->getType();
  5118. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5119. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5120. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5121. unsigned kind = -1U;
  5122. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5123. if (var->hasAttr<BlocksAttr>())
  5124. kind = 0; // __block
  5125. else if (!var->hasLocalStorage())
  5126. kind = 1; // global
  5127. } else if (isa<ObjCIvarDecl>(decl)) {
  5128. kind = 3; // ivar
  5129. } else if (isa<FieldDecl>(decl)) {
  5130. kind = 2; // field
  5131. }
  5132. if (kind != -1U) {
  5133. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5134. << kind;
  5135. }
  5136. } else if (lifetime == Qualifiers::OCL_None) {
  5137. // Try to infer lifetime.
  5138. if (!type->isObjCLifetimeType())
  5139. return false;
  5140. lifetime = type->getObjCARCImplicitLifetime();
  5141. type = Context.getLifetimeQualifiedType(type, lifetime);
  5142. decl->setType(type);
  5143. }
  5144. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5145. // Thread-local variables cannot have lifetime.
  5146. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5147. var->getTLSKind()) {
  5148. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5149. << var->getType();
  5150. return true;
  5151. }
  5152. }
  5153. return false;
  5154. }
  5155. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5156. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5157. // the wrong linkage.
  5158. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5159. // 'weak' only applies to declarations with external linkage.
  5160. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5161. if (!ND.isExternallyVisible()) {
  5162. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5163. ND.dropAttr<WeakAttr>();
  5164. }
  5165. }
  5166. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5167. if (ND.isExternallyVisible()) {
  5168. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5169. ND.dropAttr<WeakRefAttr>();
  5170. ND.dropAttr<AliasAttr>();
  5171. }
  5172. }
  5173. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5174. if (VD->hasInit()) {
  5175. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5176. assert(VD->isThisDeclarationADefinition() &&
  5177. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5178. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5179. VD->dropAttr<AliasAttr>();
  5180. }
  5181. }
  5182. }
  5183. // 'selectany' only applies to externally visible variable declarations.
  5184. // It does not apply to functions.
  5185. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5186. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5187. S.Diag(Attr->getLocation(),
  5188. diag::err_attribute_selectany_non_extern_data);
  5189. ND.dropAttr<SelectAnyAttr>();
  5190. }
  5191. }
  5192. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5193. // dll attributes require external linkage. Static locals may have external
  5194. // linkage but still cannot be explicitly imported or exported.
  5195. auto *VD = dyn_cast<VarDecl>(&ND);
  5196. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  5197. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5198. << &ND << Attr;
  5199. ND.setInvalidDecl();
  5200. }
  5201. }
  5202. // Virtual functions cannot be marked as 'notail'.
  5203. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5204. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5205. if (MD->isVirtual()) {
  5206. S.Diag(ND.getLocation(),
  5207. diag::err_invalid_attribute_on_virtual_function)
  5208. << Attr;
  5209. ND.dropAttr<NotTailCalledAttr>();
  5210. }
  5211. }
  5212. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5213. NamedDecl *NewDecl,
  5214. bool IsSpecialization,
  5215. bool IsDefinition) {
  5216. if (OldDecl->isInvalidDecl())
  5217. return;
  5218. bool IsTemplate = false;
  5219. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5220. OldDecl = OldTD->getTemplatedDecl();
  5221. IsTemplate = true;
  5222. if (!IsSpecialization)
  5223. IsDefinition = false;
  5224. }
  5225. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5226. NewDecl = NewTD->getTemplatedDecl();
  5227. IsTemplate = true;
  5228. }
  5229. if (!OldDecl || !NewDecl)
  5230. return;
  5231. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5232. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5233. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5234. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5235. // dllimport and dllexport are inheritable attributes so we have to exclude
  5236. // inherited attribute instances.
  5237. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5238. (NewExportAttr && !NewExportAttr->isInherited());
  5239. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5240. // the only exception being explicit specializations.
  5241. // Implicitly generated declarations are also excluded for now because there
  5242. // is no other way to switch these to use dllimport or dllexport.
  5243. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5244. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5245. // Allow with a warning for free functions and global variables.
  5246. bool JustWarn = false;
  5247. if (!OldDecl->isCXXClassMember()) {
  5248. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5249. if (VD && !VD->getDescribedVarTemplate())
  5250. JustWarn = true;
  5251. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5252. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5253. JustWarn = true;
  5254. }
  5255. // We cannot change a declaration that's been used because IR has already
  5256. // been emitted. Dllimported functions will still work though (modulo
  5257. // address equality) as they can use the thunk.
  5258. if (OldDecl->isUsed())
  5259. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5260. JustWarn = false;
  5261. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5262. : diag::err_attribute_dll_redeclaration;
  5263. S.Diag(NewDecl->getLocation(), DiagID)
  5264. << NewDecl
  5265. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5266. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5267. if (!JustWarn) {
  5268. NewDecl->setInvalidDecl();
  5269. return;
  5270. }
  5271. }
  5272. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5273. // exceptions being inline function definitions (except for function
  5274. // templates), local extern declarations, qualified friend declarations or
  5275. // special MSVC extension: in the last case, the declaration is treated as if
  5276. // it were marked dllexport.
  5277. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5278. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5279. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5280. // Ignore static data because out-of-line definitions are diagnosed
  5281. // separately.
  5282. IsStaticDataMember = VD->isStaticDataMember();
  5283. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5284. VarDecl::DeclarationOnly;
  5285. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5286. IsInline = FD->isInlined();
  5287. IsQualifiedFriend = FD->getQualifier() &&
  5288. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5289. }
  5290. if (OldImportAttr && !HasNewAttr &&
  5291. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5292. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5293. if (IsMicrosoft && IsDefinition) {
  5294. S.Diag(NewDecl->getLocation(),
  5295. diag::warn_redeclaration_without_import_attribute)
  5296. << NewDecl;
  5297. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5298. NewDecl->dropAttr<DLLImportAttr>();
  5299. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5300. NewImportAttr->getRange(), S.Context,
  5301. NewImportAttr->getSpellingListIndex()));
  5302. } else {
  5303. S.Diag(NewDecl->getLocation(),
  5304. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5305. << NewDecl << OldImportAttr;
  5306. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5307. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5308. OldDecl->dropAttr<DLLImportAttr>();
  5309. NewDecl->dropAttr<DLLImportAttr>();
  5310. }
  5311. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5312. // In MinGW, seeing a function declared inline drops the dllimport attribute.
  5313. OldDecl->dropAttr<DLLImportAttr>();
  5314. NewDecl->dropAttr<DLLImportAttr>();
  5315. S.Diag(NewDecl->getLocation(),
  5316. diag::warn_dllimport_dropped_from_inline_function)
  5317. << NewDecl << OldImportAttr;
  5318. }
  5319. }
  5320. /// Given that we are within the definition of the given function,
  5321. /// will that definition behave like C99's 'inline', where the
  5322. /// definition is discarded except for optimization purposes?
  5323. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5324. // Try to avoid calling GetGVALinkageForFunction.
  5325. // All cases of this require the 'inline' keyword.
  5326. if (!FD->isInlined()) return false;
  5327. // This is only possible in C++ with the gnu_inline attribute.
  5328. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5329. return false;
  5330. // Okay, go ahead and call the relatively-more-expensive function.
  5331. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5332. }
  5333. /// Determine whether a variable is extern "C" prior to attaching
  5334. /// an initializer. We can't just call isExternC() here, because that
  5335. /// will also compute and cache whether the declaration is externally
  5336. /// visible, which might change when we attach the initializer.
  5337. ///
  5338. /// This can only be used if the declaration is known to not be a
  5339. /// redeclaration of an internal linkage declaration.
  5340. ///
  5341. /// For instance:
  5342. ///
  5343. /// auto x = []{};
  5344. ///
  5345. /// Attaching the initializer here makes this declaration not externally
  5346. /// visible, because its type has internal linkage.
  5347. ///
  5348. /// FIXME: This is a hack.
  5349. template<typename T>
  5350. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5351. if (S.getLangOpts().CPlusPlus) {
  5352. // In C++, the overloadable attribute negates the effects of extern "C".
  5353. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5354. return false;
  5355. // So do CUDA's host/device attributes.
  5356. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5357. D->template hasAttr<CUDAHostAttr>()))
  5358. return false;
  5359. }
  5360. return D->isExternC();
  5361. }
  5362. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5363. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5364. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
  5365. return VD->hasExternalStorage();
  5366. if (DC->isFileContext())
  5367. return true;
  5368. if (DC->isRecord())
  5369. return false;
  5370. llvm_unreachable("Unexpected context");
  5371. }
  5372. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5373. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5374. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5375. isa<OMPDeclareReductionDecl>(DC))
  5376. return true;
  5377. if (DC->isRecord())
  5378. return false;
  5379. llvm_unreachable("Unexpected context");
  5380. }
  5381. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  5382. AttributeList::Kind Kind) {
  5383. for (const AttributeList *L = AttrList; L; L = L->getNext())
  5384. if (L->getKind() == Kind)
  5385. return true;
  5386. return false;
  5387. }
  5388. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5389. AttributeList::Kind Kind) {
  5390. // Check decl attributes on the DeclSpec.
  5391. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
  5392. return true;
  5393. // Walk the declarator structure, checking decl attributes that were in a type
  5394. // position to the decl itself.
  5395. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5396. if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  5397. return true;
  5398. }
  5399. // Finally, check attributes on the decl itself.
  5400. return hasParsedAttr(S, PD.getAttributes(), Kind);
  5401. }
  5402. /// Adjust the \c DeclContext for a function or variable that might be a
  5403. /// function-local external declaration.
  5404. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5405. if (!DC->isFunctionOrMethod())
  5406. return false;
  5407. // If this is a local extern function or variable declared within a function
  5408. // template, don't add it into the enclosing namespace scope until it is
  5409. // instantiated; it might have a dependent type right now.
  5410. if (DC->isDependentContext())
  5411. return true;
  5412. // C++11 [basic.link]p7:
  5413. // When a block scope declaration of an entity with linkage is not found to
  5414. // refer to some other declaration, then that entity is a member of the
  5415. // innermost enclosing namespace.
  5416. //
  5417. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5418. // semantically-enclosing namespace, not a lexically-enclosing one.
  5419. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5420. DC = DC->getParent();
  5421. return true;
  5422. }
  5423. /// \brief Returns true if given declaration has external C language linkage.
  5424. static bool isDeclExternC(const Decl *D) {
  5425. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5426. return FD->isExternC();
  5427. if (const auto *VD = dyn_cast<VarDecl>(D))
  5428. return VD->isExternC();
  5429. llvm_unreachable("Unknown type of decl!");
  5430. }
  5431. NamedDecl *Sema::ActOnVariableDeclarator(
  5432. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5433. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5434. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5435. QualType R = TInfo->getType();
  5436. DeclarationName Name = GetNameForDeclarator(D).getName();
  5437. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5438. if (D.isDecompositionDeclarator()) {
  5439. AddToScope = false;
  5440. // Take the name of the first declarator as our name for diagnostic
  5441. // purposes.
  5442. auto &Decomp = D.getDecompositionDeclarator();
  5443. if (!Decomp.bindings().empty()) {
  5444. II = Decomp.bindings()[0].Name;
  5445. Name = II;
  5446. }
  5447. } else if (!II) {
  5448. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5449. return nullptr;
  5450. }
  5451. if (getLangOpts().OpenCL) {
  5452. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5453. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5454. // argument.
  5455. if (R->isImageType() || R->isPipeType()) {
  5456. Diag(D.getIdentifierLoc(),
  5457. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5458. << R;
  5459. D.setInvalidType();
  5460. return nullptr;
  5461. }
  5462. // OpenCL v1.2 s6.9.r:
  5463. // The event type cannot be used to declare a program scope variable.
  5464. // OpenCL v2.0 s6.9.q:
  5465. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5466. if (NULL == S->getParent()) {
  5467. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5468. Diag(D.getIdentifierLoc(),
  5469. diag::err_invalid_type_for_program_scope_var) << R;
  5470. D.setInvalidType();
  5471. return nullptr;
  5472. }
  5473. }
  5474. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5475. QualType NR = R;
  5476. while (NR->isPointerType()) {
  5477. if (NR->isFunctionPointerType()) {
  5478. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5479. D.setInvalidType();
  5480. break;
  5481. }
  5482. NR = NR->getPointeeType();
  5483. }
  5484. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5485. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5486. // half array type (unless the cl_khr_fp16 extension is enabled).
  5487. if (Context.getBaseElementType(R)->isHalfType()) {
  5488. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5489. D.setInvalidType();
  5490. }
  5491. }
  5492. if (R->isSamplerT()) {
  5493. // OpenCL v1.2 s6.9.b p4:
  5494. // The sampler type cannot be used with the __local and __global address
  5495. // space qualifiers.
  5496. if (R.getAddressSpace() == LangAS::opencl_local ||
  5497. R.getAddressSpace() == LangAS::opencl_global) {
  5498. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5499. }
  5500. // OpenCL v1.2 s6.12.14.1:
  5501. // A global sampler must be declared with either the constant address
  5502. // space qualifier or with the const qualifier.
  5503. if (DC->isTranslationUnit() &&
  5504. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5505. R.isConstQualified())) {
  5506. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5507. D.setInvalidType();
  5508. }
  5509. }
  5510. // OpenCL v1.2 s6.9.r:
  5511. // The event type cannot be used with the __local, __constant and __global
  5512. // address space qualifiers.
  5513. if (R->isEventT()) {
  5514. if (R.getAddressSpace()) {
  5515. Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
  5516. D.setInvalidType();
  5517. }
  5518. }
  5519. }
  5520. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5521. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5522. // dllimport globals without explicit storage class are treated as extern. We
  5523. // have to change the storage class this early to get the right DeclContext.
  5524. if (SC == SC_None && !DC->isRecord() &&
  5525. hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
  5526. !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
  5527. SC = SC_Extern;
  5528. DeclContext *OriginalDC = DC;
  5529. bool IsLocalExternDecl = SC == SC_Extern &&
  5530. adjustContextForLocalExternDecl(DC);
  5531. if (SCSpec == DeclSpec::SCS_mutable) {
  5532. // mutable can only appear on non-static class members, so it's always
  5533. // an error here
  5534. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5535. D.setInvalidType();
  5536. SC = SC_None;
  5537. }
  5538. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5539. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5540. D.getDeclSpec().getStorageClassSpecLoc())) {
  5541. // In C++11, the 'register' storage class specifier is deprecated.
  5542. // Suppress the warning in system macros, it's used in macros in some
  5543. // popular C system headers, such as in glibc's htonl() macro.
  5544. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5545. getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
  5546. : diag::warn_deprecated_register)
  5547. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5548. }
  5549. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5550. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5551. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5552. // appear in the declaration specifiers in an external declaration.
  5553. // Global Register+Asm is a GNU extension we support.
  5554. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5555. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5556. D.setInvalidType();
  5557. }
  5558. }
  5559. bool IsMemberSpecialization = false;
  5560. bool IsVariableTemplateSpecialization = false;
  5561. bool IsPartialSpecialization = false;
  5562. bool IsVariableTemplate = false;
  5563. VarDecl *NewVD = nullptr;
  5564. VarTemplateDecl *NewTemplate = nullptr;
  5565. TemplateParameterList *TemplateParams = nullptr;
  5566. if (!getLangOpts().CPlusPlus) {
  5567. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5568. D.getIdentifierLoc(), II,
  5569. R, TInfo, SC);
  5570. if (R->getContainedDeducedType())
  5571. ParsingInitForAutoVars.insert(NewVD);
  5572. if (D.isInvalidType())
  5573. NewVD->setInvalidDecl();
  5574. } else {
  5575. bool Invalid = false;
  5576. if (DC->isRecord() && !CurContext->isRecord()) {
  5577. // This is an out-of-line definition of a static data member.
  5578. switch (SC) {
  5579. case SC_None:
  5580. break;
  5581. case SC_Static:
  5582. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5583. diag::err_static_out_of_line)
  5584. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5585. break;
  5586. case SC_Auto:
  5587. case SC_Register:
  5588. case SC_Extern:
  5589. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5590. // to names of variables declared in a block or to function parameters.
  5591. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5592. // of class members
  5593. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5594. diag::err_storage_class_for_static_member)
  5595. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5596. break;
  5597. case SC_PrivateExtern:
  5598. llvm_unreachable("C storage class in c++!");
  5599. }
  5600. }
  5601. if (SC == SC_Static && CurContext->isRecord()) {
  5602. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5603. if (RD->isLocalClass())
  5604. Diag(D.getIdentifierLoc(),
  5605. diag::err_static_data_member_not_allowed_in_local_class)
  5606. << Name << RD->getDeclName();
  5607. // C++98 [class.union]p1: If a union contains a static data member,
  5608. // the program is ill-formed. C++11 drops this restriction.
  5609. if (RD->isUnion())
  5610. Diag(D.getIdentifierLoc(),
  5611. getLangOpts().CPlusPlus11
  5612. ? diag::warn_cxx98_compat_static_data_member_in_union
  5613. : diag::ext_static_data_member_in_union) << Name;
  5614. // We conservatively disallow static data members in anonymous structs.
  5615. else if (!RD->getDeclName())
  5616. Diag(D.getIdentifierLoc(),
  5617. diag::err_static_data_member_not_allowed_in_anon_struct)
  5618. << Name << RD->isUnion();
  5619. }
  5620. }
  5621. // Match up the template parameter lists with the scope specifier, then
  5622. // determine whether we have a template or a template specialization.
  5623. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5624. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5625. D.getCXXScopeSpec(),
  5626. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  5627. ? D.getName().TemplateId
  5628. : nullptr,
  5629. TemplateParamLists,
  5630. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5631. if (TemplateParams) {
  5632. if (!TemplateParams->size() &&
  5633. D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  5634. // There is an extraneous 'template<>' for this variable. Complain
  5635. // about it, but allow the declaration of the variable.
  5636. Diag(TemplateParams->getTemplateLoc(),
  5637. diag::err_template_variable_noparams)
  5638. << II
  5639. << SourceRange(TemplateParams->getTemplateLoc(),
  5640. TemplateParams->getRAngleLoc());
  5641. TemplateParams = nullptr;
  5642. } else {
  5643. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  5644. // This is an explicit specialization or a partial specialization.
  5645. // FIXME: Check that we can declare a specialization here.
  5646. IsVariableTemplateSpecialization = true;
  5647. IsPartialSpecialization = TemplateParams->size() > 0;
  5648. } else { // if (TemplateParams->size() > 0)
  5649. // This is a template declaration.
  5650. IsVariableTemplate = true;
  5651. // Check that we can declare a template here.
  5652. if (CheckTemplateDeclScope(S, TemplateParams))
  5653. return nullptr;
  5654. // Only C++1y supports variable templates (N3651).
  5655. Diag(D.getIdentifierLoc(),
  5656. getLangOpts().CPlusPlus14
  5657. ? diag::warn_cxx11_compat_variable_template
  5658. : diag::ext_variable_template);
  5659. }
  5660. }
  5661. } else {
  5662. assert(
  5663. (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
  5664. "should have a 'template<>' for this decl");
  5665. }
  5666. if (IsVariableTemplateSpecialization) {
  5667. SourceLocation TemplateKWLoc =
  5668. TemplateParamLists.size() > 0
  5669. ? TemplateParamLists[0]->getTemplateLoc()
  5670. : SourceLocation();
  5671. DeclResult Res = ActOnVarTemplateSpecialization(
  5672. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5673. IsPartialSpecialization);
  5674. if (Res.isInvalid())
  5675. return nullptr;
  5676. NewVD = cast<VarDecl>(Res.get());
  5677. AddToScope = false;
  5678. } else if (D.isDecompositionDeclarator()) {
  5679. NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
  5680. D.getIdentifierLoc(), R, TInfo, SC,
  5681. Bindings);
  5682. } else
  5683. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5684. D.getIdentifierLoc(), II, R, TInfo, SC);
  5685. // If this is supposed to be a variable template, create it as such.
  5686. if (IsVariableTemplate) {
  5687. NewTemplate =
  5688. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5689. TemplateParams, NewVD);
  5690. NewVD->setDescribedVarTemplate(NewTemplate);
  5691. }
  5692. // If this decl has an auto type in need of deduction, make a note of the
  5693. // Decl so we can diagnose uses of it in its own initializer.
  5694. if (R->getContainedDeducedType())
  5695. ParsingInitForAutoVars.insert(NewVD);
  5696. if (D.isInvalidType() || Invalid) {
  5697. NewVD->setInvalidDecl();
  5698. if (NewTemplate)
  5699. NewTemplate->setInvalidDecl();
  5700. }
  5701. SetNestedNameSpecifier(NewVD, D);
  5702. // If we have any template parameter lists that don't directly belong to
  5703. // the variable (matching the scope specifier), store them.
  5704. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5705. if (TemplateParamLists.size() > VDTemplateParamLists)
  5706. NewVD->setTemplateParameterListsInfo(
  5707. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5708. if (D.getDeclSpec().isConstexprSpecified()) {
  5709. NewVD->setConstexpr(true);
  5710. // C++1z [dcl.spec.constexpr]p1:
  5711. // A static data member declared with the constexpr specifier is
  5712. // implicitly an inline variable.
  5713. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
  5714. NewVD->setImplicitlyInline();
  5715. }
  5716. if (D.getDeclSpec().isConceptSpecified()) {
  5717. if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
  5718. VTD->setConcept();
  5719. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  5720. // be declared with the thread_local, inline, friend, or constexpr
  5721. // specifiers, [...]
  5722. if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
  5723. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5724. diag::err_concept_decl_invalid_specifiers)
  5725. << 0 << 0;
  5726. NewVD->setInvalidDecl(true);
  5727. }
  5728. if (D.getDeclSpec().isConstexprSpecified()) {
  5729. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5730. diag::err_concept_decl_invalid_specifiers)
  5731. << 0 << 3;
  5732. NewVD->setInvalidDecl(true);
  5733. }
  5734. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  5735. // applied only to the definition of a function template or variable
  5736. // template, declared in namespace scope.
  5737. if (IsVariableTemplateSpecialization) {
  5738. Diag(D.getDeclSpec().getConceptSpecLoc(),
  5739. diag::err_concept_specified_specialization)
  5740. << (IsPartialSpecialization ? 2 : 1);
  5741. }
  5742. // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
  5743. // following restrictions:
  5744. // - The declared type shall have the type bool.
  5745. if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
  5746. !NewVD->isInvalidDecl()) {
  5747. Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
  5748. NewVD->setInvalidDecl(true);
  5749. }
  5750. }
  5751. }
  5752. if (D.getDeclSpec().isInlineSpecified()) {
  5753. if (!getLangOpts().CPlusPlus) {
  5754. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5755. << 0;
  5756. } else if (CurContext->isFunctionOrMethod()) {
  5757. // 'inline' is not allowed on block scope variable declaration.
  5758. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5759. diag::err_inline_declaration_block_scope) << Name
  5760. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5761. } else {
  5762. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5763. getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
  5764. : diag::ext_inline_variable);
  5765. NewVD->setInlineSpecified();
  5766. }
  5767. }
  5768. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5769. // lexical context will be different from the semantic context.
  5770. NewVD->setLexicalDeclContext(CurContext);
  5771. if (NewTemplate)
  5772. NewTemplate->setLexicalDeclContext(CurContext);
  5773. if (IsLocalExternDecl) {
  5774. if (D.isDecompositionDeclarator())
  5775. for (auto *B : Bindings)
  5776. B->setLocalExternDecl();
  5777. else
  5778. NewVD->setLocalExternDecl();
  5779. }
  5780. bool EmitTLSUnsupportedError = false;
  5781. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5782. // C++11 [dcl.stc]p4:
  5783. // When thread_local is applied to a variable of block scope the
  5784. // storage-class-specifier static is implied if it does not appear
  5785. // explicitly.
  5786. // Core issue: 'static' is not implied if the variable is declared
  5787. // 'extern'.
  5788. if (NewVD->hasLocalStorage() &&
  5789. (SCSpec != DeclSpec::SCS_unspecified ||
  5790. TSCS != DeclSpec::TSCS_thread_local ||
  5791. !DC->isFunctionOrMethod()))
  5792. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5793. diag::err_thread_non_global)
  5794. << DeclSpec::getSpecifierName(TSCS);
  5795. else if (!Context.getTargetInfo().isTLSSupported()) {
  5796. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5797. // Postpone error emission until we've collected attributes required to
  5798. // figure out whether it's a host or device variable and whether the
  5799. // error should be ignored.
  5800. EmitTLSUnsupportedError = true;
  5801. // We still need to mark the variable as TLS so it shows up in AST with
  5802. // proper storage class for other tools to use even if we're not going
  5803. // to emit any code for it.
  5804. NewVD->setTSCSpec(TSCS);
  5805. } else
  5806. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5807. diag::err_thread_unsupported);
  5808. } else
  5809. NewVD->setTSCSpec(TSCS);
  5810. }
  5811. // C99 6.7.4p3
  5812. // An inline definition of a function with external linkage shall
  5813. // not contain a definition of a modifiable object with static or
  5814. // thread storage duration...
  5815. // We only apply this when the function is required to be defined
  5816. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5817. // that a local variable with thread storage duration still has to
  5818. // be marked 'static'. Also note that it's possible to get these
  5819. // semantics in C++ using __attribute__((gnu_inline)).
  5820. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5821. !NewVD->getType().isConstQualified()) {
  5822. FunctionDecl *CurFD = getCurFunctionDecl();
  5823. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5824. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5825. diag::warn_static_local_in_extern_inline);
  5826. MaybeSuggestAddingStaticToDecl(CurFD);
  5827. }
  5828. }
  5829. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5830. if (IsVariableTemplateSpecialization)
  5831. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5832. << (IsPartialSpecialization ? 1 : 0)
  5833. << FixItHint::CreateRemoval(
  5834. D.getDeclSpec().getModulePrivateSpecLoc());
  5835. else if (IsMemberSpecialization)
  5836. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5837. << 2
  5838. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5839. else if (NewVD->hasLocalStorage())
  5840. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5841. << 0 << NewVD->getDeclName()
  5842. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5843. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5844. else {
  5845. NewVD->setModulePrivate();
  5846. if (NewTemplate)
  5847. NewTemplate->setModulePrivate();
  5848. for (auto *B : Bindings)
  5849. B->setModulePrivate();
  5850. }
  5851. }
  5852. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5853. ProcessDeclAttributes(S, NewVD, D);
  5854. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5855. if (EmitTLSUnsupportedError &&
  5856. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  5857. (getLangOpts().OpenMPIsDevice &&
  5858. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  5859. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5860. diag::err_thread_unsupported);
  5861. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5862. // storage [duration]."
  5863. if (SC == SC_None && S->getFnParent() != nullptr &&
  5864. (NewVD->hasAttr<CUDASharedAttr>() ||
  5865. NewVD->hasAttr<CUDAConstantAttr>())) {
  5866. NewVD->setStorageClass(SC_Static);
  5867. }
  5868. }
  5869. // Ensure that dllimport globals without explicit storage class are treated as
  5870. // extern. The storage class is set above using parsed attributes. Now we can
  5871. // check the VarDecl itself.
  5872. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5873. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5874. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5875. // In auto-retain/release, infer strong retension for variables of
  5876. // retainable type.
  5877. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5878. NewVD->setInvalidDecl();
  5879. // Handle GNU asm-label extension (encoded as an attribute).
  5880. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5881. // The parser guarantees this is a string.
  5882. StringLiteral *SE = cast<StringLiteral>(E);
  5883. StringRef Label = SE->getString();
  5884. if (S->getFnParent() != nullptr) {
  5885. switch (SC) {
  5886. case SC_None:
  5887. case SC_Auto:
  5888. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5889. break;
  5890. case SC_Register:
  5891. // Local Named register
  5892. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5893. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5894. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5895. break;
  5896. case SC_Static:
  5897. case SC_Extern:
  5898. case SC_PrivateExtern:
  5899. break;
  5900. }
  5901. } else if (SC == SC_Register) {
  5902. // Global Named register
  5903. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5904. const auto &TI = Context.getTargetInfo();
  5905. bool HasSizeMismatch;
  5906. if (!TI.isValidGCCRegisterName(Label))
  5907. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5908. else if (!TI.validateGlobalRegisterVariable(Label,
  5909. Context.getTypeSize(R),
  5910. HasSizeMismatch))
  5911. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5912. else if (HasSizeMismatch)
  5913. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5914. }
  5915. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5916. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5917. NewVD->setInvalidDecl(true);
  5918. }
  5919. }
  5920. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  5921. Context, Label, 0));
  5922. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  5923. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  5924. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  5925. if (I != ExtnameUndeclaredIdentifiers.end()) {
  5926. if (isDeclExternC(NewVD)) {
  5927. NewVD->addAttr(I->second);
  5928. ExtnameUndeclaredIdentifiers.erase(I);
  5929. } else
  5930. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  5931. << /*Variable*/1 << NewVD;
  5932. }
  5933. }
  5934. // Find the shadowed declaration before filtering for scope.
  5935. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  5936. ? getShadowedDeclaration(NewVD, Previous)
  5937. : nullptr;
  5938. // Don't consider existing declarations that are in a different
  5939. // scope and are out-of-semantic-context declarations (if the new
  5940. // declaration has linkage).
  5941. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  5942. D.getCXXScopeSpec().isNotEmpty() ||
  5943. IsMemberSpecialization ||
  5944. IsVariableTemplateSpecialization);
  5945. // Check whether the previous declaration is in the same block scope. This
  5946. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  5947. if (getLangOpts().CPlusPlus &&
  5948. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  5949. NewVD->setPreviousDeclInSameBlockScope(
  5950. Previous.isSingleResult() && !Previous.isShadowed() &&
  5951. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  5952. if (!getLangOpts().CPlusPlus) {
  5953. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5954. } else {
  5955. // If this is an explicit specialization of a static data member, check it.
  5956. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  5957. CheckMemberSpecialization(NewVD, Previous))
  5958. NewVD->setInvalidDecl();
  5959. // Merge the decl with the existing one if appropriate.
  5960. if (!Previous.empty()) {
  5961. if (Previous.isSingleResult() &&
  5962. isa<FieldDecl>(Previous.getFoundDecl()) &&
  5963. D.getCXXScopeSpec().isSet()) {
  5964. // The user tried to define a non-static data member
  5965. // out-of-line (C++ [dcl.meaning]p1).
  5966. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  5967. << D.getCXXScopeSpec().getRange();
  5968. Previous.clear();
  5969. NewVD->setInvalidDecl();
  5970. }
  5971. } else if (D.getCXXScopeSpec().isSet()) {
  5972. // No previous declaration in the qualifying scope.
  5973. Diag(D.getIdentifierLoc(), diag::err_no_member)
  5974. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  5975. << D.getCXXScopeSpec().getRange();
  5976. NewVD->setInvalidDecl();
  5977. }
  5978. if (!IsVariableTemplateSpecialization)
  5979. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  5980. // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
  5981. // an explicit specialization (14.8.3) or a partial specialization of a
  5982. // concept definition.
  5983. if (IsVariableTemplateSpecialization &&
  5984. !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
  5985. Previous.isSingleResult()) {
  5986. NamedDecl *PreviousDecl = Previous.getFoundDecl();
  5987. if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
  5988. if (VarTmpl->isConcept()) {
  5989. Diag(NewVD->getLocation(), diag::err_concept_specialized)
  5990. << 1 /*variable*/
  5991. << (IsPartialSpecialization ? 2 /*partially specialized*/
  5992. : 1 /*explicitly specialized*/);
  5993. Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
  5994. NewVD->setInvalidDecl();
  5995. }
  5996. }
  5997. }
  5998. if (NewTemplate) {
  5999. VarTemplateDecl *PrevVarTemplate =
  6000. NewVD->getPreviousDecl()
  6001. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6002. : nullptr;
  6003. // Check the template parameter list of this declaration, possibly
  6004. // merging in the template parameter list from the previous variable
  6005. // template declaration.
  6006. if (CheckTemplateParameterList(
  6007. TemplateParams,
  6008. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6009. : nullptr,
  6010. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6011. DC->isDependentContext())
  6012. ? TPC_ClassTemplateMember
  6013. : TPC_VarTemplate))
  6014. NewVD->setInvalidDecl();
  6015. // If we are providing an explicit specialization of a static variable
  6016. // template, make a note of that.
  6017. if (PrevVarTemplate &&
  6018. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6019. PrevVarTemplate->setMemberSpecialization();
  6020. }
  6021. }
  6022. // Diagnose shadowed variables iff this isn't a redeclaration.
  6023. if (ShadowedDecl && !D.isRedeclaration())
  6024. CheckShadow(NewVD, ShadowedDecl, Previous);
  6025. ProcessPragmaWeak(S, NewVD);
  6026. // If this is the first declaration of an extern C variable, update
  6027. // the map of such variables.
  6028. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6029. isIncompleteDeclExternC(*this, NewVD))
  6030. RegisterLocallyScopedExternCDecl(NewVD, S);
  6031. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6032. Decl *ManglingContextDecl;
  6033. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6034. NewVD->getDeclContext(), ManglingContextDecl)) {
  6035. Context.setManglingNumber(
  6036. NewVD, MCtx->getManglingNumber(
  6037. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6038. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6039. }
  6040. }
  6041. // Special handling of variable named 'main'.
  6042. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6043. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6044. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6045. // C++ [basic.start.main]p3
  6046. // A program that declares a variable main at global scope is ill-formed.
  6047. if (getLangOpts().CPlusPlus)
  6048. Diag(D.getLocStart(), diag::err_main_global_variable);
  6049. // In C, and external-linkage variable named main results in undefined
  6050. // behavior.
  6051. else if (NewVD->hasExternalFormalLinkage())
  6052. Diag(D.getLocStart(), diag::warn_main_redefined);
  6053. }
  6054. if (D.isRedeclaration() && !Previous.empty()) {
  6055. checkDLLAttributeRedeclaration(
  6056. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
  6057. IsMemberSpecialization, D.isFunctionDefinition());
  6058. }
  6059. if (NewTemplate) {
  6060. if (NewVD->isInvalidDecl())
  6061. NewTemplate->setInvalidDecl();
  6062. ActOnDocumentableDecl(NewTemplate);
  6063. return NewTemplate;
  6064. }
  6065. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6066. CompleteMemberSpecialization(NewVD, Previous);
  6067. return NewVD;
  6068. }
  6069. /// Enum describing the %select options in diag::warn_decl_shadow.
  6070. enum ShadowedDeclKind {
  6071. SDK_Local,
  6072. SDK_Global,
  6073. SDK_StaticMember,
  6074. SDK_Field,
  6075. SDK_Typedef,
  6076. SDK_Using
  6077. };
  6078. /// Determine what kind of declaration we're shadowing.
  6079. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6080. const DeclContext *OldDC) {
  6081. if (isa<TypeAliasDecl>(ShadowedDecl))
  6082. return SDK_Using;
  6083. else if (isa<TypedefDecl>(ShadowedDecl))
  6084. return SDK_Typedef;
  6085. else if (isa<RecordDecl>(OldDC))
  6086. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6087. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6088. }
  6089. /// Return the location of the capture if the given lambda captures the given
  6090. /// variable \p VD, or an invalid source location otherwise.
  6091. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6092. const VarDecl *VD) {
  6093. for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
  6094. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6095. return Capture.getLocation();
  6096. }
  6097. return SourceLocation();
  6098. }
  6099. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6100. const LookupResult &R) {
  6101. // Only diagnose if we're shadowing an unambiguous field or variable.
  6102. if (R.getResultKind() != LookupResult::Found)
  6103. return false;
  6104. // Return false if warning is ignored.
  6105. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6106. }
  6107. /// \brief Return the declaration shadowed by the given variable \p D, or null
  6108. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6109. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6110. const LookupResult &R) {
  6111. if (!shouldWarnIfShadowedDecl(Diags, R))
  6112. return nullptr;
  6113. // Don't diagnose declarations at file scope.
  6114. if (D->hasGlobalStorage())
  6115. return nullptr;
  6116. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6117. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6118. ? ShadowedDecl
  6119. : nullptr;
  6120. }
  6121. /// \brief Return the declaration shadowed by the given typedef \p D, or null
  6122. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6123. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6124. const LookupResult &R) {
  6125. // Don't warn if typedef declaration is part of a class
  6126. if (D->getDeclContext()->isRecord())
  6127. return nullptr;
  6128. if (!shouldWarnIfShadowedDecl(Diags, R))
  6129. return nullptr;
  6130. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6131. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6132. }
  6133. /// \brief Diagnose variable or built-in function shadowing. Implements
  6134. /// -Wshadow.
  6135. ///
  6136. /// This method is called whenever a VarDecl is added to a "useful"
  6137. /// scope.
  6138. ///
  6139. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6140. /// \param R the lookup of the name
  6141. ///
  6142. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6143. const LookupResult &R) {
  6144. DeclContext *NewDC = D->getDeclContext();
  6145. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6146. // Fields are not shadowed by variables in C++ static methods.
  6147. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6148. if (MD->isStatic())
  6149. return;
  6150. // Fields shadowed by constructor parameters are a special case. Usually
  6151. // the constructor initializes the field with the parameter.
  6152. if (isa<CXXConstructorDecl>(NewDC))
  6153. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6154. // Remember that this was shadowed so we can either warn about its
  6155. // modification or its existence depending on warning settings.
  6156. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6157. return;
  6158. }
  6159. }
  6160. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6161. if (shadowedVar->isExternC()) {
  6162. // For shadowing external vars, make sure that we point to the global
  6163. // declaration, not a locally scoped extern declaration.
  6164. for (auto I : shadowedVar->redecls())
  6165. if (I->isFileVarDecl()) {
  6166. ShadowedDecl = I;
  6167. break;
  6168. }
  6169. }
  6170. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6171. unsigned WarningDiag = diag::warn_decl_shadow;
  6172. SourceLocation CaptureLoc;
  6173. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6174. isa<CXXMethodDecl>(NewDC)) {
  6175. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6176. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6177. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6178. // Try to avoid warnings for lambdas with an explicit capture list.
  6179. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6180. // Warn only when the lambda captures the shadowed decl explicitly.
  6181. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6182. if (CaptureLoc.isInvalid())
  6183. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6184. } else {
  6185. // Remember that this was shadowed so we can avoid the warning if the
  6186. // shadowed decl isn't captured and the warning settings allow it.
  6187. cast<LambdaScopeInfo>(getCurFunction())
  6188. ->ShadowingDecls.push_back(
  6189. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6190. return;
  6191. }
  6192. }
  6193. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6194. // A variable can't shadow a local variable in an enclosing scope, if
  6195. // they are separated by a non-capturing declaration context.
  6196. for (DeclContext *ParentDC = NewDC;
  6197. ParentDC && !ParentDC->Equals(OldDC);
  6198. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6199. // Only block literals, captured statements, and lambda expressions
  6200. // can capture; other scopes don't.
  6201. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6202. !isLambdaCallOperator(ParentDC)) {
  6203. return;
  6204. }
  6205. }
  6206. }
  6207. }
  6208. }
  6209. // Only warn about certain kinds of shadowing for class members.
  6210. if (NewDC && NewDC->isRecord()) {
  6211. // In particular, don't warn about shadowing non-class members.
  6212. if (!OldDC->isRecord())
  6213. return;
  6214. // TODO: should we warn about static data members shadowing
  6215. // static data members from base classes?
  6216. // TODO: don't diagnose for inaccessible shadowed members.
  6217. // This is hard to do perfectly because we might friend the
  6218. // shadowing context, but that's just a false negative.
  6219. }
  6220. DeclarationName Name = R.getLookupName();
  6221. // Emit warning and note.
  6222. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6223. return;
  6224. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6225. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6226. if (!CaptureLoc.isInvalid())
  6227. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6228. << Name << /*explicitly*/ 1;
  6229. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6230. }
  6231. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6232. /// when these variables are captured by the lambda.
  6233. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6234. for (const auto &Shadow : LSI->ShadowingDecls) {
  6235. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6236. // Try to avoid the warning when the shadowed decl isn't captured.
  6237. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6238. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6239. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6240. ? diag::warn_decl_shadow_uncaptured_local
  6241. : diag::warn_decl_shadow)
  6242. << Shadow.VD->getDeclName()
  6243. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6244. if (!CaptureLoc.isInvalid())
  6245. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6246. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6247. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6248. }
  6249. }
  6250. /// \brief Check -Wshadow without the advantage of a previous lookup.
  6251. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6252. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6253. return;
  6254. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6255. Sema::LookupOrdinaryName, Sema::ForRedeclaration);
  6256. LookupName(R, S);
  6257. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6258. CheckShadow(D, ShadowedDecl, R);
  6259. }
  6260. /// Check if 'E', which is an expression that is about to be modified, refers
  6261. /// to a constructor parameter that shadows a field.
  6262. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6263. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6264. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6265. return;
  6266. E = E->IgnoreParenImpCasts();
  6267. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6268. if (!DRE)
  6269. return;
  6270. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6271. auto I = ShadowingDecls.find(D);
  6272. if (I == ShadowingDecls.end())
  6273. return;
  6274. const NamedDecl *ShadowedDecl = I->second;
  6275. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6276. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6277. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6278. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6279. // Avoid issuing multiple warnings about the same decl.
  6280. ShadowingDecls.erase(I);
  6281. }
  6282. /// Check for conflict between this global or extern "C" declaration and
  6283. /// previous global or extern "C" declarations. This is only used in C++.
  6284. template<typename T>
  6285. static bool checkGlobalOrExternCConflict(
  6286. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6287. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6288. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6289. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6290. // The common case: this global doesn't conflict with any extern "C"
  6291. // declaration.
  6292. return false;
  6293. }
  6294. if (Prev) {
  6295. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6296. // Both the old and new declarations have C language linkage. This is a
  6297. // redeclaration.
  6298. Previous.clear();
  6299. Previous.addDecl(Prev);
  6300. return true;
  6301. }
  6302. // This is a global, non-extern "C" declaration, and there is a previous
  6303. // non-global extern "C" declaration. Diagnose if this is a variable
  6304. // declaration.
  6305. if (!isa<VarDecl>(ND))
  6306. return false;
  6307. } else {
  6308. // The declaration is extern "C". Check for any declaration in the
  6309. // translation unit which might conflict.
  6310. if (IsGlobal) {
  6311. // We have already performed the lookup into the translation unit.
  6312. IsGlobal = false;
  6313. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6314. I != E; ++I) {
  6315. if (isa<VarDecl>(*I)) {
  6316. Prev = *I;
  6317. break;
  6318. }
  6319. }
  6320. } else {
  6321. DeclContext::lookup_result R =
  6322. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6323. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6324. I != E; ++I) {
  6325. if (isa<VarDecl>(*I)) {
  6326. Prev = *I;
  6327. break;
  6328. }
  6329. // FIXME: If we have any other entity with this name in global scope,
  6330. // the declaration is ill-formed, but that is a defect: it breaks the
  6331. // 'stat' hack, for instance. Only variables can have mangled name
  6332. // clashes with extern "C" declarations, so only they deserve a
  6333. // diagnostic.
  6334. }
  6335. }
  6336. if (!Prev)
  6337. return false;
  6338. }
  6339. // Use the first declaration's location to ensure we point at something which
  6340. // is lexically inside an extern "C" linkage-spec.
  6341. assert(Prev && "should have found a previous declaration to diagnose");
  6342. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6343. Prev = FD->getFirstDecl();
  6344. else
  6345. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6346. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6347. << IsGlobal << ND;
  6348. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6349. << IsGlobal;
  6350. return false;
  6351. }
  6352. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6353. /// if we have found that this is a redeclaration of some prior entity.
  6354. ///
  6355. /// Per C++ [dcl.link]p6:
  6356. /// Two declarations [for a function or variable] with C language linkage
  6357. /// with the same name that appear in different scopes refer to the same
  6358. /// [entity]. An entity with C language linkage shall not be declared with
  6359. /// the same name as an entity in global scope.
  6360. template<typename T>
  6361. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6362. LookupResult &Previous) {
  6363. if (!S.getLangOpts().CPlusPlus) {
  6364. // In C, when declaring a global variable, look for a corresponding 'extern'
  6365. // variable declared in function scope. We don't need this in C++, because
  6366. // we find local extern decls in the surrounding file-scope DeclContext.
  6367. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6368. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6369. Previous.clear();
  6370. Previous.addDecl(Prev);
  6371. return true;
  6372. }
  6373. }
  6374. return false;
  6375. }
  6376. // A declaration in the translation unit can conflict with an extern "C"
  6377. // declaration.
  6378. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6379. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6380. // An extern "C" declaration can conflict with a declaration in the
  6381. // translation unit or can be a redeclaration of an extern "C" declaration
  6382. // in another scope.
  6383. if (isIncompleteDeclExternC(S,ND))
  6384. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6385. // Neither global nor extern "C": nothing to do.
  6386. return false;
  6387. }
  6388. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6389. // If the decl is already known invalid, don't check it.
  6390. if (NewVD->isInvalidDecl())
  6391. return;
  6392. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  6393. QualType T = TInfo->getType();
  6394. // Defer checking an 'auto' type until its initializer is attached.
  6395. if (T->isUndeducedType())
  6396. return;
  6397. if (NewVD->hasAttrs())
  6398. CheckAlignasUnderalignment(NewVD);
  6399. if (T->isObjCObjectType()) {
  6400. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6401. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6402. T = Context.getObjCObjectPointerType(T);
  6403. NewVD->setType(T);
  6404. }
  6405. // Emit an error if an address space was applied to decl with local storage.
  6406. // This includes arrays of objects with address space qualifiers, but not
  6407. // automatic variables that point to other address spaces.
  6408. // ISO/IEC TR 18037 S5.1.2
  6409. if (!getLangOpts().OpenCL
  6410. && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
  6411. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6412. NewVD->setInvalidDecl();
  6413. return;
  6414. }
  6415. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6416. // scope.
  6417. if (getLangOpts().OpenCLVersion == 120 &&
  6418. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6419. NewVD->isStaticLocal()) {
  6420. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6421. NewVD->setInvalidDecl();
  6422. return;
  6423. }
  6424. if (getLangOpts().OpenCL) {
  6425. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6426. if (NewVD->hasAttr<BlocksAttr>()) {
  6427. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6428. return;
  6429. }
  6430. if (T->isBlockPointerType()) {
  6431. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6432. // can't use 'extern' storage class.
  6433. if (!T.isConstQualified()) {
  6434. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6435. << 0 /*const*/;
  6436. NewVD->setInvalidDecl();
  6437. return;
  6438. }
  6439. if (NewVD->hasExternalStorage()) {
  6440. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6441. NewVD->setInvalidDecl();
  6442. return;
  6443. }
  6444. }
  6445. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  6446. // __constant address space.
  6447. // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
  6448. // variables inside a function can also be declared in the global
  6449. // address space.
  6450. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6451. NewVD->hasExternalStorage()) {
  6452. if (!T->isSamplerT() &&
  6453. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6454. (T.getAddressSpace() == LangAS::opencl_global &&
  6455. getLangOpts().OpenCLVersion == 200))) {
  6456. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6457. if (getLangOpts().OpenCLVersion == 200)
  6458. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6459. << Scope << "global or constant";
  6460. else
  6461. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6462. << Scope << "constant";
  6463. NewVD->setInvalidDecl();
  6464. return;
  6465. }
  6466. } else {
  6467. if (T.getAddressSpace() == LangAS::opencl_global) {
  6468. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6469. << 1 /*is any function*/ << "global";
  6470. NewVD->setInvalidDecl();
  6471. return;
  6472. }
  6473. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6474. T.getAddressSpace() == LangAS::opencl_local) {
  6475. FunctionDecl *FD = getCurFunctionDecl();
  6476. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6477. // in functions.
  6478. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6479. if (T.getAddressSpace() == LangAS::opencl_constant)
  6480. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6481. << 0 /*non-kernel only*/ << "constant";
  6482. else
  6483. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6484. << 0 /*non-kernel only*/ << "local";
  6485. NewVD->setInvalidDecl();
  6486. return;
  6487. }
  6488. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6489. // in the outermost scope of a kernel function.
  6490. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6491. if (!getCurScope()->isFunctionScope()) {
  6492. if (T.getAddressSpace() == LangAS::opencl_constant)
  6493. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6494. << "constant";
  6495. else
  6496. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6497. << "local";
  6498. NewVD->setInvalidDecl();
  6499. return;
  6500. }
  6501. }
  6502. } else if (T.getAddressSpace() != LangAS::Default) {
  6503. // Do not allow other address spaces on automatic variable.
  6504. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6505. NewVD->setInvalidDecl();
  6506. return;
  6507. }
  6508. }
  6509. }
  6510. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6511. && !NewVD->hasAttr<BlocksAttr>()) {
  6512. if (getLangOpts().getGC() != LangOptions::NonGC)
  6513. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6514. else {
  6515. assert(!getLangOpts().ObjCAutoRefCount);
  6516. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6517. }
  6518. }
  6519. bool isVM = T->isVariablyModifiedType();
  6520. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6521. NewVD->hasAttr<BlocksAttr>())
  6522. getCurFunction()->setHasBranchProtectedScope();
  6523. if ((isVM && NewVD->hasLinkage()) ||
  6524. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6525. bool SizeIsNegative;
  6526. llvm::APSInt Oversized;
  6527. TypeSourceInfo *FixedTInfo =
  6528. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  6529. SizeIsNegative, Oversized);
  6530. if (!FixedTInfo && T->isVariableArrayType()) {
  6531. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6532. // FIXME: This won't give the correct result for
  6533. // int a[10][n];
  6534. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6535. if (NewVD->isFileVarDecl())
  6536. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6537. << SizeRange;
  6538. else if (NewVD->isStaticLocal())
  6539. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6540. << SizeRange;
  6541. else
  6542. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6543. << SizeRange;
  6544. NewVD->setInvalidDecl();
  6545. return;
  6546. }
  6547. if (!FixedTInfo) {
  6548. if (NewVD->isFileVarDecl())
  6549. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6550. else
  6551. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6552. NewVD->setInvalidDecl();
  6553. return;
  6554. }
  6555. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6556. NewVD->setType(FixedTInfo->getType());
  6557. NewVD->setTypeSourceInfo(FixedTInfo);
  6558. }
  6559. if (T->isVoidType()) {
  6560. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6561. // of objects and functions.
  6562. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6563. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6564. << T;
  6565. NewVD->setInvalidDecl();
  6566. return;
  6567. }
  6568. }
  6569. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6570. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6571. NewVD->setInvalidDecl();
  6572. return;
  6573. }
  6574. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6575. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6576. NewVD->setInvalidDecl();
  6577. return;
  6578. }
  6579. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6580. RequireLiteralType(NewVD->getLocation(), T,
  6581. diag::err_constexpr_var_non_literal)) {
  6582. NewVD->setInvalidDecl();
  6583. return;
  6584. }
  6585. }
  6586. /// \brief Perform semantic checking on a newly-created variable
  6587. /// declaration.
  6588. ///
  6589. /// This routine performs all of the type-checking required for a
  6590. /// variable declaration once it has been built. It is used both to
  6591. /// check variables after they have been parsed and their declarators
  6592. /// have been translated into a declaration, and to check variables
  6593. /// that have been instantiated from a template.
  6594. ///
  6595. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6596. ///
  6597. /// Returns true if the variable declaration is a redeclaration.
  6598. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6599. CheckVariableDeclarationType(NewVD);
  6600. // If the decl is already known invalid, don't check it.
  6601. if (NewVD->isInvalidDecl())
  6602. return false;
  6603. // If we did not find anything by this name, look for a non-visible
  6604. // extern "C" declaration with the same name.
  6605. if (Previous.empty() &&
  6606. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6607. Previous.setShadowed();
  6608. if (!Previous.empty()) {
  6609. MergeVarDecl(NewVD, Previous);
  6610. return true;
  6611. }
  6612. return false;
  6613. }
  6614. namespace {
  6615. struct FindOverriddenMethod {
  6616. Sema *S;
  6617. CXXMethodDecl *Method;
  6618. /// Member lookup function that determines whether a given C++
  6619. /// method overrides a method in a base class, to be used with
  6620. /// CXXRecordDecl::lookupInBases().
  6621. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6622. RecordDecl *BaseRecord =
  6623. Specifier->getType()->getAs<RecordType>()->getDecl();
  6624. DeclarationName Name = Method->getDeclName();
  6625. // FIXME: Do we care about other names here too?
  6626. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6627. // We really want to find the base class destructor here.
  6628. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6629. CanQualType CT = S->Context.getCanonicalType(T);
  6630. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6631. }
  6632. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6633. Path.Decls = Path.Decls.slice(1)) {
  6634. NamedDecl *D = Path.Decls.front();
  6635. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6636. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6637. return true;
  6638. }
  6639. }
  6640. return false;
  6641. }
  6642. };
  6643. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6644. } // end anonymous namespace
  6645. /// \brief Report an error regarding overriding, along with any relevant
  6646. /// overriden methods.
  6647. ///
  6648. /// \param DiagID the primary error to report.
  6649. /// \param MD the overriding method.
  6650. /// \param OEK which overrides to include as notes.
  6651. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6652. OverrideErrorKind OEK = OEK_All) {
  6653. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6654. for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
  6655. E = MD->end_overridden_methods();
  6656. I != E; ++I) {
  6657. // This check (& the OEK parameter) could be replaced by a predicate, but
  6658. // without lambdas that would be overkill. This is still nicer than writing
  6659. // out the diag loop 3 times.
  6660. if ((OEK == OEK_All) ||
  6661. (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
  6662. (OEK == OEK_Deleted && (*I)->isDeleted()))
  6663. S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
  6664. }
  6665. }
  6666. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6667. /// and if so, check that it's a valid override and remember it.
  6668. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6669. // Look for methods in base classes that this method might override.
  6670. CXXBasePaths Paths;
  6671. FindOverriddenMethod FOM;
  6672. FOM.Method = MD;
  6673. FOM.S = this;
  6674. bool hasDeletedOverridenMethods = false;
  6675. bool hasNonDeletedOverridenMethods = false;
  6676. bool AddedAny = false;
  6677. if (DC->lookupInBases(FOM, Paths)) {
  6678. for (auto *I : Paths.found_decls()) {
  6679. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6680. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6681. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6682. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6683. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6684. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6685. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6686. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6687. AddedAny = true;
  6688. }
  6689. }
  6690. }
  6691. }
  6692. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6693. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6694. }
  6695. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6696. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6697. }
  6698. return AddedAny;
  6699. }
  6700. namespace {
  6701. // Struct for holding all of the extra arguments needed by
  6702. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6703. struct ActOnFDArgs {
  6704. Scope *S;
  6705. Declarator &D;
  6706. MultiTemplateParamsArg TemplateParamLists;
  6707. bool AddToScope;
  6708. };
  6709. } // end anonymous namespace
  6710. namespace {
  6711. // Callback to only accept typo corrections that have a non-zero edit distance.
  6712. // Also only accept corrections that have the same parent decl.
  6713. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6714. public:
  6715. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6716. CXXRecordDecl *Parent)
  6717. : Context(Context), OriginalFD(TypoFD),
  6718. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6719. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6720. if (candidate.getEditDistance() == 0)
  6721. return false;
  6722. SmallVector<unsigned, 1> MismatchedParams;
  6723. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6724. CDeclEnd = candidate.end();
  6725. CDecl != CDeclEnd; ++CDecl) {
  6726. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6727. if (FD && !FD->hasBody() &&
  6728. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6729. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6730. CXXRecordDecl *Parent = MD->getParent();
  6731. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6732. return true;
  6733. } else if (!ExpectedParent) {
  6734. return true;
  6735. }
  6736. }
  6737. }
  6738. return false;
  6739. }
  6740. private:
  6741. ASTContext &Context;
  6742. FunctionDecl *OriginalFD;
  6743. CXXRecordDecl *ExpectedParent;
  6744. };
  6745. } // end anonymous namespace
  6746. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6747. TypoCorrectedFunctionDefinitions.insert(F);
  6748. }
  6749. /// \brief Generate diagnostics for an invalid function redeclaration.
  6750. ///
  6751. /// This routine handles generating the diagnostic messages for an invalid
  6752. /// function redeclaration, including finding possible similar declarations
  6753. /// or performing typo correction if there are no previous declarations with
  6754. /// the same name.
  6755. ///
  6756. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6757. /// the new declaration name does not cause new errors.
  6758. static NamedDecl *DiagnoseInvalidRedeclaration(
  6759. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6760. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6761. DeclarationName Name = NewFD->getDeclName();
  6762. DeclContext *NewDC = NewFD->getDeclContext();
  6763. SmallVector<unsigned, 1> MismatchedParams;
  6764. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6765. TypoCorrection Correction;
  6766. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6767. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  6768. : diag::err_member_decl_does_not_match;
  6769. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6770. IsLocalFriend ? Sema::LookupLocalFriendName
  6771. : Sema::LookupOrdinaryName,
  6772. Sema::ForRedeclaration);
  6773. NewFD->setInvalidDecl();
  6774. if (IsLocalFriend)
  6775. SemaRef.LookupName(Prev, S);
  6776. else
  6777. SemaRef.LookupQualifiedName(Prev, NewDC);
  6778. assert(!Prev.isAmbiguous() &&
  6779. "Cannot have an ambiguity in previous-declaration lookup");
  6780. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6781. if (!Prev.empty()) {
  6782. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6783. Func != FuncEnd; ++Func) {
  6784. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6785. if (FD &&
  6786. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6787. // Add 1 to the index so that 0 can mean the mismatch didn't
  6788. // involve a parameter
  6789. unsigned ParamNum =
  6790. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6791. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6792. }
  6793. }
  6794. // If the qualified name lookup yielded nothing, try typo correction
  6795. } else if ((Correction = SemaRef.CorrectTypo(
  6796. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6797. &ExtraArgs.D.getCXXScopeSpec(),
  6798. llvm::make_unique<DifferentNameValidatorCCC>(
  6799. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6800. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6801. // Set up everything for the call to ActOnFunctionDeclarator
  6802. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6803. ExtraArgs.D.getIdentifierLoc());
  6804. Previous.clear();
  6805. Previous.setLookupName(Correction.getCorrection());
  6806. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6807. CDeclEnd = Correction.end();
  6808. CDecl != CDeclEnd; ++CDecl) {
  6809. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6810. if (FD && !FD->hasBody() &&
  6811. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6812. Previous.addDecl(FD);
  6813. }
  6814. }
  6815. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6816. NamedDecl *Result;
  6817. // Retry building the function declaration with the new previous
  6818. // declarations, and with errors suppressed.
  6819. {
  6820. // Trap errors.
  6821. Sema::SFINAETrap Trap(SemaRef);
  6822. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6823. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6824. // eliminate the need for the parameter pack ExtraArgs.
  6825. Result = SemaRef.ActOnFunctionDeclarator(
  6826. ExtraArgs.S, ExtraArgs.D,
  6827. Correction.getCorrectionDecl()->getDeclContext(),
  6828. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6829. ExtraArgs.AddToScope);
  6830. if (Trap.hasErrorOccurred())
  6831. Result = nullptr;
  6832. }
  6833. if (Result) {
  6834. // Determine which correction we picked.
  6835. Decl *Canonical = Result->getCanonicalDecl();
  6836. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6837. I != E; ++I)
  6838. if ((*I)->getCanonicalDecl() == Canonical)
  6839. Correction.setCorrectionDecl(*I);
  6840. // Let Sema know about the correction.
  6841. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6842. SemaRef.diagnoseTypo(
  6843. Correction,
  6844. SemaRef.PDiag(IsLocalFriend
  6845. ? diag::err_no_matching_local_friend_suggest
  6846. : diag::err_member_decl_does_not_match_suggest)
  6847. << Name << NewDC << IsDefinition);
  6848. return Result;
  6849. }
  6850. // Pretend the typo correction never occurred
  6851. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6852. ExtraArgs.D.getIdentifierLoc());
  6853. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6854. Previous.clear();
  6855. Previous.setLookupName(Name);
  6856. }
  6857. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6858. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6859. bool NewFDisConst = false;
  6860. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6861. NewFDisConst = NewMD->isConst();
  6862. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6863. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6864. NearMatch != NearMatchEnd; ++NearMatch) {
  6865. FunctionDecl *FD = NearMatch->first;
  6866. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6867. bool FDisConst = MD && MD->isConst();
  6868. bool IsMember = MD || !IsLocalFriend;
  6869. // FIXME: These notes are poorly worded for the local friend case.
  6870. if (unsigned Idx = NearMatch->second) {
  6871. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6872. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6873. if (Loc.isInvalid()) Loc = FD->getLocation();
  6874. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6875. : diag::note_local_decl_close_param_match)
  6876. << Idx << FDParam->getType()
  6877. << NewFD->getParamDecl(Idx - 1)->getType();
  6878. } else if (FDisConst != NewFDisConst) {
  6879. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6880. << NewFDisConst << FD->getSourceRange().getEnd();
  6881. } else
  6882. SemaRef.Diag(FD->getLocation(),
  6883. IsMember ? diag::note_member_def_close_match
  6884. : diag::note_local_decl_close_match);
  6885. }
  6886. return nullptr;
  6887. }
  6888. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6889. switch (D.getDeclSpec().getStorageClassSpec()) {
  6890. default: llvm_unreachable("Unknown storage class!");
  6891. case DeclSpec::SCS_auto:
  6892. case DeclSpec::SCS_register:
  6893. case DeclSpec::SCS_mutable:
  6894. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6895. diag::err_typecheck_sclass_func);
  6896. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6897. D.setInvalidType();
  6898. break;
  6899. case DeclSpec::SCS_unspecified: break;
  6900. case DeclSpec::SCS_extern:
  6901. if (D.getDeclSpec().isExternInLinkageSpec())
  6902. return SC_None;
  6903. return SC_Extern;
  6904. case DeclSpec::SCS_static: {
  6905. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6906. // C99 6.7.1p5:
  6907. // The declaration of an identifier for a function that has
  6908. // block scope shall have no explicit storage-class specifier
  6909. // other than extern
  6910. // See also (C++ [dcl.stc]p4).
  6911. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6912. diag::err_static_block_func);
  6913. break;
  6914. } else
  6915. return SC_Static;
  6916. }
  6917. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6918. }
  6919. // No explicit storage class has already been returned
  6920. return SC_None;
  6921. }
  6922. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6923. DeclContext *DC, QualType &R,
  6924. TypeSourceInfo *TInfo,
  6925. StorageClass SC,
  6926. bool &IsVirtualOkay) {
  6927. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6928. DeclarationName Name = NameInfo.getName();
  6929. FunctionDecl *NewFD = nullptr;
  6930. bool isInline = D.getDeclSpec().isInlineSpecified();
  6931. if (!SemaRef.getLangOpts().CPlusPlus) {
  6932. // Determine whether the function was written with a
  6933. // prototype. This true when:
  6934. // - there is a prototype in the declarator, or
  6935. // - the type R of the function is some kind of typedef or other non-
  6936. // attributed reference to a type name (which eventually refers to a
  6937. // function type).
  6938. bool HasPrototype =
  6939. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  6940. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  6941. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  6942. D.getLocStart(), NameInfo, R,
  6943. TInfo, SC, isInline,
  6944. HasPrototype, false);
  6945. if (D.isInvalidType())
  6946. NewFD->setInvalidDecl();
  6947. return NewFD;
  6948. }
  6949. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  6950. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  6951. // Check that the return type is not an abstract class type.
  6952. // For record types, this is done by the AbstractClassUsageDiagnoser once
  6953. // the class has been completely parsed.
  6954. if (!DC->isRecord() &&
  6955. SemaRef.RequireNonAbstractType(
  6956. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  6957. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  6958. D.setInvalidType();
  6959. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  6960. // This is a C++ constructor declaration.
  6961. assert(DC->isRecord() &&
  6962. "Constructors can only be declared in a member context");
  6963. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  6964. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  6965. D.getLocStart(), NameInfo,
  6966. R, TInfo, isExplicit, isInline,
  6967. /*isImplicitlyDeclared=*/false,
  6968. isConstexpr);
  6969. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6970. // This is a C++ destructor declaration.
  6971. if (DC->isRecord()) {
  6972. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  6973. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  6974. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  6975. SemaRef.Context, Record,
  6976. D.getLocStart(),
  6977. NameInfo, R, TInfo, isInline,
  6978. /*isImplicitlyDeclared=*/false);
  6979. // If the class is complete, then we now create the implicit exception
  6980. // specification. If the class is incomplete or dependent, we can't do
  6981. // it yet.
  6982. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  6983. Record->getDefinition() && !Record->isBeingDefined() &&
  6984. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  6985. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  6986. }
  6987. IsVirtualOkay = true;
  6988. return NewDD;
  6989. } else {
  6990. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  6991. D.setInvalidType();
  6992. // Create a FunctionDecl to satisfy the function definition parsing
  6993. // code path.
  6994. return FunctionDecl::Create(SemaRef.Context, DC,
  6995. D.getLocStart(),
  6996. D.getIdentifierLoc(), Name, R, TInfo,
  6997. SC, isInline,
  6998. /*hasPrototype=*/true, isConstexpr);
  6999. }
  7000. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7001. if (!DC->isRecord()) {
  7002. SemaRef.Diag(D.getIdentifierLoc(),
  7003. diag::err_conv_function_not_member);
  7004. return nullptr;
  7005. }
  7006. SemaRef.CheckConversionDeclarator(D, R, SC);
  7007. IsVirtualOkay = true;
  7008. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7009. D.getLocStart(), NameInfo,
  7010. R, TInfo, isInline, isExplicit,
  7011. isConstexpr, SourceLocation());
  7012. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7013. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7014. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
  7015. isExplicit, NameInfo, R, TInfo,
  7016. D.getLocEnd());
  7017. } else if (DC->isRecord()) {
  7018. // If the name of the function is the same as the name of the record,
  7019. // then this must be an invalid constructor that has a return type.
  7020. // (The parser checks for a return type and makes the declarator a
  7021. // constructor if it has no return type).
  7022. if (Name.getAsIdentifierInfo() &&
  7023. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7024. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7025. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7026. << SourceRange(D.getIdentifierLoc());
  7027. return nullptr;
  7028. }
  7029. // This is a C++ method declaration.
  7030. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  7031. cast<CXXRecordDecl>(DC),
  7032. D.getLocStart(), NameInfo, R,
  7033. TInfo, SC, isInline,
  7034. isConstexpr, SourceLocation());
  7035. IsVirtualOkay = !Ret->isStatic();
  7036. return Ret;
  7037. } else {
  7038. bool isFriend =
  7039. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7040. if (!isFriend && SemaRef.CurContext->isRecord())
  7041. return nullptr;
  7042. // Determine whether the function was written with a
  7043. // prototype. This true when:
  7044. // - we're in C++ (where every function has a prototype),
  7045. return FunctionDecl::Create(SemaRef.Context, DC,
  7046. D.getLocStart(),
  7047. NameInfo, R, TInfo, SC, isInline,
  7048. true/*HasPrototype*/, isConstexpr);
  7049. }
  7050. }
  7051. enum OpenCLParamType {
  7052. ValidKernelParam,
  7053. PtrPtrKernelParam,
  7054. PtrKernelParam,
  7055. InvalidAddrSpacePtrKernelParam,
  7056. InvalidKernelParam,
  7057. RecordKernelParam
  7058. };
  7059. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7060. if (PT->isPointerType()) {
  7061. QualType PointeeType = PT->getPointeeType();
  7062. if (PointeeType->isPointerType())
  7063. return PtrPtrKernelParam;
  7064. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7065. PointeeType.getAddressSpace() == 0)
  7066. return InvalidAddrSpacePtrKernelParam;
  7067. return PtrKernelParam;
  7068. }
  7069. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  7070. // be used as builtin types.
  7071. if (PT->isImageType())
  7072. return PtrKernelParam;
  7073. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7074. return InvalidKernelParam;
  7075. // OpenCL extension spec v1.2 s9.5:
  7076. // This extension adds support for half scalar and vector types as built-in
  7077. // types that can be used for arithmetic operations, conversions etc.
  7078. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7079. return InvalidKernelParam;
  7080. if (PT->isRecordType())
  7081. return RecordKernelParam;
  7082. return ValidKernelParam;
  7083. }
  7084. static void checkIsValidOpenCLKernelParameter(
  7085. Sema &S,
  7086. Declarator &D,
  7087. ParmVarDecl *Param,
  7088. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7089. QualType PT = Param->getType();
  7090. // Cache the valid types we encounter to avoid rechecking structs that are
  7091. // used again
  7092. if (ValidTypes.count(PT.getTypePtr()))
  7093. return;
  7094. switch (getOpenCLKernelParameterType(S, PT)) {
  7095. case PtrPtrKernelParam:
  7096. // OpenCL v1.2 s6.9.a:
  7097. // A kernel function argument cannot be declared as a
  7098. // pointer to a pointer type.
  7099. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7100. D.setInvalidType();
  7101. return;
  7102. case InvalidAddrSpacePtrKernelParam:
  7103. // OpenCL v1.0 s6.5:
  7104. // __kernel function arguments declared to be a pointer of a type can point
  7105. // to one of the following address spaces only : __global, __local or
  7106. // __constant.
  7107. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7108. D.setInvalidType();
  7109. return;
  7110. // OpenCL v1.2 s6.9.k:
  7111. // Arguments to kernel functions in a program cannot be declared with the
  7112. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7113. // uintptr_t or a struct and/or union that contain fields declared to be
  7114. // one of these built-in scalar types.
  7115. case InvalidKernelParam:
  7116. // OpenCL v1.2 s6.8 n:
  7117. // A kernel function argument cannot be declared
  7118. // of event_t type.
  7119. // Do not diagnose half type since it is diagnosed as invalid argument
  7120. // type for any function elsewhere.
  7121. if (!PT->isHalfType())
  7122. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7123. D.setInvalidType();
  7124. return;
  7125. case PtrKernelParam:
  7126. case ValidKernelParam:
  7127. ValidTypes.insert(PT.getTypePtr());
  7128. return;
  7129. case RecordKernelParam:
  7130. break;
  7131. }
  7132. // Track nested structs we will inspect
  7133. SmallVector<const Decl *, 4> VisitStack;
  7134. // Track where we are in the nested structs. Items will migrate from
  7135. // VisitStack to HistoryStack as we do the DFS for bad field.
  7136. SmallVector<const FieldDecl *, 4> HistoryStack;
  7137. HistoryStack.push_back(nullptr);
  7138. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  7139. VisitStack.push_back(PD);
  7140. assert(VisitStack.back() && "First decl null?");
  7141. do {
  7142. const Decl *Next = VisitStack.pop_back_val();
  7143. if (!Next) {
  7144. assert(!HistoryStack.empty());
  7145. // Found a marker, we have gone up a level
  7146. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7147. ValidTypes.insert(Hist->getType().getTypePtr());
  7148. continue;
  7149. }
  7150. // Adds everything except the original parameter declaration (which is not a
  7151. // field itself) to the history stack.
  7152. const RecordDecl *RD;
  7153. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7154. HistoryStack.push_back(Field);
  7155. RD = Field->getType()->castAs<RecordType>()->getDecl();
  7156. } else {
  7157. RD = cast<RecordDecl>(Next);
  7158. }
  7159. // Add a null marker so we know when we've gone back up a level
  7160. VisitStack.push_back(nullptr);
  7161. for (const auto *FD : RD->fields()) {
  7162. QualType QT = FD->getType();
  7163. if (ValidTypes.count(QT.getTypePtr()))
  7164. continue;
  7165. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7166. if (ParamType == ValidKernelParam)
  7167. continue;
  7168. if (ParamType == RecordKernelParam) {
  7169. VisitStack.push_back(FD);
  7170. continue;
  7171. }
  7172. // OpenCL v1.2 s6.9.p:
  7173. // Arguments to kernel functions that are declared to be a struct or union
  7174. // do not allow OpenCL objects to be passed as elements of the struct or
  7175. // union.
  7176. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7177. ParamType == InvalidAddrSpacePtrKernelParam) {
  7178. S.Diag(Param->getLocation(),
  7179. diag::err_record_with_pointers_kernel_param)
  7180. << PT->isUnionType()
  7181. << PT;
  7182. } else {
  7183. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7184. }
  7185. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  7186. << PD->getDeclName();
  7187. // We have an error, now let's go back up through history and show where
  7188. // the offending field came from
  7189. for (ArrayRef<const FieldDecl *>::const_iterator
  7190. I = HistoryStack.begin() + 1,
  7191. E = HistoryStack.end();
  7192. I != E; ++I) {
  7193. const FieldDecl *OuterField = *I;
  7194. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7195. << OuterField->getType();
  7196. }
  7197. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7198. << QT->isPointerType()
  7199. << QT;
  7200. D.setInvalidType();
  7201. return;
  7202. }
  7203. } while (!VisitStack.empty());
  7204. }
  7205. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7206. /// elaborated type specifier in the specified context, and lookup finds
  7207. /// nothing.
  7208. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7209. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7210. DC = DC->getParent();
  7211. return DC;
  7212. }
  7213. /// Find the Scope in which a tag is implicitly declared if we see an
  7214. /// elaborated type specifier in the specified context, and lookup finds
  7215. /// nothing.
  7216. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7217. while (S->isClassScope() ||
  7218. (LangOpts.CPlusPlus &&
  7219. S->isFunctionPrototypeScope()) ||
  7220. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7221. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7222. S = S->getParent();
  7223. return S;
  7224. }
  7225. NamedDecl*
  7226. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7227. TypeSourceInfo *TInfo, LookupResult &Previous,
  7228. MultiTemplateParamsArg TemplateParamLists,
  7229. bool &AddToScope) {
  7230. QualType R = TInfo->getType();
  7231. assert(R.getTypePtr()->isFunctionType());
  7232. // TODO: consider using NameInfo for diagnostic.
  7233. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7234. DeclarationName Name = NameInfo.getName();
  7235. StorageClass SC = getFunctionStorageClass(*this, D);
  7236. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7237. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7238. diag::err_invalid_thread)
  7239. << DeclSpec::getSpecifierName(TSCS);
  7240. if (D.isFirstDeclarationOfMember())
  7241. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7242. D.getIdentifierLoc());
  7243. bool isFriend = false;
  7244. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7245. bool isMemberSpecialization = false;
  7246. bool isFunctionTemplateSpecialization = false;
  7247. bool isDependentClassScopeExplicitSpecialization = false;
  7248. bool HasExplicitTemplateArgs = false;
  7249. TemplateArgumentListInfo TemplateArgs;
  7250. bool isVirtualOkay = false;
  7251. DeclContext *OriginalDC = DC;
  7252. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7253. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7254. isVirtualOkay);
  7255. if (!NewFD) return nullptr;
  7256. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7257. NewFD->setTopLevelDeclInObjCContainer();
  7258. // Set the lexical context. If this is a function-scope declaration, or has a
  7259. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7260. // context will be different from the semantic context.
  7261. NewFD->setLexicalDeclContext(CurContext);
  7262. if (IsLocalExternDecl)
  7263. NewFD->setLocalExternDecl();
  7264. if (getLangOpts().CPlusPlus) {
  7265. bool isInline = D.getDeclSpec().isInlineSpecified();
  7266. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7267. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7268. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7269. bool isConcept = D.getDeclSpec().isConceptSpecified();
  7270. isFriend = D.getDeclSpec().isFriendSpecified();
  7271. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7272. // C++ [class.friend]p5
  7273. // A function can be defined in a friend declaration of a
  7274. // class . . . . Such a function is implicitly inline.
  7275. NewFD->setImplicitlyInline();
  7276. }
  7277. // If this is a method defined in an __interface, and is not a constructor
  7278. // or an overloaded operator, then set the pure flag (isVirtual will already
  7279. // return true).
  7280. if (const CXXRecordDecl *Parent =
  7281. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7282. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7283. NewFD->setPure(true);
  7284. // C++ [class.union]p2
  7285. // A union can have member functions, but not virtual functions.
  7286. if (isVirtual && Parent->isUnion())
  7287. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7288. }
  7289. SetNestedNameSpecifier(NewFD, D);
  7290. isMemberSpecialization = false;
  7291. isFunctionTemplateSpecialization = false;
  7292. if (D.isInvalidType())
  7293. NewFD->setInvalidDecl();
  7294. // Match up the template parameter lists with the scope specifier, then
  7295. // determine whether we have a template or a template specialization.
  7296. bool Invalid = false;
  7297. if (TemplateParameterList *TemplateParams =
  7298. MatchTemplateParametersToScopeSpecifier(
  7299. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  7300. D.getCXXScopeSpec(),
  7301. D.getName().getKind() == UnqualifiedId::IK_TemplateId
  7302. ? D.getName().TemplateId
  7303. : nullptr,
  7304. TemplateParamLists, isFriend, isMemberSpecialization,
  7305. Invalid)) {
  7306. if (TemplateParams->size() > 0) {
  7307. // This is a function template
  7308. // Check that we can declare a template here.
  7309. if (CheckTemplateDeclScope(S, TemplateParams))
  7310. NewFD->setInvalidDecl();
  7311. // A destructor cannot be a template.
  7312. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7313. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7314. NewFD->setInvalidDecl();
  7315. }
  7316. // If we're adding a template to a dependent context, we may need to
  7317. // rebuilding some of the types used within the template parameter list,
  7318. // now that we know what the current instantiation is.
  7319. if (DC->isDependentContext()) {
  7320. ContextRAII SavedContext(*this, DC);
  7321. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7322. Invalid = true;
  7323. }
  7324. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7325. NewFD->getLocation(),
  7326. Name, TemplateParams,
  7327. NewFD);
  7328. FunctionTemplate->setLexicalDeclContext(CurContext);
  7329. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7330. // For source fidelity, store the other template param lists.
  7331. if (TemplateParamLists.size() > 1) {
  7332. NewFD->setTemplateParameterListsInfo(Context,
  7333. TemplateParamLists.drop_back(1));
  7334. }
  7335. } else {
  7336. // This is a function template specialization.
  7337. isFunctionTemplateSpecialization = true;
  7338. // For source fidelity, store all the template param lists.
  7339. if (TemplateParamLists.size() > 0)
  7340. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7341. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7342. if (isFriend) {
  7343. // We want to remove the "template<>", found here.
  7344. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7345. // If we remove the template<> and the name is not a
  7346. // template-id, we're actually silently creating a problem:
  7347. // the friend declaration will refer to an untemplated decl,
  7348. // and clearly the user wants a template specialization. So
  7349. // we need to insert '<>' after the name.
  7350. SourceLocation InsertLoc;
  7351. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  7352. InsertLoc = D.getName().getSourceRange().getEnd();
  7353. InsertLoc = getLocForEndOfToken(InsertLoc);
  7354. }
  7355. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7356. << Name << RemoveRange
  7357. << FixItHint::CreateRemoval(RemoveRange)
  7358. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7359. }
  7360. }
  7361. }
  7362. else {
  7363. // All template param lists were matched against the scope specifier:
  7364. // this is NOT (an explicit specialization of) a template.
  7365. if (TemplateParamLists.size() > 0)
  7366. // For source fidelity, store all the template param lists.
  7367. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7368. }
  7369. if (Invalid) {
  7370. NewFD->setInvalidDecl();
  7371. if (FunctionTemplate)
  7372. FunctionTemplate->setInvalidDecl();
  7373. }
  7374. // C++ [dcl.fct.spec]p5:
  7375. // The virtual specifier shall only be used in declarations of
  7376. // nonstatic class member functions that appear within a
  7377. // member-specification of a class declaration; see 10.3.
  7378. //
  7379. if (isVirtual && !NewFD->isInvalidDecl()) {
  7380. if (!isVirtualOkay) {
  7381. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7382. diag::err_virtual_non_function);
  7383. } else if (!CurContext->isRecord()) {
  7384. // 'virtual' was specified outside of the class.
  7385. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7386. diag::err_virtual_out_of_class)
  7387. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7388. } else if (NewFD->getDescribedFunctionTemplate()) {
  7389. // C++ [temp.mem]p3:
  7390. // A member function template shall not be virtual.
  7391. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7392. diag::err_virtual_member_function_template)
  7393. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7394. } else {
  7395. // Okay: Add virtual to the method.
  7396. NewFD->setVirtualAsWritten(true);
  7397. }
  7398. if (getLangOpts().CPlusPlus14 &&
  7399. NewFD->getReturnType()->isUndeducedType())
  7400. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7401. }
  7402. if (getLangOpts().CPlusPlus14 &&
  7403. (NewFD->isDependentContext() ||
  7404. (isFriend && CurContext->isDependentContext())) &&
  7405. NewFD->getReturnType()->isUndeducedType()) {
  7406. // If the function template is referenced directly (for instance, as a
  7407. // member of the current instantiation), pretend it has a dependent type.
  7408. // This is not really justified by the standard, but is the only sane
  7409. // thing to do.
  7410. // FIXME: For a friend function, we have not marked the function as being
  7411. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7412. const FunctionProtoType *FPT =
  7413. NewFD->getType()->castAs<FunctionProtoType>();
  7414. QualType Result =
  7415. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7416. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7417. FPT->getExtProtoInfo()));
  7418. }
  7419. // C++ [dcl.fct.spec]p3:
  7420. // The inline specifier shall not appear on a block scope function
  7421. // declaration.
  7422. if (isInline && !NewFD->isInvalidDecl()) {
  7423. if (CurContext->isFunctionOrMethod()) {
  7424. // 'inline' is not allowed on block scope function declaration.
  7425. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7426. diag::err_inline_declaration_block_scope) << Name
  7427. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7428. }
  7429. }
  7430. // C++ [dcl.fct.spec]p6:
  7431. // The explicit specifier shall be used only in the declaration of a
  7432. // constructor or conversion function within its class definition;
  7433. // see 12.3.1 and 12.3.2.
  7434. if (isExplicit && !NewFD->isInvalidDecl() &&
  7435. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7436. if (!CurContext->isRecord()) {
  7437. // 'explicit' was specified outside of the class.
  7438. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7439. diag::err_explicit_out_of_class)
  7440. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7441. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7442. !isa<CXXConversionDecl>(NewFD)) {
  7443. // 'explicit' was specified on a function that wasn't a constructor
  7444. // or conversion function.
  7445. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7446. diag::err_explicit_non_ctor_or_conv_function)
  7447. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7448. }
  7449. }
  7450. if (isConstexpr) {
  7451. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7452. // are implicitly inline.
  7453. NewFD->setImplicitlyInline();
  7454. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7455. // be either constructors or to return a literal type. Therefore,
  7456. // destructors cannot be declared constexpr.
  7457. if (isa<CXXDestructorDecl>(NewFD))
  7458. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7459. }
  7460. if (isConcept) {
  7461. // This is a function concept.
  7462. if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
  7463. FTD->setConcept();
  7464. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7465. // applied only to the definition of a function template [...]
  7466. if (!D.isFunctionDefinition()) {
  7467. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7468. diag::err_function_concept_not_defined);
  7469. NewFD->setInvalidDecl();
  7470. }
  7471. // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
  7472. // have no exception-specification and is treated as if it were specified
  7473. // with noexcept(true) (15.4). [...]
  7474. if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
  7475. if (FPT->hasExceptionSpec()) {
  7476. SourceRange Range;
  7477. if (D.isFunctionDeclarator())
  7478. Range = D.getFunctionTypeInfo().getExceptionSpecRange();
  7479. Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
  7480. << FixItHint::CreateRemoval(Range);
  7481. NewFD->setInvalidDecl();
  7482. } else {
  7483. Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
  7484. }
  7485. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7486. // following restrictions:
  7487. // - The declared return type shall have the type bool.
  7488. if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
  7489. Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
  7490. NewFD->setInvalidDecl();
  7491. }
  7492. // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
  7493. // following restrictions:
  7494. // - The declaration's parameter list shall be equivalent to an empty
  7495. // parameter list.
  7496. if (FPT->getNumParams() > 0 || FPT->isVariadic())
  7497. Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
  7498. }
  7499. // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
  7500. // implicity defined to be a constexpr declaration (implicitly inline)
  7501. NewFD->setImplicitlyInline();
  7502. // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
  7503. // be declared with the thread_local, inline, friend, or constexpr
  7504. // specifiers, [...]
  7505. if (isInline) {
  7506. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7507. diag::err_concept_decl_invalid_specifiers)
  7508. << 1 << 1;
  7509. NewFD->setInvalidDecl(true);
  7510. }
  7511. if (isFriend) {
  7512. Diag(D.getDeclSpec().getFriendSpecLoc(),
  7513. diag::err_concept_decl_invalid_specifiers)
  7514. << 1 << 2;
  7515. NewFD->setInvalidDecl(true);
  7516. }
  7517. if (isConstexpr) {
  7518. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7519. diag::err_concept_decl_invalid_specifiers)
  7520. << 1 << 3;
  7521. NewFD->setInvalidDecl(true);
  7522. }
  7523. // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
  7524. // applied only to the definition of a function template or variable
  7525. // template, declared in namespace scope.
  7526. if (isFunctionTemplateSpecialization) {
  7527. Diag(D.getDeclSpec().getConceptSpecLoc(),
  7528. diag::err_concept_specified_specialization) << 1;
  7529. NewFD->setInvalidDecl(true);
  7530. return NewFD;
  7531. }
  7532. }
  7533. // If __module_private__ was specified, mark the function accordingly.
  7534. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7535. if (isFunctionTemplateSpecialization) {
  7536. SourceLocation ModulePrivateLoc
  7537. = D.getDeclSpec().getModulePrivateSpecLoc();
  7538. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7539. << 0
  7540. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7541. } else {
  7542. NewFD->setModulePrivate();
  7543. if (FunctionTemplate)
  7544. FunctionTemplate->setModulePrivate();
  7545. }
  7546. }
  7547. if (isFriend) {
  7548. if (FunctionTemplate) {
  7549. FunctionTemplate->setObjectOfFriendDecl();
  7550. FunctionTemplate->setAccess(AS_public);
  7551. }
  7552. NewFD->setObjectOfFriendDecl();
  7553. NewFD->setAccess(AS_public);
  7554. }
  7555. // If a function is defined as defaulted or deleted, mark it as such now.
  7556. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7557. // definition kind to FDK_Definition.
  7558. switch (D.getFunctionDefinitionKind()) {
  7559. case FDK_Declaration:
  7560. case FDK_Definition:
  7561. break;
  7562. case FDK_Defaulted:
  7563. NewFD->setDefaulted();
  7564. break;
  7565. case FDK_Deleted:
  7566. NewFD->setDeletedAsWritten();
  7567. break;
  7568. }
  7569. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7570. D.isFunctionDefinition()) {
  7571. // C++ [class.mfct]p2:
  7572. // A member function may be defined (8.4) in its class definition, in
  7573. // which case it is an inline member function (7.1.2)
  7574. NewFD->setImplicitlyInline();
  7575. }
  7576. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7577. !CurContext->isRecord()) {
  7578. // C++ [class.static]p1:
  7579. // A data or function member of a class may be declared static
  7580. // in a class definition, in which case it is a static member of
  7581. // the class.
  7582. // Complain about the 'static' specifier if it's on an out-of-line
  7583. // member function definition.
  7584. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7585. diag::err_static_out_of_line)
  7586. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7587. }
  7588. // C++11 [except.spec]p15:
  7589. // A deallocation function with no exception-specification is treated
  7590. // as if it were specified with noexcept(true).
  7591. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7592. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7593. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7594. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7595. NewFD->setType(Context.getFunctionType(
  7596. FPT->getReturnType(), FPT->getParamTypes(),
  7597. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7598. }
  7599. // Filter out previous declarations that don't match the scope.
  7600. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7601. D.getCXXScopeSpec().isNotEmpty() ||
  7602. isMemberSpecialization ||
  7603. isFunctionTemplateSpecialization);
  7604. // Handle GNU asm-label extension (encoded as an attribute).
  7605. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7606. // The parser guarantees this is a string.
  7607. StringLiteral *SE = cast<StringLiteral>(E);
  7608. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7609. SE->getString(), 0));
  7610. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7611. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7612. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7613. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7614. if (isDeclExternC(NewFD)) {
  7615. NewFD->addAttr(I->second);
  7616. ExtnameUndeclaredIdentifiers.erase(I);
  7617. } else
  7618. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7619. << /*Variable*/0 << NewFD;
  7620. }
  7621. }
  7622. // Copy the parameter declarations from the declarator D to the function
  7623. // declaration NewFD, if they are available. First scavenge them into Params.
  7624. SmallVector<ParmVarDecl*, 16> Params;
  7625. unsigned FTIIdx;
  7626. if (D.isFunctionDeclarator(FTIIdx)) {
  7627. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7628. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7629. // function that takes no arguments, not a function that takes a
  7630. // single void argument.
  7631. // We let through "const void" here because Sema::GetTypeForDeclarator
  7632. // already checks for that case.
  7633. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7634. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7635. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7636. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7637. Param->setDeclContext(NewFD);
  7638. Params.push_back(Param);
  7639. if (Param->isInvalidDecl())
  7640. NewFD->setInvalidDecl();
  7641. }
  7642. }
  7643. if (!getLangOpts().CPlusPlus) {
  7644. // In C, find all the tag declarations from the prototype and move them
  7645. // into the function DeclContext. Remove them from the surrounding tag
  7646. // injection context of the function, which is typically but not always
  7647. // the TU.
  7648. DeclContext *PrototypeTagContext =
  7649. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7650. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7651. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7652. // We don't want to reparent enumerators. Look at their parent enum
  7653. // instead.
  7654. if (!TD) {
  7655. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7656. TD = cast<EnumDecl>(ECD->getDeclContext());
  7657. }
  7658. if (!TD)
  7659. continue;
  7660. DeclContext *TagDC = TD->getLexicalDeclContext();
  7661. if (!TagDC->containsDecl(TD))
  7662. continue;
  7663. TagDC->removeDecl(TD);
  7664. TD->setDeclContext(NewFD);
  7665. NewFD->addDecl(TD);
  7666. // Preserve the lexical DeclContext if it is not the surrounding tag
  7667. // injection context of the FD. In this example, the semantic context of
  7668. // E will be f and the lexical context will be S, while both the
  7669. // semantic and lexical contexts of S will be f:
  7670. // void f(struct S { enum E { a } f; } s);
  7671. if (TagDC != PrototypeTagContext)
  7672. TD->setLexicalDeclContext(TagDC);
  7673. }
  7674. }
  7675. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7676. // When we're declaring a function with a typedef, typeof, etc as in the
  7677. // following example, we'll need to synthesize (unnamed)
  7678. // parameters for use in the declaration.
  7679. //
  7680. // @code
  7681. // typedef void fn(int);
  7682. // fn f;
  7683. // @endcode
  7684. // Synthesize a parameter for each argument type.
  7685. for (const auto &AI : FT->param_types()) {
  7686. ParmVarDecl *Param =
  7687. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7688. Param->setScopeInfo(0, Params.size());
  7689. Params.push_back(Param);
  7690. }
  7691. } else {
  7692. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7693. "Should not need args for typedef of non-prototype fn");
  7694. }
  7695. // Finally, we know we have the right number of parameters, install them.
  7696. NewFD->setParams(Params);
  7697. if (D.getDeclSpec().isNoreturnSpecified())
  7698. NewFD->addAttr(
  7699. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7700. Context, 0));
  7701. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7702. // because all functions have linkage.
  7703. if (!NewFD->isInvalidDecl() &&
  7704. NewFD->getReturnType()->isVariablyModifiedType()) {
  7705. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7706. NewFD->setInvalidDecl();
  7707. }
  7708. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7709. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7710. !NewFD->hasAttr<SectionAttr>()) {
  7711. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7712. PragmaClangTextSection.SectionName,
  7713. PragmaClangTextSection.PragmaLocation));
  7714. }
  7715. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7716. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7717. !NewFD->hasAttr<SectionAttr>()) {
  7718. NewFD->addAttr(
  7719. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7720. CodeSegStack.CurrentValue->getString(),
  7721. CodeSegStack.CurrentPragmaLocation));
  7722. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7723. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7724. ASTContext::PSF_Read,
  7725. NewFD))
  7726. NewFD->dropAttr<SectionAttr>();
  7727. }
  7728. // Handle attributes.
  7729. ProcessDeclAttributes(S, NewFD, D);
  7730. if (getLangOpts().OpenCL) {
  7731. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7732. // type declaration will generate a compilation error.
  7733. unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
  7734. if (AddressSpace == LangAS::opencl_local ||
  7735. AddressSpace == LangAS::opencl_global ||
  7736. AddressSpace == LangAS::opencl_constant) {
  7737. Diag(NewFD->getLocation(),
  7738. diag::err_opencl_return_value_with_address_space);
  7739. NewFD->setInvalidDecl();
  7740. }
  7741. }
  7742. if (!getLangOpts().CPlusPlus) {
  7743. // Perform semantic checking on the function declaration.
  7744. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7745. CheckMain(NewFD, D.getDeclSpec());
  7746. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7747. CheckMSVCRTEntryPoint(NewFD);
  7748. if (!NewFD->isInvalidDecl())
  7749. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7750. isMemberSpecialization));
  7751. else if (!Previous.empty())
  7752. // Recover gracefully from an invalid redeclaration.
  7753. D.setRedeclaration(true);
  7754. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7755. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7756. "previous declaration set still overloaded");
  7757. // Diagnose no-prototype function declarations with calling conventions that
  7758. // don't support variadic calls. Only do this in C and do it after merging
  7759. // possibly prototyped redeclarations.
  7760. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7761. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7762. CallingConv CC = FT->getExtInfo().getCC();
  7763. if (!supportsVariadicCall(CC)) {
  7764. // Windows system headers sometimes accidentally use stdcall without
  7765. // (void) parameters, so we relax this to a warning.
  7766. int DiagID =
  7767. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7768. Diag(NewFD->getLocation(), DiagID)
  7769. << FunctionType::getNameForCallConv(CC);
  7770. }
  7771. }
  7772. } else {
  7773. // C++11 [replacement.functions]p3:
  7774. // The program's definitions shall not be specified as inline.
  7775. //
  7776. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7777. //
  7778. // Suppress the diagnostic if the function is __attribute__((used)), since
  7779. // that forces an external definition to be emitted.
  7780. if (D.getDeclSpec().isInlineSpecified() &&
  7781. NewFD->isReplaceableGlobalAllocationFunction() &&
  7782. !NewFD->hasAttr<UsedAttr>())
  7783. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7784. diag::ext_operator_new_delete_declared_inline)
  7785. << NewFD->getDeclName();
  7786. // If the declarator is a template-id, translate the parser's template
  7787. // argument list into our AST format.
  7788. if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
  7789. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7790. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7791. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7792. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7793. TemplateId->NumArgs);
  7794. translateTemplateArguments(TemplateArgsPtr,
  7795. TemplateArgs);
  7796. HasExplicitTemplateArgs = true;
  7797. if (NewFD->isInvalidDecl()) {
  7798. HasExplicitTemplateArgs = false;
  7799. } else if (FunctionTemplate) {
  7800. // Function template with explicit template arguments.
  7801. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7802. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7803. HasExplicitTemplateArgs = false;
  7804. } else {
  7805. assert((isFunctionTemplateSpecialization ||
  7806. D.getDeclSpec().isFriendSpecified()) &&
  7807. "should have a 'template<>' for this decl");
  7808. // "friend void foo<>(int);" is an implicit specialization decl.
  7809. isFunctionTemplateSpecialization = true;
  7810. }
  7811. } else if (isFriend && isFunctionTemplateSpecialization) {
  7812. // This combination is only possible in a recovery case; the user
  7813. // wrote something like:
  7814. // template <> friend void foo(int);
  7815. // which we're recovering from as if the user had written:
  7816. // friend void foo<>(int);
  7817. // Go ahead and fake up a template id.
  7818. HasExplicitTemplateArgs = true;
  7819. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7820. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7821. }
  7822. // We do not add HD attributes to specializations here because
  7823. // they may have different constexpr-ness compared to their
  7824. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7825. // may end up with different effective targets. Instead, a
  7826. // specialization inherits its target attributes from its template
  7827. // in the CheckFunctionTemplateSpecialization() call below.
  7828. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7829. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7830. // If it's a friend (and only if it's a friend), it's possible
  7831. // that either the specialized function type or the specialized
  7832. // template is dependent, and therefore matching will fail. In
  7833. // this case, don't check the specialization yet.
  7834. bool InstantiationDependent = false;
  7835. if (isFunctionTemplateSpecialization && isFriend &&
  7836. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7837. TemplateSpecializationType::anyDependentTemplateArguments(
  7838. TemplateArgs,
  7839. InstantiationDependent))) {
  7840. assert(HasExplicitTemplateArgs &&
  7841. "friend function specialization without template args");
  7842. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7843. Previous))
  7844. NewFD->setInvalidDecl();
  7845. } else if (isFunctionTemplateSpecialization) {
  7846. if (CurContext->isDependentContext() && CurContext->isRecord()
  7847. && !isFriend) {
  7848. isDependentClassScopeExplicitSpecialization = true;
  7849. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  7850. diag::ext_function_specialization_in_class :
  7851. diag::err_function_specialization_in_class)
  7852. << NewFD->getDeclName();
  7853. } else if (CheckFunctionTemplateSpecialization(NewFD,
  7854. (HasExplicitTemplateArgs ? &TemplateArgs
  7855. : nullptr),
  7856. Previous))
  7857. NewFD->setInvalidDecl();
  7858. // C++ [dcl.stc]p1:
  7859. // A storage-class-specifier shall not be specified in an explicit
  7860. // specialization (14.7.3)
  7861. FunctionTemplateSpecializationInfo *Info =
  7862. NewFD->getTemplateSpecializationInfo();
  7863. if (Info && SC != SC_None) {
  7864. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7865. Diag(NewFD->getLocation(),
  7866. diag::err_explicit_specialization_inconsistent_storage_class)
  7867. << SC
  7868. << FixItHint::CreateRemoval(
  7869. D.getDeclSpec().getStorageClassSpecLoc());
  7870. else
  7871. Diag(NewFD->getLocation(),
  7872. diag::ext_explicit_specialization_storage_class)
  7873. << FixItHint::CreateRemoval(
  7874. D.getDeclSpec().getStorageClassSpecLoc());
  7875. }
  7876. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7877. if (CheckMemberSpecialization(NewFD, Previous))
  7878. NewFD->setInvalidDecl();
  7879. }
  7880. // Perform semantic checking on the function declaration.
  7881. if (!isDependentClassScopeExplicitSpecialization) {
  7882. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7883. CheckMain(NewFD, D.getDeclSpec());
  7884. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7885. CheckMSVCRTEntryPoint(NewFD);
  7886. if (!NewFD->isInvalidDecl())
  7887. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7888. isMemberSpecialization));
  7889. else if (!Previous.empty())
  7890. // Recover gracefully from an invalid redeclaration.
  7891. D.setRedeclaration(true);
  7892. }
  7893. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7894. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7895. "previous declaration set still overloaded");
  7896. NamedDecl *PrincipalDecl = (FunctionTemplate
  7897. ? cast<NamedDecl>(FunctionTemplate)
  7898. : NewFD);
  7899. if (isFriend && NewFD->getPreviousDecl()) {
  7900. AccessSpecifier Access = AS_public;
  7901. if (!NewFD->isInvalidDecl())
  7902. Access = NewFD->getPreviousDecl()->getAccess();
  7903. NewFD->setAccess(Access);
  7904. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7905. }
  7906. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7907. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7908. PrincipalDecl->setNonMemberOperator();
  7909. // If we have a function template, check the template parameter
  7910. // list. This will check and merge default template arguments.
  7911. if (FunctionTemplate) {
  7912. FunctionTemplateDecl *PrevTemplate =
  7913. FunctionTemplate->getPreviousDecl();
  7914. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7915. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7916. : nullptr,
  7917. D.getDeclSpec().isFriendSpecified()
  7918. ? (D.isFunctionDefinition()
  7919. ? TPC_FriendFunctionTemplateDefinition
  7920. : TPC_FriendFunctionTemplate)
  7921. : (D.getCXXScopeSpec().isSet() &&
  7922. DC && DC->isRecord() &&
  7923. DC->isDependentContext())
  7924. ? TPC_ClassTemplateMember
  7925. : TPC_FunctionTemplate);
  7926. }
  7927. if (NewFD->isInvalidDecl()) {
  7928. // Ignore all the rest of this.
  7929. } else if (!D.isRedeclaration()) {
  7930. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  7931. AddToScope };
  7932. // Fake up an access specifier if it's supposed to be a class member.
  7933. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7934. NewFD->setAccess(AS_public);
  7935. // Qualified decls generally require a previous declaration.
  7936. if (D.getCXXScopeSpec().isSet()) {
  7937. // ...with the major exception of templated-scope or
  7938. // dependent-scope friend declarations.
  7939. // TODO: we currently also suppress this check in dependent
  7940. // contexts because (1) the parameter depth will be off when
  7941. // matching friend templates and (2) we might actually be
  7942. // selecting a friend based on a dependent factor. But there
  7943. // are situations where these conditions don't apply and we
  7944. // can actually do this check immediately.
  7945. if (isFriend &&
  7946. (TemplateParamLists.size() ||
  7947. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7948. CurContext->isDependentContext())) {
  7949. // ignore these
  7950. } else {
  7951. // The user tried to provide an out-of-line definition for a
  7952. // function that is a member of a class or namespace, but there
  7953. // was no such member function declared (C++ [class.mfct]p2,
  7954. // C++ [namespace.memdef]p2). For example:
  7955. //
  7956. // class X {
  7957. // void f() const;
  7958. // };
  7959. //
  7960. // void X::f() { } // ill-formed
  7961. //
  7962. // Complain about this problem, and attempt to suggest close
  7963. // matches (e.g., those that differ only in cv-qualifiers and
  7964. // whether the parameter types are references).
  7965. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7966. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7967. AddToScope = ExtraArgs.AddToScope;
  7968. return Result;
  7969. }
  7970. }
  7971. // Unqualified local friend declarations are required to resolve
  7972. // to something.
  7973. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7974. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7975. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7976. AddToScope = ExtraArgs.AddToScope;
  7977. return Result;
  7978. }
  7979. }
  7980. } else if (!D.isFunctionDefinition() &&
  7981. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7982. !isFriend && !isFunctionTemplateSpecialization &&
  7983. !isMemberSpecialization) {
  7984. // An out-of-line member function declaration must also be a
  7985. // definition (C++ [class.mfct]p2).
  7986. // Note that this is not the case for explicit specializations of
  7987. // function templates or member functions of class templates, per
  7988. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7989. // extension for compatibility with old SWIG code which likes to
  7990. // generate them.
  7991. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7992. << D.getCXXScopeSpec().getRange();
  7993. }
  7994. }
  7995. ProcessPragmaWeak(S, NewFD);
  7996. checkAttributesAfterMerging(*this, *NewFD);
  7997. AddKnownFunctionAttributes(NewFD);
  7998. if (NewFD->hasAttr<OverloadableAttr>() &&
  7999. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8000. Diag(NewFD->getLocation(),
  8001. diag::err_attribute_overloadable_no_prototype)
  8002. << NewFD;
  8003. // Turn this into a variadic function with no parameters.
  8004. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8005. FunctionProtoType::ExtProtoInfo EPI(
  8006. Context.getDefaultCallingConvention(true, false));
  8007. EPI.Variadic = true;
  8008. EPI.ExtInfo = FT->getExtInfo();
  8009. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8010. NewFD->setType(R);
  8011. }
  8012. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8013. // member, set the visibility of this function.
  8014. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8015. AddPushedVisibilityAttribute(NewFD);
  8016. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8017. // marking the function.
  8018. AddCFAuditedAttribute(NewFD);
  8019. // If this is a function definition, check if we have to apply optnone due to
  8020. // a pragma.
  8021. if(D.isFunctionDefinition())
  8022. AddRangeBasedOptnone(NewFD);
  8023. // If this is the first declaration of an extern C variable, update
  8024. // the map of such variables.
  8025. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8026. isIncompleteDeclExternC(*this, NewFD))
  8027. RegisterLocallyScopedExternCDecl(NewFD, S);
  8028. // Set this FunctionDecl's range up to the right paren.
  8029. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8030. if (D.isRedeclaration() && !Previous.empty()) {
  8031. checkDLLAttributeRedeclaration(
  8032. *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
  8033. isMemberSpecialization || isFunctionTemplateSpecialization,
  8034. D.isFunctionDefinition());
  8035. }
  8036. if (getLangOpts().CUDA) {
  8037. IdentifierInfo *II = NewFD->getIdentifier();
  8038. if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
  8039. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8040. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8041. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  8042. Context.setcudaConfigureCallDecl(NewFD);
  8043. }
  8044. // Variadic functions, other than a *declaration* of printf, are not allowed
  8045. // in device-side CUDA code, unless someone passed
  8046. // -fcuda-allow-variadic-functions.
  8047. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8048. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8049. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8050. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8051. !D.isFunctionDefinition())) {
  8052. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8053. }
  8054. }
  8055. MarkUnusedFileScopedDecl(NewFD);
  8056. if (getLangOpts().CPlusPlus) {
  8057. if (FunctionTemplate) {
  8058. if (NewFD->isInvalidDecl())
  8059. FunctionTemplate->setInvalidDecl();
  8060. return FunctionTemplate;
  8061. }
  8062. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8063. CompleteMemberSpecialization(NewFD, Previous);
  8064. }
  8065. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  8066. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8067. if ((getLangOpts().OpenCLVersion >= 120)
  8068. && (SC == SC_Static)) {
  8069. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8070. D.setInvalidType();
  8071. }
  8072. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8073. if (!NewFD->getReturnType()->isVoidType()) {
  8074. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8075. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8076. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8077. : FixItHint());
  8078. D.setInvalidType();
  8079. }
  8080. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8081. for (auto Param : NewFD->parameters())
  8082. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8083. }
  8084. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8085. QualType PT = Param->getType();
  8086. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8087. // types.
  8088. if (getLangOpts().OpenCLVersion >= 200) {
  8089. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8090. QualType ElemTy = PipeTy->getElementType();
  8091. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8092. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8093. D.setInvalidType();
  8094. }
  8095. }
  8096. }
  8097. }
  8098. // Here we have an function template explicit specialization at class scope.
  8099. // The actually specialization will be postponed to template instatiation
  8100. // time via the ClassScopeFunctionSpecializationDecl node.
  8101. if (isDependentClassScopeExplicitSpecialization) {
  8102. ClassScopeFunctionSpecializationDecl *NewSpec =
  8103. ClassScopeFunctionSpecializationDecl::Create(
  8104. Context, CurContext, SourceLocation(),
  8105. cast<CXXMethodDecl>(NewFD),
  8106. HasExplicitTemplateArgs, TemplateArgs);
  8107. CurContext->addDecl(NewSpec);
  8108. AddToScope = false;
  8109. }
  8110. return NewFD;
  8111. }
  8112. /// \brief Checks if the new declaration declared in dependent context must be
  8113. /// put in the same redeclaration chain as the specified declaration.
  8114. ///
  8115. /// \param D Declaration that is checked.
  8116. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8117. /// same declaration name.
  8118. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8119. /// belongs to.
  8120. ///
  8121. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8122. // Any declarations should be put into redeclaration chains except for
  8123. // friend declaration in a dependent context that names a function in
  8124. // namespace scope.
  8125. //
  8126. // This allows to compile code like:
  8127. //
  8128. // void func();
  8129. // template<typename T> class C1 { friend void func() { } };
  8130. // template<typename T> class C2 { friend void func() { } };
  8131. //
  8132. // This code snippet is a valid code unless both templates are instantiated.
  8133. return !(D->getLexicalDeclContext()->isDependentContext() &&
  8134. D->getDeclContext()->isFileContext() &&
  8135. D->getFriendObjectKind() != Decl::FOK_None);
  8136. }
  8137. /// \brief Perform semantic checking of a new function declaration.
  8138. ///
  8139. /// Performs semantic analysis of the new function declaration
  8140. /// NewFD. This routine performs all semantic checking that does not
  8141. /// require the actual declarator involved in the declaration, and is
  8142. /// used both for the declaration of functions as they are parsed
  8143. /// (called via ActOnDeclarator) and for the declaration of functions
  8144. /// that have been instantiated via C++ template instantiation (called
  8145. /// via InstantiateDecl).
  8146. ///
  8147. /// \param IsMemberSpecialization whether this new function declaration is
  8148. /// a member specialization (that replaces any definition provided by the
  8149. /// previous declaration).
  8150. ///
  8151. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8152. ///
  8153. /// \returns true if the function declaration is a redeclaration.
  8154. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8155. LookupResult &Previous,
  8156. bool IsMemberSpecialization) {
  8157. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8158. "Variably modified return types are not handled here");
  8159. // Determine whether the type of this function should be merged with
  8160. // a previous visible declaration. This never happens for functions in C++,
  8161. // and always happens in C if the previous declaration was visible.
  8162. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8163. !Previous.isShadowed();
  8164. bool Redeclaration = false;
  8165. NamedDecl *OldDecl = nullptr;
  8166. bool MayNeedOverloadableChecks = false;
  8167. // Merge or overload the declaration with an existing declaration of
  8168. // the same name, if appropriate.
  8169. if (!Previous.empty()) {
  8170. // Determine whether NewFD is an overload of PrevDecl or
  8171. // a declaration that requires merging. If it's an overload,
  8172. // there's no more work to do here; we'll just add the new
  8173. // function to the scope.
  8174. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8175. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8176. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8177. Redeclaration = true;
  8178. OldDecl = Candidate;
  8179. }
  8180. } else {
  8181. MayNeedOverloadableChecks = true;
  8182. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8183. /*NewIsUsingDecl*/ false)) {
  8184. case Ovl_Match:
  8185. Redeclaration = true;
  8186. break;
  8187. case Ovl_NonFunction:
  8188. Redeclaration = true;
  8189. break;
  8190. case Ovl_Overload:
  8191. Redeclaration = false;
  8192. break;
  8193. }
  8194. }
  8195. }
  8196. // Check for a previous extern "C" declaration with this name.
  8197. if (!Redeclaration &&
  8198. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8199. if (!Previous.empty()) {
  8200. // This is an extern "C" declaration with the same name as a previous
  8201. // declaration, and thus redeclares that entity...
  8202. Redeclaration = true;
  8203. OldDecl = Previous.getFoundDecl();
  8204. MergeTypeWithPrevious = false;
  8205. // ... except in the presence of __attribute__((overloadable)).
  8206. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8207. NewFD->hasAttr<OverloadableAttr>()) {
  8208. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8209. MayNeedOverloadableChecks = true;
  8210. Redeclaration = false;
  8211. OldDecl = nullptr;
  8212. }
  8213. }
  8214. }
  8215. }
  8216. // C++11 [dcl.constexpr]p8:
  8217. // A constexpr specifier for a non-static member function that is not
  8218. // a constructor declares that member function to be const.
  8219. //
  8220. // This needs to be delayed until we know whether this is an out-of-line
  8221. // definition of a static member function.
  8222. //
  8223. // This rule is not present in C++1y, so we produce a backwards
  8224. // compatibility warning whenever it happens in C++11.
  8225. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8226. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8227. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8228. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  8229. CXXMethodDecl *OldMD = nullptr;
  8230. if (OldDecl)
  8231. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8232. if (!OldMD || !OldMD->isStatic()) {
  8233. const FunctionProtoType *FPT =
  8234. MD->getType()->castAs<FunctionProtoType>();
  8235. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8236. EPI.TypeQuals |= Qualifiers::Const;
  8237. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8238. FPT->getParamTypes(), EPI));
  8239. // Warn that we did this, if we're not performing template instantiation.
  8240. // In that case, we'll have warned already when the template was defined.
  8241. if (!inTemplateInstantiation()) {
  8242. SourceLocation AddConstLoc;
  8243. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8244. .IgnoreParens().getAs<FunctionTypeLoc>())
  8245. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8246. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8247. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8248. }
  8249. }
  8250. }
  8251. if (Redeclaration) {
  8252. // NewFD and OldDecl represent declarations that need to be
  8253. // merged.
  8254. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8255. NewFD->setInvalidDecl();
  8256. return Redeclaration;
  8257. }
  8258. Previous.clear();
  8259. Previous.addDecl(OldDecl);
  8260. if (FunctionTemplateDecl *OldTemplateDecl
  8261. = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8262. NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
  8263. FunctionTemplateDecl *NewTemplateDecl
  8264. = NewFD->getDescribedFunctionTemplate();
  8265. assert(NewTemplateDecl && "Template/non-template mismatch");
  8266. if (CXXMethodDecl *Method
  8267. = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
  8268. Method->setAccess(OldTemplateDecl->getAccess());
  8269. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8270. }
  8271. // If this is an explicit specialization of a member that is a function
  8272. // template, mark it as a member specialization.
  8273. if (IsMemberSpecialization &&
  8274. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8275. NewTemplateDecl->setMemberSpecialization();
  8276. assert(OldTemplateDecl->isMemberSpecialization());
  8277. // Explicit specializations of a member template do not inherit deleted
  8278. // status from the parent member template that they are specializing.
  8279. if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
  8280. FunctionDecl *const OldTemplatedDecl =
  8281. OldTemplateDecl->getTemplatedDecl();
  8282. // FIXME: This assert will not hold in the presence of modules.
  8283. assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
  8284. // FIXME: We need an update record for this AST mutation.
  8285. OldTemplatedDecl->setDeletedAsWritten(false);
  8286. }
  8287. }
  8288. } else {
  8289. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8290. // This needs to happen first so that 'inline' propagates.
  8291. NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
  8292. if (isa<CXXMethodDecl>(NewFD))
  8293. NewFD->setAccess(OldDecl->getAccess());
  8294. }
  8295. }
  8296. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  8297. !NewFD->getAttr<OverloadableAttr>()) {
  8298. assert((Previous.empty() ||
  8299. llvm::any_of(Previous,
  8300. [](const NamedDecl *ND) {
  8301. return ND->hasAttr<OverloadableAttr>();
  8302. })) &&
  8303. "Non-redecls shouldn't happen without overloadable present");
  8304. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  8305. const auto *FD = dyn_cast<FunctionDecl>(ND);
  8306. return FD && !FD->hasAttr<OverloadableAttr>();
  8307. });
  8308. if (OtherUnmarkedIter != Previous.end()) {
  8309. Diag(NewFD->getLocation(),
  8310. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  8311. Diag((*OtherUnmarkedIter)->getLocation(),
  8312. diag::note_attribute_overloadable_prev_overload)
  8313. << false;
  8314. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  8315. }
  8316. }
  8317. // Semantic checking for this function declaration (in isolation).
  8318. if (getLangOpts().CPlusPlus) {
  8319. // C++-specific checks.
  8320. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  8321. CheckConstructor(Constructor);
  8322. } else if (CXXDestructorDecl *Destructor =
  8323. dyn_cast<CXXDestructorDecl>(NewFD)) {
  8324. CXXRecordDecl *Record = Destructor->getParent();
  8325. QualType ClassType = Context.getTypeDeclType(Record);
  8326. // FIXME: Shouldn't we be able to perform this check even when the class
  8327. // type is dependent? Both gcc and edg can handle that.
  8328. if (!ClassType->isDependentType()) {
  8329. DeclarationName Name
  8330. = Context.DeclarationNames.getCXXDestructorName(
  8331. Context.getCanonicalType(ClassType));
  8332. if (NewFD->getDeclName() != Name) {
  8333. Diag(NewFD->getLocation(), diag::err_destructor_name);
  8334. NewFD->setInvalidDecl();
  8335. return Redeclaration;
  8336. }
  8337. }
  8338. } else if (CXXConversionDecl *Conversion
  8339. = dyn_cast<CXXConversionDecl>(NewFD)) {
  8340. ActOnConversionDeclarator(Conversion);
  8341. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  8342. if (auto *TD = Guide->getDescribedFunctionTemplate())
  8343. CheckDeductionGuideTemplate(TD);
  8344. // A deduction guide is not on the list of entities that can be
  8345. // explicitly specialized.
  8346. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  8347. Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
  8348. << /*explicit specialization*/ 1;
  8349. }
  8350. // Find any virtual functions that this function overrides.
  8351. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  8352. if (!Method->isFunctionTemplateSpecialization() &&
  8353. !Method->getDescribedFunctionTemplate() &&
  8354. Method->isCanonicalDecl()) {
  8355. if (AddOverriddenMethods(Method->getParent(), Method)) {
  8356. // If the function was marked as "static", we have a problem.
  8357. if (NewFD->getStorageClass() == SC_Static) {
  8358. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  8359. }
  8360. }
  8361. }
  8362. if (Method->isStatic())
  8363. checkThisInStaticMemberFunctionType(Method);
  8364. }
  8365. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  8366. if (NewFD->isOverloadedOperator() &&
  8367. CheckOverloadedOperatorDeclaration(NewFD)) {
  8368. NewFD->setInvalidDecl();
  8369. return Redeclaration;
  8370. }
  8371. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  8372. if (NewFD->getLiteralIdentifier() &&
  8373. CheckLiteralOperatorDeclaration(NewFD)) {
  8374. NewFD->setInvalidDecl();
  8375. return Redeclaration;
  8376. }
  8377. // In C++, check default arguments now that we have merged decls. Unless
  8378. // the lexical context is the class, because in this case this is done
  8379. // during delayed parsing anyway.
  8380. if (!CurContext->isRecord())
  8381. CheckCXXDefaultArguments(NewFD);
  8382. // If this function declares a builtin function, check the type of this
  8383. // declaration against the expected type for the builtin.
  8384. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  8385. ASTContext::GetBuiltinTypeError Error;
  8386. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  8387. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  8388. // If the type of the builtin differs only in its exception
  8389. // specification, that's OK.
  8390. // FIXME: If the types do differ in this way, it would be better to
  8391. // retain the 'noexcept' form of the type.
  8392. if (!T.isNull() &&
  8393. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  8394. NewFD->getType()))
  8395. // The type of this function differs from the type of the builtin,
  8396. // so forget about the builtin entirely.
  8397. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  8398. }
  8399. // If this function is declared as being extern "C", then check to see if
  8400. // the function returns a UDT (class, struct, or union type) that is not C
  8401. // compatible, and if it does, warn the user.
  8402. // But, issue any diagnostic on the first declaration only.
  8403. if (Previous.empty() && NewFD->isExternC()) {
  8404. QualType R = NewFD->getReturnType();
  8405. if (R->isIncompleteType() && !R->isVoidType())
  8406. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  8407. << NewFD << R;
  8408. else if (!R.isPODType(Context) && !R->isVoidType() &&
  8409. !R->isObjCObjectPointerType())
  8410. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  8411. }
  8412. // C++1z [dcl.fct]p6:
  8413. // [...] whether the function has a non-throwing exception-specification
  8414. // [is] part of the function type
  8415. //
  8416. // This results in an ABI break between C++14 and C++17 for functions whose
  8417. // declared type includes an exception-specification in a parameter or
  8418. // return type. (Exception specifications on the function itself are OK in
  8419. // most cases, and exception specifications are not permitted in most other
  8420. // contexts where they could make it into a mangling.)
  8421. if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
  8422. auto HasNoexcept = [&](QualType T) -> bool {
  8423. // Strip off declarator chunks that could be between us and a function
  8424. // type. We don't need to look far, exception specifications are very
  8425. // restricted prior to C++17.
  8426. if (auto *RT = T->getAs<ReferenceType>())
  8427. T = RT->getPointeeType();
  8428. else if (T->isAnyPointerType())
  8429. T = T->getPointeeType();
  8430. else if (auto *MPT = T->getAs<MemberPointerType>())
  8431. T = MPT->getPointeeType();
  8432. if (auto *FPT = T->getAs<FunctionProtoType>())
  8433. if (FPT->isNothrow(Context))
  8434. return true;
  8435. return false;
  8436. };
  8437. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  8438. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  8439. for (QualType T : FPT->param_types())
  8440. AnyNoexcept |= HasNoexcept(T);
  8441. if (AnyNoexcept)
  8442. Diag(NewFD->getLocation(),
  8443. diag::warn_cxx17_compat_exception_spec_in_signature)
  8444. << NewFD;
  8445. }
  8446. if (!Redeclaration && LangOpts.CUDA)
  8447. checkCUDATargetOverload(NewFD, Previous);
  8448. }
  8449. return Redeclaration;
  8450. }
  8451. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  8452. // C++11 [basic.start.main]p3:
  8453. // A program that [...] declares main to be inline, static or
  8454. // constexpr is ill-formed.
  8455. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  8456. // appear in a declaration of main.
  8457. // static main is not an error under C99, but we should warn about it.
  8458. // We accept _Noreturn main as an extension.
  8459. if (FD->getStorageClass() == SC_Static)
  8460. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  8461. ? diag::err_static_main : diag::warn_static_main)
  8462. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  8463. if (FD->isInlineSpecified())
  8464. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  8465. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  8466. if (DS.isNoreturnSpecified()) {
  8467. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  8468. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  8469. Diag(NoreturnLoc, diag::ext_noreturn_main);
  8470. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  8471. << FixItHint::CreateRemoval(NoreturnRange);
  8472. }
  8473. if (FD->isConstexpr()) {
  8474. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  8475. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  8476. FD->setConstexpr(false);
  8477. }
  8478. if (getLangOpts().OpenCL) {
  8479. Diag(FD->getLocation(), diag::err_opencl_no_main)
  8480. << FD->hasAttr<OpenCLKernelAttr>();
  8481. FD->setInvalidDecl();
  8482. return;
  8483. }
  8484. QualType T = FD->getType();
  8485. assert(T->isFunctionType() && "function decl is not of function type");
  8486. const FunctionType* FT = T->castAs<FunctionType>();
  8487. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  8488. // In C with GNU extensions we allow main() to have non-integer return
  8489. // type, but we should warn about the extension, and we disable the
  8490. // implicit-return-zero rule.
  8491. // GCC in C mode accepts qualified 'int'.
  8492. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  8493. FD->setHasImplicitReturnZero(true);
  8494. else {
  8495. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  8496. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8497. if (RTRange.isValid())
  8498. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  8499. << FixItHint::CreateReplacement(RTRange, "int");
  8500. }
  8501. } else {
  8502. // In C and C++, main magically returns 0 if you fall off the end;
  8503. // set the flag which tells us that.
  8504. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  8505. // All the standards say that main() should return 'int'.
  8506. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  8507. FD->setHasImplicitReturnZero(true);
  8508. else {
  8509. // Otherwise, this is just a flat-out error.
  8510. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8511. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  8512. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  8513. : FixItHint());
  8514. FD->setInvalidDecl(true);
  8515. }
  8516. }
  8517. // Treat protoless main() as nullary.
  8518. if (isa<FunctionNoProtoType>(FT)) return;
  8519. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  8520. unsigned nparams = FTP->getNumParams();
  8521. assert(FD->getNumParams() == nparams);
  8522. bool HasExtraParameters = (nparams > 3);
  8523. if (FTP->isVariadic()) {
  8524. Diag(FD->getLocation(), diag::ext_variadic_main);
  8525. // FIXME: if we had information about the location of the ellipsis, we
  8526. // could add a FixIt hint to remove it as a parameter.
  8527. }
  8528. // Darwin passes an undocumented fourth argument of type char**. If
  8529. // other platforms start sprouting these, the logic below will start
  8530. // getting shifty.
  8531. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  8532. HasExtraParameters = false;
  8533. if (HasExtraParameters) {
  8534. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  8535. FD->setInvalidDecl(true);
  8536. nparams = 3;
  8537. }
  8538. // FIXME: a lot of the following diagnostics would be improved
  8539. // if we had some location information about types.
  8540. QualType CharPP =
  8541. Context.getPointerType(Context.getPointerType(Context.CharTy));
  8542. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  8543. for (unsigned i = 0; i < nparams; ++i) {
  8544. QualType AT = FTP->getParamType(i);
  8545. bool mismatch = true;
  8546. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  8547. mismatch = false;
  8548. else if (Expected[i] == CharPP) {
  8549. // As an extension, the following forms are okay:
  8550. // char const **
  8551. // char const * const *
  8552. // char * const *
  8553. QualifierCollector qs;
  8554. const PointerType* PT;
  8555. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  8556. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  8557. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  8558. Context.CharTy)) {
  8559. qs.removeConst();
  8560. mismatch = !qs.empty();
  8561. }
  8562. }
  8563. if (mismatch) {
  8564. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  8565. // TODO: suggest replacing given type with expected type
  8566. FD->setInvalidDecl(true);
  8567. }
  8568. }
  8569. if (nparams == 1 && !FD->isInvalidDecl()) {
  8570. Diag(FD->getLocation(), diag::warn_main_one_arg);
  8571. }
  8572. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8573. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8574. FD->setInvalidDecl();
  8575. }
  8576. }
  8577. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  8578. QualType T = FD->getType();
  8579. assert(T->isFunctionType() && "function decl is not of function type");
  8580. const FunctionType *FT = T->castAs<FunctionType>();
  8581. // Set an implicit return of 'zero' if the function can return some integral,
  8582. // enumeration, pointer or nullptr type.
  8583. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  8584. FT->getReturnType()->isAnyPointerType() ||
  8585. FT->getReturnType()->isNullPtrType())
  8586. // DllMain is exempt because a return value of zero means it failed.
  8587. if (FD->getName() != "DllMain")
  8588. FD->setHasImplicitReturnZero(true);
  8589. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8590. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8591. FD->setInvalidDecl();
  8592. }
  8593. }
  8594. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  8595. // FIXME: Need strict checking. In C89, we need to check for
  8596. // any assignment, increment, decrement, function-calls, or
  8597. // commas outside of a sizeof. In C99, it's the same list,
  8598. // except that the aforementioned are allowed in unevaluated
  8599. // expressions. Everything else falls under the
  8600. // "may accept other forms of constant expressions" exception.
  8601. // (We never end up here for C++, so the constant expression
  8602. // rules there don't matter.)
  8603. const Expr *Culprit;
  8604. if (Init->isConstantInitializer(Context, false, &Culprit))
  8605. return false;
  8606. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  8607. << Culprit->getSourceRange();
  8608. return true;
  8609. }
  8610. namespace {
  8611. // Visits an initialization expression to see if OrigDecl is evaluated in
  8612. // its own initialization and throws a warning if it does.
  8613. class SelfReferenceChecker
  8614. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  8615. Sema &S;
  8616. Decl *OrigDecl;
  8617. bool isRecordType;
  8618. bool isPODType;
  8619. bool isReferenceType;
  8620. bool isInitList;
  8621. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  8622. public:
  8623. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  8624. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  8625. S(S), OrigDecl(OrigDecl) {
  8626. isPODType = false;
  8627. isRecordType = false;
  8628. isReferenceType = false;
  8629. isInitList = false;
  8630. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  8631. isPODType = VD->getType().isPODType(S.Context);
  8632. isRecordType = VD->getType()->isRecordType();
  8633. isReferenceType = VD->getType()->isReferenceType();
  8634. }
  8635. }
  8636. // For most expressions, just call the visitor. For initializer lists,
  8637. // track the index of the field being initialized since fields are
  8638. // initialized in order allowing use of previously initialized fields.
  8639. void CheckExpr(Expr *E) {
  8640. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  8641. if (!InitList) {
  8642. Visit(E);
  8643. return;
  8644. }
  8645. // Track and increment the index here.
  8646. isInitList = true;
  8647. InitFieldIndex.push_back(0);
  8648. for (auto Child : InitList->children()) {
  8649. CheckExpr(cast<Expr>(Child));
  8650. ++InitFieldIndex.back();
  8651. }
  8652. InitFieldIndex.pop_back();
  8653. }
  8654. // Returns true if MemberExpr is checked and no further checking is needed.
  8655. // Returns false if additional checking is required.
  8656. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  8657. llvm::SmallVector<FieldDecl*, 4> Fields;
  8658. Expr *Base = E;
  8659. bool ReferenceField = false;
  8660. // Get the field memebers used.
  8661. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8662. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  8663. if (!FD)
  8664. return false;
  8665. Fields.push_back(FD);
  8666. if (FD->getType()->isReferenceType())
  8667. ReferenceField = true;
  8668. Base = ME->getBase()->IgnoreParenImpCasts();
  8669. }
  8670. // Keep checking only if the base Decl is the same.
  8671. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  8672. if (!DRE || DRE->getDecl() != OrigDecl)
  8673. return false;
  8674. // A reference field can be bound to an unininitialized field.
  8675. if (CheckReference && !ReferenceField)
  8676. return true;
  8677. // Convert FieldDecls to their index number.
  8678. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  8679. for (const FieldDecl *I : llvm::reverse(Fields))
  8680. UsedFieldIndex.push_back(I->getFieldIndex());
  8681. // See if a warning is needed by checking the first difference in index
  8682. // numbers. If field being used has index less than the field being
  8683. // initialized, then the use is safe.
  8684. for (auto UsedIter = UsedFieldIndex.begin(),
  8685. UsedEnd = UsedFieldIndex.end(),
  8686. OrigIter = InitFieldIndex.begin(),
  8687. OrigEnd = InitFieldIndex.end();
  8688. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  8689. if (*UsedIter < *OrigIter)
  8690. return true;
  8691. if (*UsedIter > *OrigIter)
  8692. break;
  8693. }
  8694. // TODO: Add a different warning which will print the field names.
  8695. HandleDeclRefExpr(DRE);
  8696. return true;
  8697. }
  8698. // For most expressions, the cast is directly above the DeclRefExpr.
  8699. // For conditional operators, the cast can be outside the conditional
  8700. // operator if both expressions are DeclRefExpr's.
  8701. void HandleValue(Expr *E) {
  8702. E = E->IgnoreParens();
  8703. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  8704. HandleDeclRefExpr(DRE);
  8705. return;
  8706. }
  8707. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  8708. Visit(CO->getCond());
  8709. HandleValue(CO->getTrueExpr());
  8710. HandleValue(CO->getFalseExpr());
  8711. return;
  8712. }
  8713. if (BinaryConditionalOperator *BCO =
  8714. dyn_cast<BinaryConditionalOperator>(E)) {
  8715. Visit(BCO->getCond());
  8716. HandleValue(BCO->getFalseExpr());
  8717. return;
  8718. }
  8719. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  8720. HandleValue(OVE->getSourceExpr());
  8721. return;
  8722. }
  8723. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  8724. if (BO->getOpcode() == BO_Comma) {
  8725. Visit(BO->getLHS());
  8726. HandleValue(BO->getRHS());
  8727. return;
  8728. }
  8729. }
  8730. if (isa<MemberExpr>(E)) {
  8731. if (isInitList) {
  8732. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  8733. false /*CheckReference*/))
  8734. return;
  8735. }
  8736. Expr *Base = E->IgnoreParenImpCasts();
  8737. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8738. // Check for static member variables and don't warn on them.
  8739. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8740. return;
  8741. Base = ME->getBase()->IgnoreParenImpCasts();
  8742. }
  8743. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  8744. HandleDeclRefExpr(DRE);
  8745. return;
  8746. }
  8747. Visit(E);
  8748. }
  8749. // Reference types not handled in HandleValue are handled here since all
  8750. // uses of references are bad, not just r-value uses.
  8751. void VisitDeclRefExpr(DeclRefExpr *E) {
  8752. if (isReferenceType)
  8753. HandleDeclRefExpr(E);
  8754. }
  8755. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  8756. if (E->getCastKind() == CK_LValueToRValue) {
  8757. HandleValue(E->getSubExpr());
  8758. return;
  8759. }
  8760. Inherited::VisitImplicitCastExpr(E);
  8761. }
  8762. void VisitMemberExpr(MemberExpr *E) {
  8763. if (isInitList) {
  8764. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  8765. return;
  8766. }
  8767. // Don't warn on arrays since they can be treated as pointers.
  8768. if (E->getType()->canDecayToPointerType()) return;
  8769. // Warn when a non-static method call is followed by non-static member
  8770. // field accesses, which is followed by a DeclRefExpr.
  8771. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  8772. bool Warn = (MD && !MD->isStatic());
  8773. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  8774. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8775. if (!isa<FieldDecl>(ME->getMemberDecl()))
  8776. Warn = false;
  8777. Base = ME->getBase()->IgnoreParenImpCasts();
  8778. }
  8779. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  8780. if (Warn)
  8781. HandleDeclRefExpr(DRE);
  8782. return;
  8783. }
  8784. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  8785. // Visit that expression.
  8786. Visit(Base);
  8787. }
  8788. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  8789. Expr *Callee = E->getCallee();
  8790. if (isa<UnresolvedLookupExpr>(Callee))
  8791. return Inherited::VisitCXXOperatorCallExpr(E);
  8792. Visit(Callee);
  8793. for (auto Arg: E->arguments())
  8794. HandleValue(Arg->IgnoreParenImpCasts());
  8795. }
  8796. void VisitUnaryOperator(UnaryOperator *E) {
  8797. // For POD record types, addresses of its own members are well-defined.
  8798. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  8799. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  8800. if (!isPODType)
  8801. HandleValue(E->getSubExpr());
  8802. return;
  8803. }
  8804. if (E->isIncrementDecrementOp()) {
  8805. HandleValue(E->getSubExpr());
  8806. return;
  8807. }
  8808. Inherited::VisitUnaryOperator(E);
  8809. }
  8810. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  8811. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  8812. if (E->getConstructor()->isCopyConstructor()) {
  8813. Expr *ArgExpr = E->getArg(0);
  8814. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  8815. if (ILE->getNumInits() == 1)
  8816. ArgExpr = ILE->getInit(0);
  8817. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  8818. if (ICE->getCastKind() == CK_NoOp)
  8819. ArgExpr = ICE->getSubExpr();
  8820. HandleValue(ArgExpr);
  8821. return;
  8822. }
  8823. Inherited::VisitCXXConstructExpr(E);
  8824. }
  8825. void VisitCallExpr(CallExpr *E) {
  8826. // Treat std::move as a use.
  8827. if (E->getNumArgs() == 1) {
  8828. if (FunctionDecl *FD = E->getDirectCallee()) {
  8829. if (FD->isInStdNamespace() && FD->getIdentifier() &&
  8830. FD->getIdentifier()->isStr("move")) {
  8831. HandleValue(E->getArg(0));
  8832. return;
  8833. }
  8834. }
  8835. }
  8836. Inherited::VisitCallExpr(E);
  8837. }
  8838. void VisitBinaryOperator(BinaryOperator *E) {
  8839. if (E->isCompoundAssignmentOp()) {
  8840. HandleValue(E->getLHS());
  8841. Visit(E->getRHS());
  8842. return;
  8843. }
  8844. Inherited::VisitBinaryOperator(E);
  8845. }
  8846. // A custom visitor for BinaryConditionalOperator is needed because the
  8847. // regular visitor would check the condition and true expression separately
  8848. // but both point to the same place giving duplicate diagnostics.
  8849. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  8850. Visit(E->getCond());
  8851. Visit(E->getFalseExpr());
  8852. }
  8853. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  8854. Decl* ReferenceDecl = DRE->getDecl();
  8855. if (OrigDecl != ReferenceDecl) return;
  8856. unsigned diag;
  8857. if (isReferenceType) {
  8858. diag = diag::warn_uninit_self_reference_in_reference_init;
  8859. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  8860. diag = diag::warn_static_self_reference_in_init;
  8861. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  8862. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  8863. DRE->getDecl()->getType()->isRecordType()) {
  8864. diag = diag::warn_uninit_self_reference_in_init;
  8865. } else {
  8866. // Local variables will be handled by the CFG analysis.
  8867. return;
  8868. }
  8869. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  8870. S.PDiag(diag)
  8871. << DRE->getNameInfo().getName()
  8872. << OrigDecl->getLocation()
  8873. << DRE->getSourceRange());
  8874. }
  8875. };
  8876. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  8877. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  8878. bool DirectInit) {
  8879. // Parameters arguments are occassionially constructed with itself,
  8880. // for instance, in recursive functions. Skip them.
  8881. if (isa<ParmVarDecl>(OrigDecl))
  8882. return;
  8883. E = E->IgnoreParens();
  8884. // Skip checking T a = a where T is not a record or reference type.
  8885. // Doing so is a way to silence uninitialized warnings.
  8886. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  8887. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  8888. if (ICE->getCastKind() == CK_LValueToRValue)
  8889. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  8890. if (DRE->getDecl() == OrigDecl)
  8891. return;
  8892. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  8893. }
  8894. } // end anonymous namespace
  8895. namespace {
  8896. // Simple wrapper to add the name of a variable or (if no variable is
  8897. // available) a DeclarationName into a diagnostic.
  8898. struct VarDeclOrName {
  8899. VarDecl *VDecl;
  8900. DeclarationName Name;
  8901. friend const Sema::SemaDiagnosticBuilder &
  8902. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  8903. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  8904. }
  8905. };
  8906. } // end anonymous namespace
  8907. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  8908. DeclarationName Name, QualType Type,
  8909. TypeSourceInfo *TSI,
  8910. SourceRange Range, bool DirectInit,
  8911. Expr *Init) {
  8912. bool IsInitCapture = !VDecl;
  8913. assert((!VDecl || !VDecl->isInitCapture()) &&
  8914. "init captures are expected to be deduced prior to initialization");
  8915. VarDeclOrName VN{VDecl, Name};
  8916. DeducedType *Deduced = Type->getContainedDeducedType();
  8917. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  8918. // C++11 [dcl.spec.auto]p3
  8919. if (!Init) {
  8920. assert(VDecl && "no init for init capture deduction?");
  8921. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  8922. << VDecl->getDeclName() << Type;
  8923. return QualType();
  8924. }
  8925. ArrayRef<Expr*> DeduceInits = Init;
  8926. if (DirectInit) {
  8927. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  8928. DeduceInits = PL->exprs();
  8929. }
  8930. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  8931. assert(VDecl && "non-auto type for init capture deduction?");
  8932. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  8933. InitializationKind Kind = InitializationKind::CreateForInit(
  8934. VDecl->getLocation(), DirectInit, Init);
  8935. // FIXME: Initialization should not be taking a mutable list of inits.
  8936. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  8937. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  8938. InitsCopy);
  8939. }
  8940. if (DirectInit) {
  8941. if (auto *IL = dyn_cast<InitListExpr>(Init))
  8942. DeduceInits = IL->inits();
  8943. }
  8944. // Deduction only works if we have exactly one source expression.
  8945. if (DeduceInits.empty()) {
  8946. // It isn't possible to write this directly, but it is possible to
  8947. // end up in this situation with "auto x(some_pack...);"
  8948. Diag(Init->getLocStart(), IsInitCapture
  8949. ? diag::err_init_capture_no_expression
  8950. : diag::err_auto_var_init_no_expression)
  8951. << VN << Type << Range;
  8952. return QualType();
  8953. }
  8954. if (DeduceInits.size() > 1) {
  8955. Diag(DeduceInits[1]->getLocStart(),
  8956. IsInitCapture ? diag::err_init_capture_multiple_expressions
  8957. : diag::err_auto_var_init_multiple_expressions)
  8958. << VN << Type << Range;
  8959. return QualType();
  8960. }
  8961. Expr *DeduceInit = DeduceInits[0];
  8962. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  8963. Diag(Init->getLocStart(), IsInitCapture
  8964. ? diag::err_init_capture_paren_braces
  8965. : diag::err_auto_var_init_paren_braces)
  8966. << isa<InitListExpr>(Init) << VN << Type << Range;
  8967. return QualType();
  8968. }
  8969. // Expressions default to 'id' when we're in a debugger.
  8970. bool DefaultedAnyToId = false;
  8971. if (getLangOpts().DebuggerCastResultToId &&
  8972. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  8973. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  8974. if (Result.isInvalid()) {
  8975. return QualType();
  8976. }
  8977. Init = Result.get();
  8978. DefaultedAnyToId = true;
  8979. }
  8980. // C++ [dcl.decomp]p1:
  8981. // If the assignment-expression [...] has array type A and no ref-qualifier
  8982. // is present, e has type cv A
  8983. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  8984. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  8985. DeduceInit->getType()->isConstantArrayType())
  8986. return Context.getQualifiedType(DeduceInit->getType(),
  8987. Type.getQualifiers());
  8988. QualType DeducedType;
  8989. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  8990. if (!IsInitCapture)
  8991. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  8992. else if (isa<InitListExpr>(Init))
  8993. Diag(Range.getBegin(),
  8994. diag::err_init_capture_deduction_failure_from_init_list)
  8995. << VN
  8996. << (DeduceInit->getType().isNull() ? TSI->getType()
  8997. : DeduceInit->getType())
  8998. << DeduceInit->getSourceRange();
  8999. else
  9000. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9001. << VN << TSI->getType()
  9002. << (DeduceInit->getType().isNull() ? TSI->getType()
  9003. : DeduceInit->getType())
  9004. << DeduceInit->getSourceRange();
  9005. }
  9006. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9007. // 'id' instead of a specific object type prevents most of our usual
  9008. // checks.
  9009. // We only want to warn outside of template instantiations, though:
  9010. // inside a template, the 'id' could have come from a parameter.
  9011. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9012. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9013. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9014. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9015. }
  9016. return DeducedType;
  9017. }
  9018. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9019. Expr *Init) {
  9020. QualType DeducedType = deduceVarTypeFromInitializer(
  9021. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9022. VDecl->getSourceRange(), DirectInit, Init);
  9023. if (DeducedType.isNull()) {
  9024. VDecl->setInvalidDecl();
  9025. return true;
  9026. }
  9027. VDecl->setType(DeducedType);
  9028. assert(VDecl->isLinkageValid());
  9029. // In ARC, infer lifetime.
  9030. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9031. VDecl->setInvalidDecl();
  9032. // If this is a redeclaration, check that the type we just deduced matches
  9033. // the previously declared type.
  9034. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9035. // We never need to merge the type, because we cannot form an incomplete
  9036. // array of auto, nor deduce such a type.
  9037. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9038. }
  9039. // Check the deduced type is valid for a variable declaration.
  9040. CheckVariableDeclarationType(VDecl);
  9041. return VDecl->isInvalidDecl();
  9042. }
  9043. /// AddInitializerToDecl - Adds the initializer Init to the
  9044. /// declaration dcl. If DirectInit is true, this is C++ direct
  9045. /// initialization rather than copy initialization.
  9046. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9047. // If there is no declaration, there was an error parsing it. Just ignore
  9048. // the initializer.
  9049. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9050. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9051. return;
  9052. }
  9053. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9054. // Pure-specifiers are handled in ActOnPureSpecifier.
  9055. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9056. << Method->getDeclName() << Init->getSourceRange();
  9057. Method->setInvalidDecl();
  9058. return;
  9059. }
  9060. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9061. if (!VDecl) {
  9062. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9063. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9064. RealDecl->setInvalidDecl();
  9065. return;
  9066. }
  9067. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9068. if (VDecl->getType()->isUndeducedType()) {
  9069. // Attempt typo correction early so that the type of the init expression can
  9070. // be deduced based on the chosen correction if the original init contains a
  9071. // TypoExpr.
  9072. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9073. if (!Res.isUsable()) {
  9074. RealDecl->setInvalidDecl();
  9075. return;
  9076. }
  9077. Init = Res.get();
  9078. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9079. return;
  9080. }
  9081. // dllimport cannot be used on variable definitions.
  9082. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9083. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9084. VDecl->setInvalidDecl();
  9085. return;
  9086. }
  9087. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9088. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9089. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9090. VDecl->setInvalidDecl();
  9091. return;
  9092. }
  9093. if (!VDecl->getType()->isDependentType()) {
  9094. // A definition must end up with a complete type, which means it must be
  9095. // complete with the restriction that an array type might be completed by
  9096. // the initializer; note that later code assumes this restriction.
  9097. QualType BaseDeclType = VDecl->getType();
  9098. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9099. BaseDeclType = Array->getElementType();
  9100. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9101. diag::err_typecheck_decl_incomplete_type)) {
  9102. RealDecl->setInvalidDecl();
  9103. return;
  9104. }
  9105. // The variable can not have an abstract class type.
  9106. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9107. diag::err_abstract_type_in_decl,
  9108. AbstractVariableType))
  9109. VDecl->setInvalidDecl();
  9110. }
  9111. // If adding the initializer will turn this declaration into a definition,
  9112. // and we already have a definition for this variable, diagnose or otherwise
  9113. // handle the situation.
  9114. VarDecl *Def;
  9115. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9116. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9117. !VDecl->isThisDeclarationADemotedDefinition() &&
  9118. checkVarDeclRedefinition(Def, VDecl))
  9119. return;
  9120. if (getLangOpts().CPlusPlus) {
  9121. // C++ [class.static.data]p4
  9122. // If a static data member is of const integral or const
  9123. // enumeration type, its declaration in the class definition can
  9124. // specify a constant-initializer which shall be an integral
  9125. // constant expression (5.19). In that case, the member can appear
  9126. // in integral constant expressions. The member shall still be
  9127. // defined in a namespace scope if it is used in the program and the
  9128. // namespace scope definition shall not contain an initializer.
  9129. //
  9130. // We already performed a redefinition check above, but for static
  9131. // data members we also need to check whether there was an in-class
  9132. // declaration with an initializer.
  9133. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9134. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9135. << VDecl->getDeclName();
  9136. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9137. diag::note_previous_initializer)
  9138. << 0;
  9139. return;
  9140. }
  9141. if (VDecl->hasLocalStorage())
  9142. getCurFunction()->setHasBranchProtectedScope();
  9143. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9144. VDecl->setInvalidDecl();
  9145. return;
  9146. }
  9147. }
  9148. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  9149. // a kernel function cannot be initialized."
  9150. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  9151. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  9152. VDecl->setInvalidDecl();
  9153. return;
  9154. }
  9155. // Get the decls type and save a reference for later, since
  9156. // CheckInitializerTypes may change it.
  9157. QualType DclT = VDecl->getType(), SavT = DclT;
  9158. // Expressions default to 'id' when we're in a debugger
  9159. // and we are assigning it to a variable of Objective-C pointer type.
  9160. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  9161. Init->getType() == Context.UnknownAnyTy) {
  9162. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9163. if (Result.isInvalid()) {
  9164. VDecl->setInvalidDecl();
  9165. return;
  9166. }
  9167. Init = Result.get();
  9168. }
  9169. // Perform the initialization.
  9170. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  9171. if (!VDecl->isInvalidDecl()) {
  9172. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9173. InitializationKind Kind = InitializationKind::CreateForInit(
  9174. VDecl->getLocation(), DirectInit, Init);
  9175. MultiExprArg Args = Init;
  9176. if (CXXDirectInit)
  9177. Args = MultiExprArg(CXXDirectInit->getExprs(),
  9178. CXXDirectInit->getNumExprs());
  9179. // Try to correct any TypoExprs in the initialization arguments.
  9180. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  9181. ExprResult Res = CorrectDelayedTyposInExpr(
  9182. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  9183. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  9184. return Init.Failed() ? ExprError() : E;
  9185. });
  9186. if (Res.isInvalid()) {
  9187. VDecl->setInvalidDecl();
  9188. } else if (Res.get() != Args[Idx]) {
  9189. Args[Idx] = Res.get();
  9190. }
  9191. }
  9192. if (VDecl->isInvalidDecl())
  9193. return;
  9194. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  9195. /*TopLevelOfInitList=*/false,
  9196. /*TreatUnavailableAsInvalid=*/false);
  9197. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  9198. if (Result.isInvalid()) {
  9199. VDecl->setInvalidDecl();
  9200. return;
  9201. }
  9202. Init = Result.getAs<Expr>();
  9203. }
  9204. // Check for self-references within variable initializers.
  9205. // Variables declared within a function/method body (except for references)
  9206. // are handled by a dataflow analysis.
  9207. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  9208. VDecl->getType()->isReferenceType()) {
  9209. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  9210. }
  9211. // If the type changed, it means we had an incomplete type that was
  9212. // completed by the initializer. For example:
  9213. // int ary[] = { 1, 3, 5 };
  9214. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  9215. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  9216. VDecl->setType(DclT);
  9217. if (!VDecl->isInvalidDecl()) {
  9218. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  9219. if (VDecl->hasAttr<BlocksAttr>())
  9220. checkRetainCycles(VDecl, Init);
  9221. // It is safe to assign a weak reference into a strong variable.
  9222. // Although this code can still have problems:
  9223. // id x = self.weakProp;
  9224. // id y = self.weakProp;
  9225. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9226. // paths through the function. This should be revisited if
  9227. // -Wrepeated-use-of-weak is made flow-sensitive.
  9228. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  9229. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  9230. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9231. Init->getLocStart()))
  9232. getCurFunction()->markSafeWeakUse(Init);
  9233. }
  9234. // The initialization is usually a full-expression.
  9235. //
  9236. // FIXME: If this is a braced initialization of an aggregate, it is not
  9237. // an expression, and each individual field initializer is a separate
  9238. // full-expression. For instance, in:
  9239. //
  9240. // struct Temp { ~Temp(); };
  9241. // struct S { S(Temp); };
  9242. // struct T { S a, b; } t = { Temp(), Temp() }
  9243. //
  9244. // we should destroy the first Temp before constructing the second.
  9245. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9246. false,
  9247. VDecl->isConstexpr());
  9248. if (Result.isInvalid()) {
  9249. VDecl->setInvalidDecl();
  9250. return;
  9251. }
  9252. Init = Result.get();
  9253. // Attach the initializer to the decl.
  9254. VDecl->setInit(Init);
  9255. if (VDecl->isLocalVarDecl()) {
  9256. // Don't check the initializer if the declaration is malformed.
  9257. if (VDecl->isInvalidDecl()) {
  9258. // do nothing
  9259. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  9260. // This is true even in OpenCL C++.
  9261. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  9262. CheckForConstantInitializer(Init, DclT);
  9263. // Otherwise, C++ does not restrict the initializer.
  9264. } else if (getLangOpts().CPlusPlus) {
  9265. // do nothing
  9266. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9267. // static storage duration shall be constant expressions or string literals.
  9268. } else if (VDecl->getStorageClass() == SC_Static) {
  9269. CheckForConstantInitializer(Init, DclT);
  9270. // C89 is stricter than C99 for aggregate initializers.
  9271. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9272. // for an object that has aggregate or union type shall be
  9273. // constant expressions.
  9274. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9275. isa<InitListExpr>(Init)) {
  9276. const Expr *Culprit;
  9277. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  9278. Diag(Culprit->getExprLoc(),
  9279. diag::ext_aggregate_init_not_constant)
  9280. << Culprit->getSourceRange();
  9281. }
  9282. }
  9283. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  9284. VDecl->getLexicalDeclContext()->isRecord()) {
  9285. // This is an in-class initialization for a static data member, e.g.,
  9286. //
  9287. // struct S {
  9288. // static const int value = 17;
  9289. // };
  9290. // C++ [class.mem]p4:
  9291. // A member-declarator can contain a constant-initializer only
  9292. // if it declares a static member (9.4) of const integral or
  9293. // const enumeration type, see 9.4.2.
  9294. //
  9295. // C++11 [class.static.data]p3:
  9296. // If a non-volatile non-inline const static data member is of integral
  9297. // or enumeration type, its declaration in the class definition can
  9298. // specify a brace-or-equal-initializer in which every initializer-clause
  9299. // that is an assignment-expression is a constant expression. A static
  9300. // data member of literal type can be declared in the class definition
  9301. // with the constexpr specifier; if so, its declaration shall specify a
  9302. // brace-or-equal-initializer in which every initializer-clause that is
  9303. // an assignment-expression is a constant expression.
  9304. // Do nothing on dependent types.
  9305. if (DclT->isDependentType()) {
  9306. // Allow any 'static constexpr' members, whether or not they are of literal
  9307. // type. We separately check that every constexpr variable is of literal
  9308. // type.
  9309. } else if (VDecl->isConstexpr()) {
  9310. // Require constness.
  9311. } else if (!DclT.isConstQualified()) {
  9312. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  9313. << Init->getSourceRange();
  9314. VDecl->setInvalidDecl();
  9315. // We allow integer constant expressions in all cases.
  9316. } else if (DclT->isIntegralOrEnumerationType()) {
  9317. // Check whether the expression is a constant expression.
  9318. SourceLocation Loc;
  9319. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  9320. // In C++11, a non-constexpr const static data member with an
  9321. // in-class initializer cannot be volatile.
  9322. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  9323. else if (Init->isValueDependent())
  9324. ; // Nothing to check.
  9325. else if (Init->isIntegerConstantExpr(Context, &Loc))
  9326. ; // Ok, it's an ICE!
  9327. else if (Init->isEvaluatable(Context)) {
  9328. // If we can constant fold the initializer through heroics, accept it,
  9329. // but report this as a use of an extension for -pedantic.
  9330. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  9331. << Init->getSourceRange();
  9332. } else {
  9333. // Otherwise, this is some crazy unknown case. Report the issue at the
  9334. // location provided by the isIntegerConstantExpr failed check.
  9335. Diag(Loc, diag::err_in_class_initializer_non_constant)
  9336. << Init->getSourceRange();
  9337. VDecl->setInvalidDecl();
  9338. }
  9339. // We allow foldable floating-point constants as an extension.
  9340. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  9341. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  9342. // it anyway and provide a fixit to add the 'constexpr'.
  9343. if (getLangOpts().CPlusPlus11) {
  9344. Diag(VDecl->getLocation(),
  9345. diag::ext_in_class_initializer_float_type_cxx11)
  9346. << DclT << Init->getSourceRange();
  9347. Diag(VDecl->getLocStart(),
  9348. diag::note_in_class_initializer_float_type_cxx11)
  9349. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9350. } else {
  9351. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  9352. << DclT << Init->getSourceRange();
  9353. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  9354. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  9355. << Init->getSourceRange();
  9356. VDecl->setInvalidDecl();
  9357. }
  9358. }
  9359. // Suggest adding 'constexpr' in C++11 for literal types.
  9360. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  9361. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  9362. << DclT << Init->getSourceRange()
  9363. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9364. VDecl->setConstexpr(true);
  9365. } else {
  9366. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  9367. << DclT << Init->getSourceRange();
  9368. VDecl->setInvalidDecl();
  9369. }
  9370. } else if (VDecl->isFileVarDecl()) {
  9371. // In C, extern is typically used to avoid tentative definitions when
  9372. // declaring variables in headers, but adding an intializer makes it a
  9373. // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
  9374. // In C++, extern is often used to give implictly static const variables
  9375. // external linkage, so don't warn in that case. If selectany is present,
  9376. // this might be header code intended for C and C++ inclusion, so apply the
  9377. // C++ rules.
  9378. if (VDecl->getStorageClass() == SC_Extern &&
  9379. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  9380. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  9381. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  9382. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  9383. Diag(VDecl->getLocation(), diag::warn_extern_init);
  9384. // C99 6.7.8p4. All file scoped initializers need to be constant.
  9385. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  9386. CheckForConstantInitializer(Init, DclT);
  9387. }
  9388. // We will represent direct-initialization similarly to copy-initialization:
  9389. // int x(1); -as-> int x = 1;
  9390. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  9391. //
  9392. // Clients that want to distinguish between the two forms, can check for
  9393. // direct initializer using VarDecl::getInitStyle().
  9394. // A major benefit is that clients that don't particularly care about which
  9395. // exactly form was it (like the CodeGen) can handle both cases without
  9396. // special case code.
  9397. // C++ 8.5p11:
  9398. // The form of initialization (using parentheses or '=') is generally
  9399. // insignificant, but does matter when the entity being initialized has a
  9400. // class type.
  9401. if (CXXDirectInit) {
  9402. assert(DirectInit && "Call-style initializer must be direct init.");
  9403. VDecl->setInitStyle(VarDecl::CallInit);
  9404. } else if (DirectInit) {
  9405. // This must be list-initialization. No other way is direct-initialization.
  9406. VDecl->setInitStyle(VarDecl::ListInit);
  9407. }
  9408. CheckCompleteVariableDeclaration(VDecl);
  9409. }
  9410. /// ActOnInitializerError - Given that there was an error parsing an
  9411. /// initializer for the given declaration, try to return to some form
  9412. /// of sanity.
  9413. void Sema::ActOnInitializerError(Decl *D) {
  9414. // Our main concern here is re-establishing invariants like "a
  9415. // variable's type is either dependent or complete".
  9416. if (!D || D->isInvalidDecl()) return;
  9417. VarDecl *VD = dyn_cast<VarDecl>(D);
  9418. if (!VD) return;
  9419. // Bindings are not usable if we can't make sense of the initializer.
  9420. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  9421. for (auto *BD : DD->bindings())
  9422. BD->setInvalidDecl();
  9423. // Auto types are meaningless if we can't make sense of the initializer.
  9424. if (ParsingInitForAutoVars.count(D)) {
  9425. D->setInvalidDecl();
  9426. return;
  9427. }
  9428. QualType Ty = VD->getType();
  9429. if (Ty->isDependentType()) return;
  9430. // Require a complete type.
  9431. if (RequireCompleteType(VD->getLocation(),
  9432. Context.getBaseElementType(Ty),
  9433. diag::err_typecheck_decl_incomplete_type)) {
  9434. VD->setInvalidDecl();
  9435. return;
  9436. }
  9437. // Require a non-abstract type.
  9438. if (RequireNonAbstractType(VD->getLocation(), Ty,
  9439. diag::err_abstract_type_in_decl,
  9440. AbstractVariableType)) {
  9441. VD->setInvalidDecl();
  9442. return;
  9443. }
  9444. // Don't bother complaining about constructors or destructors,
  9445. // though.
  9446. }
  9447. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  9448. // If there is no declaration, there was an error parsing it. Just ignore it.
  9449. if (!RealDecl)
  9450. return;
  9451. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  9452. QualType Type = Var->getType();
  9453. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  9454. if (isa<DecompositionDecl>(RealDecl)) {
  9455. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  9456. Var->setInvalidDecl();
  9457. return;
  9458. }
  9459. if (Type->isUndeducedType() &&
  9460. DeduceVariableDeclarationType(Var, false, nullptr))
  9461. return;
  9462. // C++11 [class.static.data]p3: A static data member can be declared with
  9463. // the constexpr specifier; if so, its declaration shall specify
  9464. // a brace-or-equal-initializer.
  9465. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  9466. // the definition of a variable [...] or the declaration of a static data
  9467. // member.
  9468. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  9469. !Var->isThisDeclarationADemotedDefinition()) {
  9470. if (Var->isStaticDataMember()) {
  9471. // C++1z removes the relevant rule; the in-class declaration is always
  9472. // a definition there.
  9473. if (!getLangOpts().CPlusPlus1z) {
  9474. Diag(Var->getLocation(),
  9475. diag::err_constexpr_static_mem_var_requires_init)
  9476. << Var->getDeclName();
  9477. Var->setInvalidDecl();
  9478. return;
  9479. }
  9480. } else {
  9481. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  9482. Var->setInvalidDecl();
  9483. return;
  9484. }
  9485. }
  9486. // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
  9487. // definition having the concept specifier is called a variable concept. A
  9488. // concept definition refers to [...] a variable concept and its initializer.
  9489. if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
  9490. if (VTD->isConcept()) {
  9491. Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
  9492. Var->setInvalidDecl();
  9493. return;
  9494. }
  9495. }
  9496. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  9497. // be initialized.
  9498. if (!Var->isInvalidDecl() &&
  9499. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  9500. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  9501. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  9502. Var->setInvalidDecl();
  9503. return;
  9504. }
  9505. switch (Var->isThisDeclarationADefinition()) {
  9506. case VarDecl::Definition:
  9507. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  9508. break;
  9509. // We have an out-of-line definition of a static data member
  9510. // that has an in-class initializer, so we type-check this like
  9511. // a declaration.
  9512. //
  9513. // Fall through
  9514. case VarDecl::DeclarationOnly:
  9515. // It's only a declaration.
  9516. // Block scope. C99 6.7p7: If an identifier for an object is
  9517. // declared with no linkage (C99 6.2.2p6), the type for the
  9518. // object shall be complete.
  9519. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  9520. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  9521. RequireCompleteType(Var->getLocation(), Type,
  9522. diag::err_typecheck_decl_incomplete_type))
  9523. Var->setInvalidDecl();
  9524. // Make sure that the type is not abstract.
  9525. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9526. RequireNonAbstractType(Var->getLocation(), Type,
  9527. diag::err_abstract_type_in_decl,
  9528. AbstractVariableType))
  9529. Var->setInvalidDecl();
  9530. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9531. Var->getStorageClass() == SC_PrivateExtern) {
  9532. Diag(Var->getLocation(), diag::warn_private_extern);
  9533. Diag(Var->getLocation(), diag::note_private_extern);
  9534. }
  9535. return;
  9536. case VarDecl::TentativeDefinition:
  9537. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  9538. // object that has file scope without an initializer, and without a
  9539. // storage-class specifier or with the storage-class specifier "static",
  9540. // constitutes a tentative definition. Note: A tentative definition with
  9541. // external linkage is valid (C99 6.2.2p5).
  9542. if (!Var->isInvalidDecl()) {
  9543. if (const IncompleteArrayType *ArrayT
  9544. = Context.getAsIncompleteArrayType(Type)) {
  9545. if (RequireCompleteType(Var->getLocation(),
  9546. ArrayT->getElementType(),
  9547. diag::err_illegal_decl_array_incomplete_type))
  9548. Var->setInvalidDecl();
  9549. } else if (Var->getStorageClass() == SC_Static) {
  9550. // C99 6.9.2p3: If the declaration of an identifier for an object is
  9551. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  9552. // declared type shall not be an incomplete type.
  9553. // NOTE: code such as the following
  9554. // static struct s;
  9555. // struct s { int a; };
  9556. // is accepted by gcc. Hence here we issue a warning instead of
  9557. // an error and we do not invalidate the static declaration.
  9558. // NOTE: to avoid multiple warnings, only check the first declaration.
  9559. if (Var->isFirstDecl())
  9560. RequireCompleteType(Var->getLocation(), Type,
  9561. diag::ext_typecheck_decl_incomplete_type);
  9562. }
  9563. }
  9564. // Record the tentative definition; we're done.
  9565. if (!Var->isInvalidDecl())
  9566. TentativeDefinitions.push_back(Var);
  9567. return;
  9568. }
  9569. // Provide a specific diagnostic for uninitialized variable
  9570. // definitions with incomplete array type.
  9571. if (Type->isIncompleteArrayType()) {
  9572. Diag(Var->getLocation(),
  9573. diag::err_typecheck_incomplete_array_needs_initializer);
  9574. Var->setInvalidDecl();
  9575. return;
  9576. }
  9577. // Provide a specific diagnostic for uninitialized variable
  9578. // definitions with reference type.
  9579. if (Type->isReferenceType()) {
  9580. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  9581. << Var->getDeclName()
  9582. << SourceRange(Var->getLocation(), Var->getLocation());
  9583. Var->setInvalidDecl();
  9584. return;
  9585. }
  9586. // Do not attempt to type-check the default initializer for a
  9587. // variable with dependent type.
  9588. if (Type->isDependentType())
  9589. return;
  9590. if (Var->isInvalidDecl())
  9591. return;
  9592. if (!Var->hasAttr<AliasAttr>()) {
  9593. if (RequireCompleteType(Var->getLocation(),
  9594. Context.getBaseElementType(Type),
  9595. diag::err_typecheck_decl_incomplete_type)) {
  9596. Var->setInvalidDecl();
  9597. return;
  9598. }
  9599. } else {
  9600. return;
  9601. }
  9602. // The variable can not have an abstract class type.
  9603. if (RequireNonAbstractType(Var->getLocation(), Type,
  9604. diag::err_abstract_type_in_decl,
  9605. AbstractVariableType)) {
  9606. Var->setInvalidDecl();
  9607. return;
  9608. }
  9609. // Check for jumps past the implicit initializer. C++0x
  9610. // clarifies that this applies to a "variable with automatic
  9611. // storage duration", not a "local variable".
  9612. // C++11 [stmt.dcl]p3
  9613. // A program that jumps from a point where a variable with automatic
  9614. // storage duration is not in scope to a point where it is in scope is
  9615. // ill-formed unless the variable has scalar type, class type with a
  9616. // trivial default constructor and a trivial destructor, a cv-qualified
  9617. // version of one of these types, or an array of one of the preceding
  9618. // types and is declared without an initializer.
  9619. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  9620. if (const RecordType *Record
  9621. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  9622. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  9623. // Mark the function for further checking even if the looser rules of
  9624. // C++11 do not require such checks, so that we can diagnose
  9625. // incompatibilities with C++98.
  9626. if (!CXXRecord->isPOD())
  9627. getCurFunction()->setHasBranchProtectedScope();
  9628. }
  9629. }
  9630. // C++03 [dcl.init]p9:
  9631. // If no initializer is specified for an object, and the
  9632. // object is of (possibly cv-qualified) non-POD class type (or
  9633. // array thereof), the object shall be default-initialized; if
  9634. // the object is of const-qualified type, the underlying class
  9635. // type shall have a user-declared default
  9636. // constructor. Otherwise, if no initializer is specified for
  9637. // a non- static object, the object and its subobjects, if
  9638. // any, have an indeterminate initial value); if the object
  9639. // or any of its subobjects are of const-qualified type, the
  9640. // program is ill-formed.
  9641. // C++0x [dcl.init]p11:
  9642. // If no initializer is specified for an object, the object is
  9643. // default-initialized; [...].
  9644. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  9645. InitializationKind Kind
  9646. = InitializationKind::CreateDefault(Var->getLocation());
  9647. InitializationSequence InitSeq(*this, Entity, Kind, None);
  9648. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  9649. if (Init.isInvalid())
  9650. Var->setInvalidDecl();
  9651. else if (Init.get()) {
  9652. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  9653. // This is important for template substitution.
  9654. Var->setInitStyle(VarDecl::CallInit);
  9655. }
  9656. CheckCompleteVariableDeclaration(Var);
  9657. }
  9658. }
  9659. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  9660. // If there is no declaration, there was an error parsing it. Ignore it.
  9661. if (!D)
  9662. return;
  9663. VarDecl *VD = dyn_cast<VarDecl>(D);
  9664. if (!VD) {
  9665. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  9666. D->setInvalidDecl();
  9667. return;
  9668. }
  9669. VD->setCXXForRangeDecl(true);
  9670. // for-range-declaration cannot be given a storage class specifier.
  9671. int Error = -1;
  9672. switch (VD->getStorageClass()) {
  9673. case SC_None:
  9674. break;
  9675. case SC_Extern:
  9676. Error = 0;
  9677. break;
  9678. case SC_Static:
  9679. Error = 1;
  9680. break;
  9681. case SC_PrivateExtern:
  9682. Error = 2;
  9683. break;
  9684. case SC_Auto:
  9685. Error = 3;
  9686. break;
  9687. case SC_Register:
  9688. Error = 4;
  9689. break;
  9690. }
  9691. if (Error != -1) {
  9692. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  9693. << VD->getDeclName() << Error;
  9694. D->setInvalidDecl();
  9695. }
  9696. }
  9697. StmtResult
  9698. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  9699. IdentifierInfo *Ident,
  9700. ParsedAttributes &Attrs,
  9701. SourceLocation AttrEnd) {
  9702. // C++1y [stmt.iter]p1:
  9703. // A range-based for statement of the form
  9704. // for ( for-range-identifier : for-range-initializer ) statement
  9705. // is equivalent to
  9706. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  9707. DeclSpec DS(Attrs.getPool().getFactory());
  9708. const char *PrevSpec;
  9709. unsigned DiagID;
  9710. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  9711. getPrintingPolicy());
  9712. Declarator D(DS, Declarator::ForContext);
  9713. D.SetIdentifier(Ident, IdentLoc);
  9714. D.takeAttributes(Attrs, AttrEnd);
  9715. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  9716. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  9717. EmptyAttrs, IdentLoc);
  9718. Decl *Var = ActOnDeclarator(S, D);
  9719. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  9720. FinalizeDeclaration(Var);
  9721. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  9722. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  9723. }
  9724. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  9725. if (var->isInvalidDecl()) return;
  9726. if (getLangOpts().OpenCL) {
  9727. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  9728. // initialiser
  9729. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  9730. !var->hasInit()) {
  9731. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  9732. << 1 /*Init*/;
  9733. var->setInvalidDecl();
  9734. return;
  9735. }
  9736. }
  9737. // In Objective-C, don't allow jumps past the implicit initialization of a
  9738. // local retaining variable.
  9739. if (getLangOpts().ObjC1 &&
  9740. var->hasLocalStorage()) {
  9741. switch (var->getType().getObjCLifetime()) {
  9742. case Qualifiers::OCL_None:
  9743. case Qualifiers::OCL_ExplicitNone:
  9744. case Qualifiers::OCL_Autoreleasing:
  9745. break;
  9746. case Qualifiers::OCL_Weak:
  9747. case Qualifiers::OCL_Strong:
  9748. getCurFunction()->setHasBranchProtectedScope();
  9749. break;
  9750. }
  9751. }
  9752. // Warn about externally-visible variables being defined without a
  9753. // prior declaration. We only want to do this for global
  9754. // declarations, but we also specifically need to avoid doing it for
  9755. // class members because the linkage of an anonymous class can
  9756. // change if it's later given a typedef name.
  9757. if (var->isThisDeclarationADefinition() &&
  9758. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  9759. var->isExternallyVisible() && var->hasLinkage() &&
  9760. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  9761. var->getLocation())) {
  9762. // Find a previous declaration that's not a definition.
  9763. VarDecl *prev = var->getPreviousDecl();
  9764. while (prev && prev->isThisDeclarationADefinition())
  9765. prev = prev->getPreviousDecl();
  9766. if (!prev)
  9767. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  9768. }
  9769. // Cache the result of checking for constant initialization.
  9770. Optional<bool> CacheHasConstInit;
  9771. const Expr *CacheCulprit;
  9772. auto checkConstInit = [&]() mutable {
  9773. if (!CacheHasConstInit)
  9774. CacheHasConstInit = var->getInit()->isConstantInitializer(
  9775. Context, var->getType()->isReferenceType(), &CacheCulprit);
  9776. return *CacheHasConstInit;
  9777. };
  9778. if (var->getTLSKind() == VarDecl::TLS_Static) {
  9779. if (var->getType().isDestructedType()) {
  9780. // GNU C++98 edits for __thread, [basic.start.term]p3:
  9781. // The type of an object with thread storage duration shall not
  9782. // have a non-trivial destructor.
  9783. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  9784. if (getLangOpts().CPlusPlus11)
  9785. Diag(var->getLocation(), diag::note_use_thread_local);
  9786. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  9787. if (!checkConstInit()) {
  9788. // GNU C++98 edits for __thread, [basic.start.init]p4:
  9789. // An object of thread storage duration shall not require dynamic
  9790. // initialization.
  9791. // FIXME: Need strict checking here.
  9792. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  9793. << CacheCulprit->getSourceRange();
  9794. if (getLangOpts().CPlusPlus11)
  9795. Diag(var->getLocation(), diag::note_use_thread_local);
  9796. }
  9797. }
  9798. }
  9799. // Apply section attributes and pragmas to global variables.
  9800. bool GlobalStorage = var->hasGlobalStorage();
  9801. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  9802. !inTemplateInstantiation()) {
  9803. PragmaStack<StringLiteral *> *Stack = nullptr;
  9804. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  9805. if (var->getType().isConstQualified())
  9806. Stack = &ConstSegStack;
  9807. else if (!var->getInit()) {
  9808. Stack = &BSSSegStack;
  9809. SectionFlags |= ASTContext::PSF_Write;
  9810. } else {
  9811. Stack = &DataSegStack;
  9812. SectionFlags |= ASTContext::PSF_Write;
  9813. }
  9814. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  9815. var->addAttr(SectionAttr::CreateImplicit(
  9816. Context, SectionAttr::Declspec_allocate,
  9817. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  9818. }
  9819. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  9820. if (UnifySection(SA->getName(), SectionFlags, var))
  9821. var->dropAttr<SectionAttr>();
  9822. // Apply the init_seg attribute if this has an initializer. If the
  9823. // initializer turns out to not be dynamic, we'll end up ignoring this
  9824. // attribute.
  9825. if (CurInitSeg && var->getInit())
  9826. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  9827. CurInitSegLoc));
  9828. }
  9829. // All the following checks are C++ only.
  9830. if (!getLangOpts().CPlusPlus) {
  9831. // If this variable must be emitted, add it as an initializer for the
  9832. // current module.
  9833. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9834. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9835. return;
  9836. }
  9837. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  9838. CheckCompleteDecompositionDeclaration(DD);
  9839. QualType type = var->getType();
  9840. if (type->isDependentType()) return;
  9841. // __block variables might require us to capture a copy-initializer.
  9842. if (var->hasAttr<BlocksAttr>()) {
  9843. // It's currently invalid to ever have a __block variable with an
  9844. // array type; should we diagnose that here?
  9845. // Regardless, we don't want to ignore array nesting when
  9846. // constructing this copy.
  9847. if (type->isStructureOrClassType()) {
  9848. EnterExpressionEvaluationContext scope(
  9849. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  9850. SourceLocation poi = var->getLocation();
  9851. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  9852. ExprResult result
  9853. = PerformMoveOrCopyInitialization(
  9854. InitializedEntity::InitializeBlock(poi, type, false),
  9855. var, var->getType(), varRef, /*AllowNRVO=*/true);
  9856. if (!result.isInvalid()) {
  9857. result = MaybeCreateExprWithCleanups(result);
  9858. Expr *init = result.getAs<Expr>();
  9859. Context.setBlockVarCopyInits(var, init);
  9860. }
  9861. }
  9862. }
  9863. Expr *Init = var->getInit();
  9864. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  9865. QualType baseType = Context.getBaseElementType(type);
  9866. if (Init && !Init->isValueDependent()) {
  9867. if (var->isConstexpr()) {
  9868. SmallVector<PartialDiagnosticAt, 8> Notes;
  9869. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  9870. SourceLocation DiagLoc = var->getLocation();
  9871. // If the note doesn't add any useful information other than a source
  9872. // location, fold it into the primary diagnostic.
  9873. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  9874. diag::note_invalid_subexpr_in_const_expr) {
  9875. DiagLoc = Notes[0].first;
  9876. Notes.clear();
  9877. }
  9878. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  9879. << var << Init->getSourceRange();
  9880. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  9881. Diag(Notes[I].first, Notes[I].second);
  9882. }
  9883. } else if (var->isUsableInConstantExpressions(Context)) {
  9884. // Check whether the initializer of a const variable of integral or
  9885. // enumeration type is an ICE now, since we can't tell whether it was
  9886. // initialized by a constant expression if we check later.
  9887. var->checkInitIsICE();
  9888. }
  9889. // Don't emit further diagnostics about constexpr globals since they
  9890. // were just diagnosed.
  9891. if (!var->isConstexpr() && GlobalStorage &&
  9892. var->hasAttr<RequireConstantInitAttr>()) {
  9893. // FIXME: Need strict checking in C++03 here.
  9894. bool DiagErr = getLangOpts().CPlusPlus11
  9895. ? !var->checkInitIsICE() : !checkConstInit();
  9896. if (DiagErr) {
  9897. auto attr = var->getAttr<RequireConstantInitAttr>();
  9898. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  9899. << Init->getSourceRange();
  9900. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  9901. << attr->getRange();
  9902. if (getLangOpts().CPlusPlus11) {
  9903. APValue Value;
  9904. SmallVector<PartialDiagnosticAt, 8> Notes;
  9905. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  9906. for (auto &it : Notes)
  9907. Diag(it.first, it.second);
  9908. } else {
  9909. Diag(CacheCulprit->getExprLoc(),
  9910. diag::note_invalid_subexpr_in_const_expr)
  9911. << CacheCulprit->getSourceRange();
  9912. }
  9913. }
  9914. }
  9915. else if (!var->isConstexpr() && IsGlobal &&
  9916. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  9917. var->getLocation())) {
  9918. // Warn about globals which don't have a constant initializer. Don't
  9919. // warn about globals with a non-trivial destructor because we already
  9920. // warned about them.
  9921. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  9922. if (!(RD && !RD->hasTrivialDestructor())) {
  9923. if (!checkConstInit())
  9924. Diag(var->getLocation(), diag::warn_global_constructor)
  9925. << Init->getSourceRange();
  9926. }
  9927. }
  9928. }
  9929. // Require the destructor.
  9930. if (const RecordType *recordType = baseType->getAs<RecordType>())
  9931. FinalizeVarWithDestructor(var, recordType);
  9932. // If this variable must be emitted, add it as an initializer for the current
  9933. // module.
  9934. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  9935. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  9936. }
  9937. /// \brief Determines if a variable's alignment is dependent.
  9938. static bool hasDependentAlignment(VarDecl *VD) {
  9939. if (VD->getType()->isDependentType())
  9940. return true;
  9941. for (auto *I : VD->specific_attrs<AlignedAttr>())
  9942. if (I->isAlignmentDependent())
  9943. return true;
  9944. return false;
  9945. }
  9946. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  9947. /// any semantic actions necessary after any initializer has been attached.
  9948. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  9949. // Note that we are no longer parsing the initializer for this declaration.
  9950. ParsingInitForAutoVars.erase(ThisDecl);
  9951. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  9952. if (!VD)
  9953. return;
  9954. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  9955. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  9956. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  9957. if (PragmaClangBSSSection.Valid)
  9958. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  9959. PragmaClangBSSSection.SectionName,
  9960. PragmaClangBSSSection.PragmaLocation));
  9961. if (PragmaClangDataSection.Valid)
  9962. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  9963. PragmaClangDataSection.SectionName,
  9964. PragmaClangDataSection.PragmaLocation));
  9965. if (PragmaClangRodataSection.Valid)
  9966. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  9967. PragmaClangRodataSection.SectionName,
  9968. PragmaClangRodataSection.PragmaLocation));
  9969. }
  9970. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  9971. for (auto *BD : DD->bindings()) {
  9972. FinalizeDeclaration(BD);
  9973. }
  9974. }
  9975. checkAttributesAfterMerging(*this, *VD);
  9976. // Perform TLS alignment check here after attributes attached to the variable
  9977. // which may affect the alignment have been processed. Only perform the check
  9978. // if the target has a maximum TLS alignment (zero means no constraints).
  9979. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  9980. // Protect the check so that it's not performed on dependent types and
  9981. // dependent alignments (we can't determine the alignment in that case).
  9982. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  9983. !VD->isInvalidDecl()) {
  9984. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  9985. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  9986. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  9987. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  9988. << (unsigned)MaxAlignChars.getQuantity();
  9989. }
  9990. }
  9991. }
  9992. if (VD->isStaticLocal()) {
  9993. if (FunctionDecl *FD =
  9994. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  9995. // Static locals inherit dll attributes from their function.
  9996. if (Attr *A = getDLLAttr(FD)) {
  9997. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  9998. NewAttr->setInherited(true);
  9999. VD->addAttr(NewAttr);
  10000. }
  10001. // CUDA E.2.9.4: Within the body of a __device__ or __global__
  10002. // function, only __shared__ variables may be declared with
  10003. // static storage class.
  10004. if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
  10005. CUDADiagIfDeviceCode(VD->getLocation(),
  10006. diag::err_device_static_local_var)
  10007. << CurrentCUDATarget())
  10008. VD->setInvalidDecl();
  10009. }
  10010. }
  10011. // Perform check for initializers of device-side global variables.
  10012. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10013. // 7.5). We must also apply the same checks to all __shared__
  10014. // variables whether they are local or not. CUDA also allows
  10015. // constant initializers for __constant__ and __device__ variables.
  10016. if (getLangOpts().CUDA) {
  10017. const Expr *Init = VD->getInit();
  10018. if (Init && VD->hasGlobalStorage()) {
  10019. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  10020. VD->hasAttr<CUDASharedAttr>()) {
  10021. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  10022. bool AllowedInit = false;
  10023. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  10024. AllowedInit =
  10025. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  10026. // We'll allow constant initializers even if it's a non-empty
  10027. // constructor according to CUDA rules. This deviates from NVCC,
  10028. // but allows us to handle things like constexpr constructors.
  10029. if (!AllowedInit &&
  10030. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10031. AllowedInit = VD->getInit()->isConstantInitializer(
  10032. Context, VD->getType()->isReferenceType());
  10033. // Also make sure that destructor, if there is one, is empty.
  10034. if (AllowedInit)
  10035. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  10036. AllowedInit =
  10037. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  10038. if (!AllowedInit) {
  10039. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  10040. ? diag::err_shared_var_init
  10041. : diag::err_dynamic_var_init)
  10042. << Init->getSourceRange();
  10043. VD->setInvalidDecl();
  10044. }
  10045. } else {
  10046. // This is a host-side global variable. Check that the initializer is
  10047. // callable from the host side.
  10048. const FunctionDecl *InitFn = nullptr;
  10049. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  10050. InitFn = CE->getConstructor();
  10051. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  10052. InitFn = CE->getDirectCallee();
  10053. }
  10054. if (InitFn) {
  10055. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  10056. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  10057. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  10058. << InitFnTarget << InitFn;
  10059. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  10060. VD->setInvalidDecl();
  10061. }
  10062. }
  10063. }
  10064. }
  10065. }
  10066. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10067. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10068. // Imported static data members cannot be defined out-of-line.
  10069. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10070. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10071. VD->isThisDeclarationADefinition()) {
  10072. // We allow definitions of dllimport class template static data members
  10073. // with a warning.
  10074. CXXRecordDecl *Context =
  10075. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10076. bool IsClassTemplateMember =
  10077. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10078. Context->getDescribedClassTemplate();
  10079. Diag(VD->getLocation(),
  10080. IsClassTemplateMember
  10081. ? diag::warn_attribute_dllimport_static_field_definition
  10082. : diag::err_attribute_dllimport_static_field_definition);
  10083. Diag(IA->getLocation(), diag::note_attribute);
  10084. if (!IsClassTemplateMember)
  10085. VD->setInvalidDecl();
  10086. }
  10087. }
  10088. // dllimport/dllexport variables cannot be thread local, their TLS index
  10089. // isn't exported with the variable.
  10090. if (DLLAttr && VD->getTLSKind()) {
  10091. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10092. if (F && getDLLAttr(F)) {
  10093. assert(VD->isStaticLocal());
  10094. // But if this is a static local in a dlimport/dllexport function, the
  10095. // function will never be inlined, which means the var would never be
  10096. // imported, so having it marked import/export is safe.
  10097. } else {
  10098. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10099. << DLLAttr;
  10100. VD->setInvalidDecl();
  10101. }
  10102. }
  10103. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10104. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10105. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10106. VD->dropAttr<UsedAttr>();
  10107. }
  10108. }
  10109. const DeclContext *DC = VD->getDeclContext();
  10110. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10111. // member, set the visibility of this variable.
  10112. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10113. AddPushedVisibilityAttribute(VD);
  10114. // FIXME: Warn on unused var template partial specializations.
  10115. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10116. MarkUnusedFileScopedDecl(VD);
  10117. // Now we have parsed the initializer and can update the table of magic
  10118. // tag values.
  10119. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10120. !VD->getType()->isIntegralOrEnumerationType())
  10121. return;
  10122. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10123. const Expr *MagicValueExpr = VD->getInit();
  10124. if (!MagicValueExpr) {
  10125. continue;
  10126. }
  10127. llvm::APSInt MagicValueInt;
  10128. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10129. Diag(I->getRange().getBegin(),
  10130. diag::err_type_tag_for_datatype_not_ice)
  10131. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10132. continue;
  10133. }
  10134. if (MagicValueInt.getActiveBits() > 64) {
  10135. Diag(I->getRange().getBegin(),
  10136. diag::err_type_tag_for_datatype_too_large)
  10137. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10138. continue;
  10139. }
  10140. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10141. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10142. MagicValue,
  10143. I->getMatchingCType(),
  10144. I->getLayoutCompatible(),
  10145. I->getMustBeNull());
  10146. }
  10147. }
  10148. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10149. auto *VD = dyn_cast<VarDecl>(DD);
  10150. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10151. }
  10152. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10153. ArrayRef<Decl *> Group) {
  10154. SmallVector<Decl*, 8> Decls;
  10155. if (DS.isTypeSpecOwned())
  10156. Decls.push_back(DS.getRepAsDecl());
  10157. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  10158. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  10159. bool DiagnosedMultipleDecomps = false;
  10160. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  10161. bool DiagnosedNonDeducedAuto = false;
  10162. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10163. if (Decl *D = Group[i]) {
  10164. // For declarators, there are some additional syntactic-ish checks we need
  10165. // to perform.
  10166. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  10167. if (!FirstDeclaratorInGroup)
  10168. FirstDeclaratorInGroup = DD;
  10169. if (!FirstDecompDeclaratorInGroup)
  10170. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  10171. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  10172. !hasDeducedAuto(DD))
  10173. FirstNonDeducedAutoInGroup = DD;
  10174. if (FirstDeclaratorInGroup != DD) {
  10175. // A decomposition declaration cannot be combined with any other
  10176. // declaration in the same group.
  10177. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  10178. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  10179. diag::err_decomp_decl_not_alone)
  10180. << FirstDeclaratorInGroup->getSourceRange()
  10181. << DD->getSourceRange();
  10182. DiagnosedMultipleDecomps = true;
  10183. }
  10184. // A declarator that uses 'auto' in any way other than to declare a
  10185. // variable with a deduced type cannot be combined with any other
  10186. // declarator in the same group.
  10187. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  10188. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  10189. diag::err_auto_non_deduced_not_alone)
  10190. << FirstNonDeducedAutoInGroup->getType()
  10191. ->hasAutoForTrailingReturnType()
  10192. << FirstDeclaratorInGroup->getSourceRange()
  10193. << DD->getSourceRange();
  10194. DiagnosedNonDeducedAuto = true;
  10195. }
  10196. }
  10197. }
  10198. Decls.push_back(D);
  10199. }
  10200. }
  10201. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  10202. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  10203. handleTagNumbering(Tag, S);
  10204. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  10205. getLangOpts().CPlusPlus)
  10206. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  10207. }
  10208. }
  10209. return BuildDeclaratorGroup(Decls);
  10210. }
  10211. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  10212. /// group, performing any necessary semantic checking.
  10213. Sema::DeclGroupPtrTy
  10214. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  10215. // C++14 [dcl.spec.auto]p7: (DR1347)
  10216. // If the type that replaces the placeholder type is not the same in each
  10217. // deduction, the program is ill-formed.
  10218. if (Group.size() > 1) {
  10219. QualType Deduced;
  10220. VarDecl *DeducedDecl = nullptr;
  10221. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10222. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  10223. if (!D || D->isInvalidDecl())
  10224. break;
  10225. DeducedType *DT = D->getType()->getContainedDeducedType();
  10226. if (!DT || DT->getDeducedType().isNull())
  10227. continue;
  10228. if (Deduced.isNull()) {
  10229. Deduced = DT->getDeducedType();
  10230. DeducedDecl = D;
  10231. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  10232. auto *AT = dyn_cast<AutoType>(DT);
  10233. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  10234. diag::err_auto_different_deductions)
  10235. << (AT ? (unsigned)AT->getKeyword() : 3)
  10236. << Deduced << DeducedDecl->getDeclName()
  10237. << DT->getDeducedType() << D->getDeclName()
  10238. << DeducedDecl->getInit()->getSourceRange()
  10239. << D->getInit()->getSourceRange();
  10240. D->setInvalidDecl();
  10241. break;
  10242. }
  10243. }
  10244. }
  10245. ActOnDocumentableDecls(Group);
  10246. return DeclGroupPtrTy::make(
  10247. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  10248. }
  10249. void Sema::ActOnDocumentableDecl(Decl *D) {
  10250. ActOnDocumentableDecls(D);
  10251. }
  10252. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10253. // Don't parse the comment if Doxygen diagnostics are ignored.
  10254. if (Group.empty() || !Group[0])
  10255. return;
  10256. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10257. Group[0]->getLocation()) &&
  10258. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10259. Group[0]->getLocation()))
  10260. return;
  10261. if (Group.size() >= 2) {
  10262. // This is a decl group. Normally it will contain only declarations
  10263. // produced from declarator list. But in case we have any definitions or
  10264. // additional declaration references:
  10265. // 'typedef struct S {} S;'
  10266. // 'typedef struct S *S;'
  10267. // 'struct S *pS;'
  10268. // FinalizeDeclaratorGroup adds these as separate declarations.
  10269. Decl *MaybeTagDecl = Group[0];
  10270. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10271. Group = Group.slice(1);
  10272. }
  10273. }
  10274. // See if there are any new comments that are not attached to a decl.
  10275. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10276. if (!Comments.empty() &&
  10277. !Comments.back()->isAttached()) {
  10278. // There is at least one comment that not attached to a decl.
  10279. // Maybe it should be attached to one of these decls?
  10280. //
  10281. // Note that this way we pick up not only comments that precede the
  10282. // declaration, but also comments that *follow* the declaration -- thanks to
  10283. // the lookahead in the lexer: we've consumed the semicolon and looked
  10284. // ahead through comments.
  10285. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10286. Context.getCommentForDecl(Group[i], &PP);
  10287. }
  10288. }
  10289. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10290. /// to introduce parameters into function prototype scope.
  10291. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10292. const DeclSpec &DS = D.getDeclSpec();
  10293. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10294. // C++03 [dcl.stc]p2 also permits 'auto'.
  10295. StorageClass SC = SC_None;
  10296. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10297. SC = SC_Register;
  10298. } else if (getLangOpts().CPlusPlus &&
  10299. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  10300. SC = SC_Auto;
  10301. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  10302. Diag(DS.getStorageClassSpecLoc(),
  10303. diag::err_invalid_storage_class_in_func_decl);
  10304. D.getMutableDeclSpec().ClearStorageClassSpecs();
  10305. }
  10306. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  10307. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  10308. << DeclSpec::getSpecifierName(TSCS);
  10309. if (DS.isInlineSpecified())
  10310. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  10311. << getLangOpts().CPlusPlus1z;
  10312. if (DS.isConstexprSpecified())
  10313. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  10314. << 0;
  10315. if (DS.isConceptSpecified())
  10316. Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
  10317. DiagnoseFunctionSpecifiers(DS);
  10318. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10319. QualType parmDeclType = TInfo->getType();
  10320. if (getLangOpts().CPlusPlus) {
  10321. // Check that there are no default arguments inside the type of this
  10322. // parameter.
  10323. CheckExtraCXXDefaultArguments(D);
  10324. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  10325. if (D.getCXXScopeSpec().isSet()) {
  10326. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  10327. << D.getCXXScopeSpec().getRange();
  10328. D.getCXXScopeSpec().clear();
  10329. }
  10330. }
  10331. // Ensure we have a valid name
  10332. IdentifierInfo *II = nullptr;
  10333. if (D.hasName()) {
  10334. II = D.getIdentifier();
  10335. if (!II) {
  10336. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  10337. << GetNameForDeclarator(D).getName();
  10338. D.setInvalidType(true);
  10339. }
  10340. }
  10341. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  10342. if (II) {
  10343. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  10344. ForRedeclaration);
  10345. LookupName(R, S);
  10346. if (R.isSingleResult()) {
  10347. NamedDecl *PrevDecl = R.getFoundDecl();
  10348. if (PrevDecl->isTemplateParameter()) {
  10349. // Maybe we will complain about the shadowed template parameter.
  10350. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10351. // Just pretend that we didn't see the previous declaration.
  10352. PrevDecl = nullptr;
  10353. } else if (S->isDeclScope(PrevDecl)) {
  10354. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  10355. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10356. // Recover by removing the name
  10357. II = nullptr;
  10358. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  10359. D.setInvalidType(true);
  10360. }
  10361. }
  10362. }
  10363. // Temporarily put parameter variables in the translation unit, not
  10364. // the enclosing context. This prevents them from accidentally
  10365. // looking like class members in C++.
  10366. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  10367. D.getLocStart(),
  10368. D.getIdentifierLoc(), II,
  10369. parmDeclType, TInfo,
  10370. SC);
  10371. if (D.isInvalidType())
  10372. New->setInvalidDecl();
  10373. assert(S->isFunctionPrototypeScope());
  10374. assert(S->getFunctionPrototypeDepth() >= 1);
  10375. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  10376. S->getNextFunctionPrototypeIndex());
  10377. // Add the parameter declaration into this scope.
  10378. S->AddDecl(New);
  10379. if (II)
  10380. IdResolver.AddDecl(New);
  10381. ProcessDeclAttributes(S, New, D);
  10382. if (D.getDeclSpec().isModulePrivateSpecified())
  10383. Diag(New->getLocation(), diag::err_module_private_local)
  10384. << 1 << New->getDeclName()
  10385. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  10386. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  10387. if (New->hasAttr<BlocksAttr>()) {
  10388. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  10389. }
  10390. return New;
  10391. }
  10392. /// \brief Synthesizes a variable for a parameter arising from a
  10393. /// typedef.
  10394. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  10395. SourceLocation Loc,
  10396. QualType T) {
  10397. /* FIXME: setting StartLoc == Loc.
  10398. Would it be worth to modify callers so as to provide proper source
  10399. location for the unnamed parameters, embedding the parameter's type? */
  10400. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  10401. T, Context.getTrivialTypeSourceInfo(T, Loc),
  10402. SC_None, nullptr);
  10403. Param->setImplicit();
  10404. return Param;
  10405. }
  10406. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  10407. // Don't diagnose unused-parameter errors in template instantiations; we
  10408. // will already have done so in the template itself.
  10409. if (inTemplateInstantiation())
  10410. return;
  10411. for (const ParmVarDecl *Parameter : Parameters) {
  10412. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  10413. !Parameter->hasAttr<UnusedAttr>()) {
  10414. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  10415. << Parameter->getDeclName();
  10416. }
  10417. }
  10418. }
  10419. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  10420. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  10421. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  10422. return;
  10423. // Warn if the return value is pass-by-value and larger than the specified
  10424. // threshold.
  10425. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  10426. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  10427. if (Size > LangOpts.NumLargeByValueCopy)
  10428. Diag(D->getLocation(), diag::warn_return_value_size)
  10429. << D->getDeclName() << Size;
  10430. }
  10431. // Warn if any parameter is pass-by-value and larger than the specified
  10432. // threshold.
  10433. for (const ParmVarDecl *Parameter : Parameters) {
  10434. QualType T = Parameter->getType();
  10435. if (T->isDependentType() || !T.isPODType(Context))
  10436. continue;
  10437. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  10438. if (Size > LangOpts.NumLargeByValueCopy)
  10439. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  10440. << Parameter->getDeclName() << Size;
  10441. }
  10442. }
  10443. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  10444. SourceLocation NameLoc, IdentifierInfo *Name,
  10445. QualType T, TypeSourceInfo *TSInfo,
  10446. StorageClass SC) {
  10447. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  10448. if (getLangOpts().ObjCAutoRefCount &&
  10449. T.getObjCLifetime() == Qualifiers::OCL_None &&
  10450. T->isObjCLifetimeType()) {
  10451. Qualifiers::ObjCLifetime lifetime;
  10452. // Special cases for arrays:
  10453. // - if it's const, use __unsafe_unretained
  10454. // - otherwise, it's an error
  10455. if (T->isArrayType()) {
  10456. if (!T.isConstQualified()) {
  10457. DelayedDiagnostics.add(
  10458. sema::DelayedDiagnostic::makeForbiddenType(
  10459. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  10460. }
  10461. lifetime = Qualifiers::OCL_ExplicitNone;
  10462. } else {
  10463. lifetime = T->getObjCARCImplicitLifetime();
  10464. }
  10465. T = Context.getLifetimeQualifiedType(T, lifetime);
  10466. }
  10467. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  10468. Context.getAdjustedParameterType(T),
  10469. TSInfo, SC, nullptr);
  10470. // Parameters can not be abstract class types.
  10471. // For record types, this is done by the AbstractClassUsageDiagnoser once
  10472. // the class has been completely parsed.
  10473. if (!CurContext->isRecord() &&
  10474. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  10475. AbstractParamType))
  10476. New->setInvalidDecl();
  10477. // Parameter declarators cannot be interface types. All ObjC objects are
  10478. // passed by reference.
  10479. if (T->isObjCObjectType()) {
  10480. SourceLocation TypeEndLoc =
  10481. getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
  10482. Diag(NameLoc,
  10483. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  10484. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  10485. T = Context.getObjCObjectPointerType(T);
  10486. New->setType(T);
  10487. }
  10488. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  10489. // duration shall not be qualified by an address-space qualifier."
  10490. // Since all parameters have automatic store duration, they can not have
  10491. // an address space.
  10492. if (T.getAddressSpace() != 0) {
  10493. // OpenCL allows function arguments declared to be an array of a type
  10494. // to be qualified with an address space.
  10495. if (!(getLangOpts().OpenCL && T->isArrayType())) {
  10496. Diag(NameLoc, diag::err_arg_with_address_space);
  10497. New->setInvalidDecl();
  10498. }
  10499. }
  10500. return New;
  10501. }
  10502. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  10503. SourceLocation LocAfterDecls) {
  10504. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  10505. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  10506. // for a K&R function.
  10507. if (!FTI.hasPrototype) {
  10508. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  10509. --i;
  10510. if (FTI.Params[i].Param == nullptr) {
  10511. SmallString<256> Code;
  10512. llvm::raw_svector_ostream(Code)
  10513. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  10514. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  10515. << FTI.Params[i].Ident
  10516. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  10517. // Implicitly declare the argument as type 'int' for lack of a better
  10518. // type.
  10519. AttributeFactory attrs;
  10520. DeclSpec DS(attrs);
  10521. const char* PrevSpec; // unused
  10522. unsigned DiagID; // unused
  10523. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  10524. DiagID, Context.getPrintingPolicy());
  10525. // Use the identifier location for the type source range.
  10526. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  10527. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  10528. Declarator ParamD(DS, Declarator::KNRTypeListContext);
  10529. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  10530. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  10531. }
  10532. }
  10533. }
  10534. }
  10535. Decl *
  10536. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  10537. MultiTemplateParamsArg TemplateParameterLists,
  10538. SkipBodyInfo *SkipBody) {
  10539. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  10540. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  10541. Scope *ParentScope = FnBodyScope->getParent();
  10542. D.setFunctionDefinitionKind(FDK_Definition);
  10543. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  10544. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  10545. }
  10546. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  10547. Consumer.HandleInlineFunctionDefinition(D);
  10548. }
  10549. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  10550. const FunctionDecl*& PossibleZeroParamPrototype) {
  10551. // Don't warn about invalid declarations.
  10552. if (FD->isInvalidDecl())
  10553. return false;
  10554. // Or declarations that aren't global.
  10555. if (!FD->isGlobal())
  10556. return false;
  10557. // Don't warn about C++ member functions.
  10558. if (isa<CXXMethodDecl>(FD))
  10559. return false;
  10560. // Don't warn about 'main'.
  10561. if (FD->isMain())
  10562. return false;
  10563. // Don't warn about inline functions.
  10564. if (FD->isInlined())
  10565. return false;
  10566. // Don't warn about function templates.
  10567. if (FD->getDescribedFunctionTemplate())
  10568. return false;
  10569. // Don't warn about function template specializations.
  10570. if (FD->isFunctionTemplateSpecialization())
  10571. return false;
  10572. // Don't warn for OpenCL kernels.
  10573. if (FD->hasAttr<OpenCLKernelAttr>())
  10574. return false;
  10575. // Don't warn on explicitly deleted functions.
  10576. if (FD->isDeleted())
  10577. return false;
  10578. bool MissingPrototype = true;
  10579. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  10580. Prev; Prev = Prev->getPreviousDecl()) {
  10581. // Ignore any declarations that occur in function or method
  10582. // scope, because they aren't visible from the header.
  10583. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  10584. continue;
  10585. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  10586. if (FD->getNumParams() == 0)
  10587. PossibleZeroParamPrototype = Prev;
  10588. break;
  10589. }
  10590. return MissingPrototype;
  10591. }
  10592. void
  10593. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  10594. const FunctionDecl *EffectiveDefinition,
  10595. SkipBodyInfo *SkipBody) {
  10596. const FunctionDecl *Definition = EffectiveDefinition;
  10597. if (!Definition)
  10598. if (!FD->isDefined(Definition))
  10599. return;
  10600. if (canRedefineFunction(Definition, getLangOpts()))
  10601. return;
  10602. // Don't emit an error when this is redefinition of a typo-corrected
  10603. // definition.
  10604. if (TypoCorrectedFunctionDefinitions.count(Definition))
  10605. return;
  10606. // If we don't have a visible definition of the function, and it's inline or
  10607. // a template, skip the new definition.
  10608. if (SkipBody && !hasVisibleDefinition(Definition) &&
  10609. (Definition->getFormalLinkage() == InternalLinkage ||
  10610. Definition->isInlined() ||
  10611. Definition->getDescribedFunctionTemplate() ||
  10612. Definition->getNumTemplateParameterLists())) {
  10613. SkipBody->ShouldSkip = true;
  10614. if (auto *TD = Definition->getDescribedFunctionTemplate())
  10615. makeMergedDefinitionVisible(TD);
  10616. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  10617. return;
  10618. }
  10619. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  10620. Definition->getStorageClass() == SC_Extern)
  10621. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  10622. << FD->getDeclName() << getLangOpts().CPlusPlus;
  10623. else
  10624. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  10625. Diag(Definition->getLocation(), diag::note_previous_definition);
  10626. FD->setInvalidDecl();
  10627. }
  10628. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  10629. Sema &S) {
  10630. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  10631. LambdaScopeInfo *LSI = S.PushLambdaScope();
  10632. LSI->CallOperator = CallOperator;
  10633. LSI->Lambda = LambdaClass;
  10634. LSI->ReturnType = CallOperator->getReturnType();
  10635. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  10636. if (LCD == LCD_None)
  10637. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  10638. else if (LCD == LCD_ByCopy)
  10639. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  10640. else if (LCD == LCD_ByRef)
  10641. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  10642. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  10643. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  10644. LSI->Mutable = !CallOperator->isConst();
  10645. // Add the captures to the LSI so they can be noted as already
  10646. // captured within tryCaptureVar.
  10647. auto I = LambdaClass->field_begin();
  10648. for (const auto &C : LambdaClass->captures()) {
  10649. if (C.capturesVariable()) {
  10650. VarDecl *VD = C.getCapturedVar();
  10651. if (VD->isInitCapture())
  10652. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  10653. QualType CaptureType = VD->getType();
  10654. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  10655. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  10656. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  10657. /*EllipsisLoc*/C.isPackExpansion()
  10658. ? C.getEllipsisLoc() : SourceLocation(),
  10659. CaptureType, /*Expr*/ nullptr);
  10660. } else if (C.capturesThis()) {
  10661. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  10662. /*Expr*/ nullptr,
  10663. C.getCaptureKind() == LCK_StarThis);
  10664. } else {
  10665. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  10666. }
  10667. ++I;
  10668. }
  10669. }
  10670. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  10671. SkipBodyInfo *SkipBody) {
  10672. if (!D)
  10673. return D;
  10674. FunctionDecl *FD = nullptr;
  10675. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  10676. FD = FunTmpl->getTemplatedDecl();
  10677. else
  10678. FD = cast<FunctionDecl>(D);
  10679. // Check for defining attributes before the check for redefinition.
  10680. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  10681. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  10682. FD->dropAttr<AliasAttr>();
  10683. FD->setInvalidDecl();
  10684. }
  10685. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  10686. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  10687. FD->dropAttr<IFuncAttr>();
  10688. FD->setInvalidDecl();
  10689. }
  10690. // See if this is a redefinition. If 'will have body' is already set, then
  10691. // these checks were already performed when it was set.
  10692. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  10693. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  10694. // If we're skipping the body, we're done. Don't enter the scope.
  10695. if (SkipBody && SkipBody->ShouldSkip)
  10696. return D;
  10697. }
  10698. // Mark this function as "will have a body eventually". This lets users to
  10699. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  10700. // this function.
  10701. FD->setWillHaveBody();
  10702. // If we are instantiating a generic lambda call operator, push
  10703. // a LambdaScopeInfo onto the function stack. But use the information
  10704. // that's already been calculated (ActOnLambdaExpr) to prime the current
  10705. // LambdaScopeInfo.
  10706. // When the template operator is being specialized, the LambdaScopeInfo,
  10707. // has to be properly restored so that tryCaptureVariable doesn't try
  10708. // and capture any new variables. In addition when calculating potential
  10709. // captures during transformation of nested lambdas, it is necessary to
  10710. // have the LSI properly restored.
  10711. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  10712. assert(inTemplateInstantiation() &&
  10713. "There should be an active template instantiation on the stack "
  10714. "when instantiating a generic lambda!");
  10715. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  10716. } else {
  10717. // Enter a new function scope
  10718. PushFunctionScope();
  10719. }
  10720. // Builtin functions cannot be defined.
  10721. if (unsigned BuiltinID = FD->getBuiltinID()) {
  10722. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  10723. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  10724. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  10725. FD->setInvalidDecl();
  10726. }
  10727. }
  10728. // The return type of a function definition must be complete
  10729. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  10730. QualType ResultType = FD->getReturnType();
  10731. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  10732. !FD->isInvalidDecl() &&
  10733. RequireCompleteType(FD->getLocation(), ResultType,
  10734. diag::err_func_def_incomplete_result))
  10735. FD->setInvalidDecl();
  10736. if (FnBodyScope)
  10737. PushDeclContext(FnBodyScope, FD);
  10738. // Check the validity of our function parameters
  10739. CheckParmsForFunctionDef(FD->parameters(),
  10740. /*CheckParameterNames=*/true);
  10741. // Add non-parameter declarations already in the function to the current
  10742. // scope.
  10743. if (FnBodyScope) {
  10744. for (Decl *NPD : FD->decls()) {
  10745. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  10746. if (!NonParmDecl)
  10747. continue;
  10748. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  10749. "parameters should not be in newly created FD yet");
  10750. // If the decl has a name, make it accessible in the current scope.
  10751. if (NonParmDecl->getDeclName())
  10752. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  10753. // Similarly, dive into enums and fish their constants out, making them
  10754. // accessible in this scope.
  10755. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  10756. for (auto *EI : ED->enumerators())
  10757. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  10758. }
  10759. }
  10760. }
  10761. // Introduce our parameters into the function scope
  10762. for (auto Param : FD->parameters()) {
  10763. Param->setOwningFunction(FD);
  10764. // If this has an identifier, add it to the scope stack.
  10765. if (Param->getIdentifier() && FnBodyScope) {
  10766. CheckShadow(FnBodyScope, Param);
  10767. PushOnScopeChains(Param, FnBodyScope);
  10768. }
  10769. }
  10770. // Ensure that the function's exception specification is instantiated.
  10771. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  10772. ResolveExceptionSpec(D->getLocation(), FPT);
  10773. // dllimport cannot be applied to non-inline function definitions.
  10774. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  10775. !FD->isTemplateInstantiation()) {
  10776. assert(!FD->hasAttr<DLLExportAttr>());
  10777. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  10778. FD->setInvalidDecl();
  10779. return D;
  10780. }
  10781. // We want to attach documentation to original Decl (which might be
  10782. // a function template).
  10783. ActOnDocumentableDecl(D);
  10784. if (getCurLexicalContext()->isObjCContainer() &&
  10785. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  10786. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  10787. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  10788. return D;
  10789. }
  10790. /// \brief Given the set of return statements within a function body,
  10791. /// compute the variables that are subject to the named return value
  10792. /// optimization.
  10793. ///
  10794. /// Each of the variables that is subject to the named return value
  10795. /// optimization will be marked as NRVO variables in the AST, and any
  10796. /// return statement that has a marked NRVO variable as its NRVO candidate can
  10797. /// use the named return value optimization.
  10798. ///
  10799. /// This function applies a very simplistic algorithm for NRVO: if every return
  10800. /// statement in the scope of a variable has the same NRVO candidate, that
  10801. /// candidate is an NRVO variable.
  10802. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  10803. ReturnStmt **Returns = Scope->Returns.data();
  10804. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  10805. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  10806. if (!NRVOCandidate->isNRVOVariable())
  10807. Returns[I]->setNRVOCandidate(nullptr);
  10808. }
  10809. }
  10810. }
  10811. bool Sema::canDelayFunctionBody(const Declarator &D) {
  10812. // We can't delay parsing the body of a constexpr function template (yet).
  10813. if (D.getDeclSpec().isConstexprSpecified())
  10814. return false;
  10815. // We can't delay parsing the body of a function template with a deduced
  10816. // return type (yet).
  10817. if (D.getDeclSpec().hasAutoTypeSpec()) {
  10818. // If the placeholder introduces a non-deduced trailing return type,
  10819. // we can still delay parsing it.
  10820. if (D.getNumTypeObjects()) {
  10821. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  10822. if (Outer.Kind == DeclaratorChunk::Function &&
  10823. Outer.Fun.hasTrailingReturnType()) {
  10824. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  10825. return Ty.isNull() || !Ty->isUndeducedType();
  10826. }
  10827. }
  10828. return false;
  10829. }
  10830. return true;
  10831. }
  10832. bool Sema::canSkipFunctionBody(Decl *D) {
  10833. // We cannot skip the body of a function (or function template) which is
  10834. // constexpr, since we may need to evaluate its body in order to parse the
  10835. // rest of the file.
  10836. // We cannot skip the body of a function with an undeduced return type,
  10837. // because any callers of that function need to know the type.
  10838. if (const FunctionDecl *FD = D->getAsFunction())
  10839. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  10840. return false;
  10841. return Consumer.shouldSkipFunctionBody(D);
  10842. }
  10843. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  10844. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
  10845. FD->setHasSkippedBody();
  10846. else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
  10847. MD->setHasSkippedBody();
  10848. return Decl;
  10849. }
  10850. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  10851. return ActOnFinishFunctionBody(D, BodyArg, false);
  10852. }
  10853. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  10854. bool IsInstantiation) {
  10855. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  10856. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  10857. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  10858. if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
  10859. CheckCompletedCoroutineBody(FD, Body);
  10860. if (FD) {
  10861. FD->setBody(Body);
  10862. FD->setWillHaveBody(false);
  10863. if (getLangOpts().CPlusPlus14) {
  10864. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  10865. FD->getReturnType()->isUndeducedType()) {
  10866. // If the function has a deduced result type but contains no 'return'
  10867. // statements, the result type as written must be exactly 'auto', and
  10868. // the deduced result type is 'void'.
  10869. if (!FD->getReturnType()->getAs<AutoType>()) {
  10870. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  10871. << FD->getReturnType();
  10872. FD->setInvalidDecl();
  10873. } else {
  10874. // Substitute 'void' for the 'auto' in the type.
  10875. TypeLoc ResultType = getReturnTypeLoc(FD);
  10876. Context.adjustDeducedFunctionResultType(
  10877. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  10878. }
  10879. }
  10880. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  10881. // In C++11, we don't use 'auto' deduction rules for lambda call
  10882. // operators because we don't support return type deduction.
  10883. auto *LSI = getCurLambda();
  10884. if (LSI->HasImplicitReturnType) {
  10885. deduceClosureReturnType(*LSI);
  10886. // C++11 [expr.prim.lambda]p4:
  10887. // [...] if there are no return statements in the compound-statement
  10888. // [the deduced type is] the type void
  10889. QualType RetType =
  10890. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  10891. // Update the return type to the deduced type.
  10892. const FunctionProtoType *Proto =
  10893. FD->getType()->getAs<FunctionProtoType>();
  10894. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  10895. Proto->getExtProtoInfo()));
  10896. }
  10897. }
  10898. // The only way to be included in UndefinedButUsed is if there is an
  10899. // ODR use before the definition. Avoid the expensive map lookup if this
  10900. // is the first declaration.
  10901. if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
  10902. if (!FD->isExternallyVisible())
  10903. UndefinedButUsed.erase(FD);
  10904. else if (FD->isInlined() &&
  10905. !LangOpts.GNUInline &&
  10906. (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
  10907. UndefinedButUsed.erase(FD);
  10908. }
  10909. // If the function implicitly returns zero (like 'main') or is naked,
  10910. // don't complain about missing return statements.
  10911. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  10912. WP.disableCheckFallThrough();
  10913. // MSVC permits the use of pure specifier (=0) on function definition,
  10914. // defined at class scope, warn about this non-standard construct.
  10915. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  10916. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  10917. if (!FD->isInvalidDecl()) {
  10918. // Don't diagnose unused parameters of defaulted or deleted functions.
  10919. if (!FD->isDeleted() && !FD->isDefaulted())
  10920. DiagnoseUnusedParameters(FD->parameters());
  10921. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  10922. FD->getReturnType(), FD);
  10923. // If this is a structor, we need a vtable.
  10924. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  10925. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  10926. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  10927. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  10928. // Try to apply the named return value optimization. We have to check
  10929. // if we can do this here because lambdas keep return statements around
  10930. // to deduce an implicit return type.
  10931. if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
  10932. !FD->isDependentContext())
  10933. computeNRVO(Body, getCurFunction());
  10934. }
  10935. // GNU warning -Wmissing-prototypes:
  10936. // Warn if a global function is defined without a previous
  10937. // prototype declaration. This warning is issued even if the
  10938. // definition itself provides a prototype. The aim is to detect
  10939. // global functions that fail to be declared in header files.
  10940. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  10941. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  10942. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  10943. if (PossibleZeroParamPrototype) {
  10944. // We found a declaration that is not a prototype,
  10945. // but that could be a zero-parameter prototype
  10946. if (TypeSourceInfo *TI =
  10947. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  10948. TypeLoc TL = TI->getTypeLoc();
  10949. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  10950. Diag(PossibleZeroParamPrototype->getLocation(),
  10951. diag::note_declaration_not_a_prototype)
  10952. << PossibleZeroParamPrototype
  10953. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  10954. }
  10955. }
  10956. // GNU warning -Wstrict-prototypes
  10957. // Warn if K&R function is defined without a previous declaration.
  10958. // This warning is issued only if the definition itself does not provide
  10959. // a prototype. Only K&R definitions do not provide a prototype.
  10960. // An empty list in a function declarator that is part of a definition
  10961. // of that function specifies that the function has no parameters
  10962. // (C99 6.7.5.3p14)
  10963. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  10964. !LangOpts.CPlusPlus) {
  10965. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  10966. TypeLoc TL = TI->getTypeLoc();
  10967. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  10968. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  10969. }
  10970. }
  10971. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  10972. const CXXMethodDecl *KeyFunction;
  10973. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  10974. MD->isVirtual() &&
  10975. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  10976. MD == KeyFunction->getCanonicalDecl()) {
  10977. // Update the key-function state if necessary for this ABI.
  10978. if (FD->isInlined() &&
  10979. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  10980. Context.setNonKeyFunction(MD);
  10981. // If the newly-chosen key function is already defined, then we
  10982. // need to mark the vtable as used retroactively.
  10983. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  10984. const FunctionDecl *Definition;
  10985. if (KeyFunction && KeyFunction->isDefined(Definition))
  10986. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  10987. } else {
  10988. // We just defined they key function; mark the vtable as used.
  10989. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  10990. }
  10991. }
  10992. }
  10993. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  10994. "Function parsing confused");
  10995. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  10996. assert(MD == getCurMethodDecl() && "Method parsing confused");
  10997. MD->setBody(Body);
  10998. if (!MD->isInvalidDecl()) {
  10999. DiagnoseUnusedParameters(MD->parameters());
  11000. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11001. MD->getReturnType(), MD);
  11002. if (Body)
  11003. computeNRVO(Body, getCurFunction());
  11004. }
  11005. if (getCurFunction()->ObjCShouldCallSuper) {
  11006. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  11007. << MD->getSelector().getAsString();
  11008. getCurFunction()->ObjCShouldCallSuper = false;
  11009. }
  11010. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11011. const ObjCMethodDecl *InitMethod = nullptr;
  11012. bool isDesignated =
  11013. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11014. assert(isDesignated && InitMethod);
  11015. (void)isDesignated;
  11016. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11017. auto IFace = MD->getClassInterface();
  11018. if (!IFace)
  11019. return false;
  11020. auto SuperD = IFace->getSuperClass();
  11021. if (!SuperD)
  11022. return false;
  11023. return SuperD->getIdentifier() ==
  11024. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  11025. };
  11026. // Don't issue this warning for unavailable inits or direct subclasses
  11027. // of NSObject.
  11028. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  11029. Diag(MD->getLocation(),
  11030. diag::warn_objc_designated_init_missing_super_call);
  11031. Diag(InitMethod->getLocation(),
  11032. diag::note_objc_designated_init_marked_here);
  11033. }
  11034. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  11035. }
  11036. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  11037. // Don't issue this warning for unavaialable inits.
  11038. if (!MD->isUnavailable())
  11039. Diag(MD->getLocation(),
  11040. diag::warn_objc_secondary_init_missing_init_call);
  11041. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  11042. }
  11043. } else {
  11044. return nullptr;
  11045. }
  11046. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11047. DiagnoseUnguardedAvailabilityViolations(dcl);
  11048. assert(!getCurFunction()->ObjCShouldCallSuper &&
  11049. "This should only be set for ObjC methods, which should have been "
  11050. "handled in the block above.");
  11051. // Verify and clean out per-function state.
  11052. if (Body && (!FD || !FD->isDefaulted())) {
  11053. // C++ constructors that have function-try-blocks can't have return
  11054. // statements in the handlers of that block. (C++ [except.handle]p14)
  11055. // Verify this.
  11056. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  11057. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  11058. // Verify that gotos and switch cases don't jump into scopes illegally.
  11059. if (getCurFunction()->NeedsScopeChecking() &&
  11060. !PP.isCodeCompletionEnabled())
  11061. DiagnoseInvalidJumps(Body);
  11062. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  11063. if (!Destructor->getParent()->isDependentType())
  11064. CheckDestructor(Destructor);
  11065. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11066. Destructor->getParent());
  11067. }
  11068. // If any errors have occurred, clear out any temporaries that may have
  11069. // been leftover. This ensures that these temporaries won't be picked up for
  11070. // deletion in some later function.
  11071. if (getDiagnostics().hasErrorOccurred() ||
  11072. getDiagnostics().getSuppressAllDiagnostics()) {
  11073. DiscardCleanupsInEvaluationContext();
  11074. }
  11075. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  11076. !isa<FunctionTemplateDecl>(dcl)) {
  11077. // Since the body is valid, issue any analysis-based warnings that are
  11078. // enabled.
  11079. ActivePolicy = &WP;
  11080. }
  11081. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  11082. (!CheckConstexprFunctionDecl(FD) ||
  11083. !CheckConstexprFunctionBody(FD, Body)))
  11084. FD->setInvalidDecl();
  11085. if (FD && FD->hasAttr<NakedAttr>()) {
  11086. for (const Stmt *S : Body->children()) {
  11087. // Allow local register variables without initializer as they don't
  11088. // require prologue.
  11089. bool RegisterVariables = false;
  11090. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  11091. for (const auto *Decl : DS->decls()) {
  11092. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  11093. RegisterVariables =
  11094. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  11095. if (!RegisterVariables)
  11096. break;
  11097. }
  11098. }
  11099. }
  11100. if (RegisterVariables)
  11101. continue;
  11102. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  11103. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  11104. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  11105. FD->setInvalidDecl();
  11106. break;
  11107. }
  11108. }
  11109. }
  11110. assert(ExprCleanupObjects.size() ==
  11111. ExprEvalContexts.back().NumCleanupObjects &&
  11112. "Leftover temporaries in function");
  11113. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  11114. assert(MaybeODRUseExprs.empty() &&
  11115. "Leftover expressions for odr-use checking");
  11116. }
  11117. if (!IsInstantiation)
  11118. PopDeclContext();
  11119. PopFunctionScopeInfo(ActivePolicy, dcl);
  11120. // If any errors have occurred, clear out any temporaries that may have
  11121. // been leftover. This ensures that these temporaries won't be picked up for
  11122. // deletion in some later function.
  11123. if (getDiagnostics().hasErrorOccurred()) {
  11124. DiscardCleanupsInEvaluationContext();
  11125. }
  11126. return dcl;
  11127. }
  11128. /// When we finish delayed parsing of an attribute, we must attach it to the
  11129. /// relevant Decl.
  11130. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  11131. ParsedAttributes &Attrs) {
  11132. // Always attach attributes to the underlying decl.
  11133. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  11134. D = TD->getTemplatedDecl();
  11135. ProcessDeclAttributeList(S, D, Attrs.getList());
  11136. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  11137. if (Method->isStatic())
  11138. checkThisInStaticMemberFunctionAttributes(Method);
  11139. }
  11140. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  11141. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  11142. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  11143. IdentifierInfo &II, Scope *S) {
  11144. // Before we produce a declaration for an implicitly defined
  11145. // function, see whether there was a locally-scoped declaration of
  11146. // this name as a function or variable. If so, use that
  11147. // (non-visible) declaration, and complain about it.
  11148. if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
  11149. Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
  11150. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  11151. return ExternCPrev;
  11152. }
  11153. // Extension in C99. Legal in C90, but warn about it.
  11154. unsigned diag_id;
  11155. if (II.getName().startswith("__builtin_"))
  11156. diag_id = diag::warn_builtin_unknown;
  11157. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  11158. else if (getLangOpts().OpenCL)
  11159. diag_id = diag::err_opencl_implicit_function_decl;
  11160. else if (getLangOpts().C99)
  11161. diag_id = diag::ext_implicit_function_decl;
  11162. else
  11163. diag_id = diag::warn_implicit_function_decl;
  11164. Diag(Loc, diag_id) << &II;
  11165. // Because typo correction is expensive, only do it if the implicit
  11166. // function declaration is going to be treated as an error.
  11167. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  11168. TypoCorrection Corrected;
  11169. if (S &&
  11170. (Corrected = CorrectTypo(
  11171. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  11172. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  11173. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  11174. /*ErrorRecovery*/false);
  11175. }
  11176. // Set a Declarator for the implicit definition: int foo();
  11177. const char *Dummy;
  11178. AttributeFactory attrFactory;
  11179. DeclSpec DS(attrFactory);
  11180. unsigned DiagID;
  11181. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  11182. Context.getPrintingPolicy());
  11183. (void)Error; // Silence warning.
  11184. assert(!Error && "Error setting up implicit decl!");
  11185. SourceLocation NoLoc;
  11186. Declarator D(DS, Declarator::BlockContext);
  11187. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  11188. /*IsAmbiguous=*/false,
  11189. /*LParenLoc=*/NoLoc,
  11190. /*Params=*/nullptr,
  11191. /*NumParams=*/0,
  11192. /*EllipsisLoc=*/NoLoc,
  11193. /*RParenLoc=*/NoLoc,
  11194. /*TypeQuals=*/0,
  11195. /*RefQualifierIsLvalueRef=*/true,
  11196. /*RefQualifierLoc=*/NoLoc,
  11197. /*ConstQualifierLoc=*/NoLoc,
  11198. /*VolatileQualifierLoc=*/NoLoc,
  11199. /*RestrictQualifierLoc=*/NoLoc,
  11200. /*MutableLoc=*/NoLoc,
  11201. EST_None,
  11202. /*ESpecRange=*/SourceRange(),
  11203. /*Exceptions=*/nullptr,
  11204. /*ExceptionRanges=*/nullptr,
  11205. /*NumExceptions=*/0,
  11206. /*NoexceptExpr=*/nullptr,
  11207. /*ExceptionSpecTokens=*/nullptr,
  11208. /*DeclsInPrototype=*/None,
  11209. Loc, Loc, D),
  11210. DS.getAttributes(),
  11211. SourceLocation());
  11212. D.SetIdentifier(&II, Loc);
  11213. // Insert this function into the enclosing block scope.
  11214. while (S && !S->isCompoundStmtScope())
  11215. S = S->getParent();
  11216. if (S == nullptr)
  11217. S = TUScope;
  11218. DeclContext *PrevDC = CurContext;
  11219. CurContext = Context.getTranslationUnitDecl();
  11220. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(S, D));
  11221. FD->setImplicit();
  11222. CurContext = PrevDC;
  11223. AddKnownFunctionAttributes(FD);
  11224. return FD;
  11225. }
  11226. /// \brief Adds any function attributes that we know a priori based on
  11227. /// the declaration of this function.
  11228. ///
  11229. /// These attributes can apply both to implicitly-declared builtins
  11230. /// (like __builtin___printf_chk) or to library-declared functions
  11231. /// like NSLog or printf.
  11232. ///
  11233. /// We need to check for duplicate attributes both here and where user-written
  11234. /// attributes are applied to declarations.
  11235. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  11236. if (FD->isInvalidDecl())
  11237. return;
  11238. // If this is a built-in function, map its builtin attributes to
  11239. // actual attributes.
  11240. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11241. // Handle printf-formatting attributes.
  11242. unsigned FormatIdx;
  11243. bool HasVAListArg;
  11244. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  11245. if (!FD->hasAttr<FormatAttr>()) {
  11246. const char *fmt = "printf";
  11247. unsigned int NumParams = FD->getNumParams();
  11248. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  11249. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  11250. fmt = "NSString";
  11251. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11252. &Context.Idents.get(fmt),
  11253. FormatIdx+1,
  11254. HasVAListArg ? 0 : FormatIdx+2,
  11255. FD->getLocation()));
  11256. }
  11257. }
  11258. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  11259. HasVAListArg)) {
  11260. if (!FD->hasAttr<FormatAttr>())
  11261. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11262. &Context.Idents.get("scanf"),
  11263. FormatIdx+1,
  11264. HasVAListArg ? 0 : FormatIdx+2,
  11265. FD->getLocation()));
  11266. }
  11267. // Mark const if we don't care about errno and that is the only
  11268. // thing preventing the function from being const. This allows
  11269. // IRgen to use LLVM intrinsics for such functions.
  11270. if (!getLangOpts().MathErrno &&
  11271. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
  11272. if (!FD->hasAttr<ConstAttr>())
  11273. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11274. }
  11275. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  11276. !FD->hasAttr<ReturnsTwiceAttr>())
  11277. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  11278. FD->getLocation()));
  11279. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  11280. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11281. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  11282. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  11283. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  11284. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11285. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  11286. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  11287. // Add the appropriate attribute, depending on the CUDA compilation mode
  11288. // and which target the builtin belongs to. For example, during host
  11289. // compilation, aux builtins are __device__, while the rest are __host__.
  11290. if (getLangOpts().CUDAIsDevice !=
  11291. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  11292. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  11293. else
  11294. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  11295. }
  11296. }
  11297. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  11298. // throw, add an implicit nothrow attribute to any extern "C" function we come
  11299. // across.
  11300. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  11301. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  11302. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  11303. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  11304. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11305. }
  11306. IdentifierInfo *Name = FD->getIdentifier();
  11307. if (!Name)
  11308. return;
  11309. if ((!getLangOpts().CPlusPlus &&
  11310. FD->getDeclContext()->isTranslationUnit()) ||
  11311. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  11312. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  11313. LinkageSpecDecl::lang_c)) {
  11314. // Okay: this could be a libc/libm/Objective-C function we know
  11315. // about.
  11316. } else
  11317. return;
  11318. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  11319. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  11320. // target-specific builtins, perhaps?
  11321. if (!FD->hasAttr<FormatAttr>())
  11322. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11323. &Context.Idents.get("printf"), 2,
  11324. Name->isStr("vasprintf") ? 0 : 3,
  11325. FD->getLocation()));
  11326. }
  11327. if (Name->isStr("__CFStringMakeConstantString")) {
  11328. // We already have a __builtin___CFStringMakeConstantString,
  11329. // but builds that use -fno-constant-cfstrings don't go through that.
  11330. if (!FD->hasAttr<FormatArgAttr>())
  11331. FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
  11332. FD->getLocation()));
  11333. }
  11334. }
  11335. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  11336. TypeSourceInfo *TInfo) {
  11337. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  11338. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  11339. if (!TInfo) {
  11340. assert(D.isInvalidType() && "no declarator info for valid type");
  11341. TInfo = Context.getTrivialTypeSourceInfo(T);
  11342. }
  11343. // Scope manipulation handled by caller.
  11344. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  11345. D.getLocStart(),
  11346. D.getIdentifierLoc(),
  11347. D.getIdentifier(),
  11348. TInfo);
  11349. // Bail out immediately if we have an invalid declaration.
  11350. if (D.isInvalidType()) {
  11351. NewTD->setInvalidDecl();
  11352. return NewTD;
  11353. }
  11354. if (D.getDeclSpec().isModulePrivateSpecified()) {
  11355. if (CurContext->isFunctionOrMethod())
  11356. Diag(NewTD->getLocation(), diag::err_module_private_local)
  11357. << 2 << NewTD->getDeclName()
  11358. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11359. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11360. else
  11361. NewTD->setModulePrivate();
  11362. }
  11363. // C++ [dcl.typedef]p8:
  11364. // If the typedef declaration defines an unnamed class (or
  11365. // enum), the first typedef-name declared by the declaration
  11366. // to be that class type (or enum type) is used to denote the
  11367. // class type (or enum type) for linkage purposes only.
  11368. // We need to check whether the type was declared in the declaration.
  11369. switch (D.getDeclSpec().getTypeSpecType()) {
  11370. case TST_enum:
  11371. case TST_struct:
  11372. case TST_interface:
  11373. case TST_union:
  11374. case TST_class: {
  11375. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  11376. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  11377. break;
  11378. }
  11379. default:
  11380. break;
  11381. }
  11382. return NewTD;
  11383. }
  11384. /// \brief Check that this is a valid underlying type for an enum declaration.
  11385. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  11386. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  11387. QualType T = TI->getType();
  11388. if (T->isDependentType())
  11389. return false;
  11390. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  11391. if (BT->isInteger())
  11392. return false;
  11393. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  11394. return true;
  11395. }
  11396. /// Check whether this is a valid redeclaration of a previous enumeration.
  11397. /// \return true if the redeclaration was invalid.
  11398. bool Sema::CheckEnumRedeclaration(
  11399. SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
  11400. bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
  11401. bool IsFixed = !EnumUnderlyingTy.isNull();
  11402. if (IsScoped != Prev->isScoped()) {
  11403. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  11404. << Prev->isScoped();
  11405. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11406. return true;
  11407. }
  11408. if (IsFixed && Prev->isFixed()) {
  11409. if (!EnumUnderlyingTy->isDependentType() &&
  11410. !Prev->getIntegerType()->isDependentType() &&
  11411. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  11412. Prev->getIntegerType())) {
  11413. // TODO: Highlight the underlying type of the redeclaration.
  11414. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  11415. << EnumUnderlyingTy << Prev->getIntegerType();
  11416. Diag(Prev->getLocation(), diag::note_previous_declaration)
  11417. << Prev->getIntegerTypeRange();
  11418. return true;
  11419. }
  11420. } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
  11421. ;
  11422. } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
  11423. ;
  11424. } else if (IsFixed != Prev->isFixed()) {
  11425. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  11426. << Prev->isFixed();
  11427. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11428. return true;
  11429. }
  11430. return false;
  11431. }
  11432. /// \brief Get diagnostic %select index for tag kind for
  11433. /// redeclaration diagnostic message.
  11434. /// WARNING: Indexes apply to particular diagnostics only!
  11435. ///
  11436. /// \returns diagnostic %select index.
  11437. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  11438. switch (Tag) {
  11439. case TTK_Struct: return 0;
  11440. case TTK_Interface: return 1;
  11441. case TTK_Class: return 2;
  11442. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  11443. }
  11444. }
  11445. /// \brief Determine if tag kind is a class-key compatible with
  11446. /// class for redeclaration (class, struct, or __interface).
  11447. ///
  11448. /// \returns true iff the tag kind is compatible.
  11449. static bool isClassCompatTagKind(TagTypeKind Tag)
  11450. {
  11451. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  11452. }
  11453. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  11454. TagTypeKind TTK) {
  11455. if (isa<TypedefDecl>(PrevDecl))
  11456. return NTK_Typedef;
  11457. else if (isa<TypeAliasDecl>(PrevDecl))
  11458. return NTK_TypeAlias;
  11459. else if (isa<ClassTemplateDecl>(PrevDecl))
  11460. return NTK_Template;
  11461. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  11462. return NTK_TypeAliasTemplate;
  11463. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  11464. return NTK_TemplateTemplateArgument;
  11465. switch (TTK) {
  11466. case TTK_Struct:
  11467. case TTK_Interface:
  11468. case TTK_Class:
  11469. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  11470. case TTK_Union:
  11471. return NTK_NonUnion;
  11472. case TTK_Enum:
  11473. return NTK_NonEnum;
  11474. }
  11475. llvm_unreachable("invalid TTK");
  11476. }
  11477. /// \brief Determine whether a tag with a given kind is acceptable
  11478. /// as a redeclaration of the given tag declaration.
  11479. ///
  11480. /// \returns true if the new tag kind is acceptable, false otherwise.
  11481. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  11482. TagTypeKind NewTag, bool isDefinition,
  11483. SourceLocation NewTagLoc,
  11484. const IdentifierInfo *Name) {
  11485. // C++ [dcl.type.elab]p3:
  11486. // The class-key or enum keyword present in the
  11487. // elaborated-type-specifier shall agree in kind with the
  11488. // declaration to which the name in the elaborated-type-specifier
  11489. // refers. This rule also applies to the form of
  11490. // elaborated-type-specifier that declares a class-name or
  11491. // friend class since it can be construed as referring to the
  11492. // definition of the class. Thus, in any
  11493. // elaborated-type-specifier, the enum keyword shall be used to
  11494. // refer to an enumeration (7.2), the union class-key shall be
  11495. // used to refer to a union (clause 9), and either the class or
  11496. // struct class-key shall be used to refer to a class (clause 9)
  11497. // declared using the class or struct class-key.
  11498. TagTypeKind OldTag = Previous->getTagKind();
  11499. if (!isDefinition || !isClassCompatTagKind(NewTag))
  11500. if (OldTag == NewTag)
  11501. return true;
  11502. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  11503. // Warn about the struct/class tag mismatch.
  11504. bool isTemplate = false;
  11505. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  11506. isTemplate = Record->getDescribedClassTemplate();
  11507. if (inTemplateInstantiation()) {
  11508. // In a template instantiation, do not offer fix-its for tag mismatches
  11509. // since they usually mess up the template instead of fixing the problem.
  11510. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11511. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11512. << getRedeclDiagFromTagKind(OldTag);
  11513. return true;
  11514. }
  11515. if (isDefinition) {
  11516. // On definitions, check previous tags and issue a fix-it for each
  11517. // one that doesn't match the current tag.
  11518. if (Previous->getDefinition()) {
  11519. // Don't suggest fix-its for redefinitions.
  11520. return true;
  11521. }
  11522. bool previousMismatch = false;
  11523. for (auto I : Previous->redecls()) {
  11524. if (I->getTagKind() != NewTag) {
  11525. if (!previousMismatch) {
  11526. previousMismatch = true;
  11527. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  11528. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11529. << getRedeclDiagFromTagKind(I->getTagKind());
  11530. }
  11531. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  11532. << getRedeclDiagFromTagKind(NewTag)
  11533. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  11534. TypeWithKeyword::getTagTypeKindName(NewTag));
  11535. }
  11536. }
  11537. return true;
  11538. }
  11539. // Check for a previous definition. If current tag and definition
  11540. // are same type, do nothing. If no definition, but disagree with
  11541. // with previous tag type, give a warning, but no fix-it.
  11542. const TagDecl *Redecl = Previous->getDefinition() ?
  11543. Previous->getDefinition() : Previous;
  11544. if (Redecl->getTagKind() == NewTag) {
  11545. return true;
  11546. }
  11547. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11548. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11549. << getRedeclDiagFromTagKind(OldTag);
  11550. Diag(Redecl->getLocation(), diag::note_previous_use);
  11551. // If there is a previous definition, suggest a fix-it.
  11552. if (Previous->getDefinition()) {
  11553. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  11554. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  11555. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  11556. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  11557. }
  11558. return true;
  11559. }
  11560. return false;
  11561. }
  11562. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  11563. /// from an outer enclosing namespace or file scope inside a friend declaration.
  11564. /// This should provide the commented out code in the following snippet:
  11565. /// namespace N {
  11566. /// struct X;
  11567. /// namespace M {
  11568. /// struct Y { friend struct /*N::*/ X; };
  11569. /// }
  11570. /// }
  11571. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  11572. SourceLocation NameLoc) {
  11573. // While the decl is in a namespace, do repeated lookup of that name and see
  11574. // if we get the same namespace back. If we do not, continue until
  11575. // translation unit scope, at which point we have a fully qualified NNS.
  11576. SmallVector<IdentifierInfo *, 4> Namespaces;
  11577. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11578. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  11579. // This tag should be declared in a namespace, which can only be enclosed by
  11580. // other namespaces. Bail if there's an anonymous namespace in the chain.
  11581. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  11582. if (!Namespace || Namespace->isAnonymousNamespace())
  11583. return FixItHint();
  11584. IdentifierInfo *II = Namespace->getIdentifier();
  11585. Namespaces.push_back(II);
  11586. NamedDecl *Lookup = SemaRef.LookupSingleName(
  11587. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  11588. if (Lookup == Namespace)
  11589. break;
  11590. }
  11591. // Once we have all the namespaces, reverse them to go outermost first, and
  11592. // build an NNS.
  11593. SmallString<64> Insertion;
  11594. llvm::raw_svector_ostream OS(Insertion);
  11595. if (DC->isTranslationUnit())
  11596. OS << "::";
  11597. std::reverse(Namespaces.begin(), Namespaces.end());
  11598. for (auto *II : Namespaces)
  11599. OS << II->getName() << "::";
  11600. return FixItHint::CreateInsertion(NameLoc, Insertion);
  11601. }
  11602. /// \brief Determine whether a tag originally declared in context \p OldDC can
  11603. /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
  11604. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  11605. /// using-declaration).
  11606. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  11607. DeclContext *NewDC) {
  11608. OldDC = OldDC->getRedeclContext();
  11609. NewDC = NewDC->getRedeclContext();
  11610. if (OldDC->Equals(NewDC))
  11611. return true;
  11612. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  11613. // encloses the other).
  11614. if (S.getLangOpts().MSVCCompat &&
  11615. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  11616. return true;
  11617. return false;
  11618. }
  11619. /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
  11620. /// former case, Name will be non-null. In the later case, Name will be null.
  11621. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  11622. /// reference/declaration/definition of a tag.
  11623. ///
  11624. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  11625. /// trailing-type-specifier) other than one in an alias-declaration.
  11626. ///
  11627. /// \param SkipBody If non-null, will be set to indicate if the caller should
  11628. /// skip the definition of this tag and treat it as if it were a declaration.
  11629. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  11630. SourceLocation KWLoc, CXXScopeSpec &SS,
  11631. IdentifierInfo *Name, SourceLocation NameLoc,
  11632. AttributeList *Attr, AccessSpecifier AS,
  11633. SourceLocation ModulePrivateLoc,
  11634. MultiTemplateParamsArg TemplateParameterLists,
  11635. bool &OwnedDecl, bool &IsDependent,
  11636. SourceLocation ScopedEnumKWLoc,
  11637. bool ScopedEnumUsesClassTag,
  11638. TypeResult UnderlyingType,
  11639. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  11640. SkipBodyInfo *SkipBody) {
  11641. // If this is not a definition, it must have a name.
  11642. IdentifierInfo *OrigName = Name;
  11643. assert((Name != nullptr || TUK == TUK_Definition) &&
  11644. "Nameless record must be a definition!");
  11645. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  11646. OwnedDecl = false;
  11647. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  11648. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  11649. // FIXME: Check member specializations more carefully.
  11650. bool isMemberSpecialization = false;
  11651. bool Invalid = false;
  11652. // We only need to do this matching if we have template parameters
  11653. // or a scope specifier, which also conveniently avoids this work
  11654. // for non-C++ cases.
  11655. if (TemplateParameterLists.size() > 0 ||
  11656. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  11657. if (TemplateParameterList *TemplateParams =
  11658. MatchTemplateParametersToScopeSpecifier(
  11659. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  11660. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  11661. if (Kind == TTK_Enum) {
  11662. Diag(KWLoc, diag::err_enum_template);
  11663. return nullptr;
  11664. }
  11665. if (TemplateParams->size() > 0) {
  11666. // This is a declaration or definition of a class template (which may
  11667. // be a member of another template).
  11668. if (Invalid)
  11669. return nullptr;
  11670. OwnedDecl = false;
  11671. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  11672. SS, Name, NameLoc, Attr,
  11673. TemplateParams, AS,
  11674. ModulePrivateLoc,
  11675. /*FriendLoc*/SourceLocation(),
  11676. TemplateParameterLists.size()-1,
  11677. TemplateParameterLists.data(),
  11678. SkipBody);
  11679. return Result.get();
  11680. } else {
  11681. // The "template<>" header is extraneous.
  11682. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  11683. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  11684. isMemberSpecialization = true;
  11685. }
  11686. }
  11687. }
  11688. // Figure out the underlying type if this a enum declaration. We need to do
  11689. // this early, because it's needed to detect if this is an incompatible
  11690. // redeclaration.
  11691. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  11692. bool EnumUnderlyingIsImplicit = false;
  11693. if (Kind == TTK_Enum) {
  11694. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
  11695. // No underlying type explicitly specified, or we failed to parse the
  11696. // type, default to int.
  11697. EnumUnderlying = Context.IntTy.getTypePtr();
  11698. else if (UnderlyingType.get()) {
  11699. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  11700. // integral type; any cv-qualification is ignored.
  11701. TypeSourceInfo *TI = nullptr;
  11702. GetTypeFromParser(UnderlyingType.get(), &TI);
  11703. EnumUnderlying = TI;
  11704. if (CheckEnumUnderlyingType(TI))
  11705. // Recover by falling back to int.
  11706. EnumUnderlying = Context.IntTy.getTypePtr();
  11707. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  11708. UPPC_FixedUnderlyingType))
  11709. EnumUnderlying = Context.IntTy.getTypePtr();
  11710. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11711. if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
  11712. // Microsoft enums are always of int type.
  11713. EnumUnderlying = Context.IntTy.getTypePtr();
  11714. EnumUnderlyingIsImplicit = true;
  11715. }
  11716. }
  11717. }
  11718. DeclContext *SearchDC = CurContext;
  11719. DeclContext *DC = CurContext;
  11720. bool isStdBadAlloc = false;
  11721. bool isStdAlignValT = false;
  11722. RedeclarationKind Redecl = ForRedeclaration;
  11723. if (TUK == TUK_Friend || TUK == TUK_Reference)
  11724. Redecl = NotForRedeclaration;
  11725. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  11726. /// implemented asks for structural equivalence checking, the returned decl
  11727. /// here is passed back to the parser, allowing the tag body to be parsed.
  11728. auto createTagFromNewDecl = [&]() -> TagDecl * {
  11729. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  11730. // If there is an identifier, use the location of the identifier as the
  11731. // location of the decl, otherwise use the location of the struct/union
  11732. // keyword.
  11733. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  11734. TagDecl *New = nullptr;
  11735. if (Kind == TTK_Enum) {
  11736. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  11737. ScopedEnum, ScopedEnumUsesClassTag,
  11738. !EnumUnderlying.isNull());
  11739. // If this is an undefined enum, bail.
  11740. if (TUK != TUK_Definition && !Invalid)
  11741. return nullptr;
  11742. if (EnumUnderlying) {
  11743. EnumDecl *ED = cast<EnumDecl>(New);
  11744. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  11745. ED->setIntegerTypeSourceInfo(TI);
  11746. else
  11747. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  11748. ED->setPromotionType(ED->getIntegerType());
  11749. }
  11750. } else { // struct/union
  11751. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  11752. nullptr);
  11753. }
  11754. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  11755. // Add alignment attributes if necessary; these attributes are checked
  11756. // when the ASTContext lays out the structure.
  11757. //
  11758. // It is important for implementing the correct semantics that this
  11759. // happen here (in ActOnTag). The #pragma pack stack is
  11760. // maintained as a result of parser callbacks which can occur at
  11761. // many points during the parsing of a struct declaration (because
  11762. // the #pragma tokens are effectively skipped over during the
  11763. // parsing of the struct).
  11764. if (TUK == TUK_Definition) {
  11765. AddAlignmentAttributesForRecord(RD);
  11766. AddMsStructLayoutForRecord(RD);
  11767. }
  11768. }
  11769. New->setLexicalDeclContext(CurContext);
  11770. return New;
  11771. };
  11772. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  11773. if (Name && SS.isNotEmpty()) {
  11774. // We have a nested-name tag ('struct foo::bar').
  11775. // Check for invalid 'foo::'.
  11776. if (SS.isInvalid()) {
  11777. Name = nullptr;
  11778. goto CreateNewDecl;
  11779. }
  11780. // If this is a friend or a reference to a class in a dependent
  11781. // context, don't try to make a decl for it.
  11782. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  11783. DC = computeDeclContext(SS, false);
  11784. if (!DC) {
  11785. IsDependent = true;
  11786. return nullptr;
  11787. }
  11788. } else {
  11789. DC = computeDeclContext(SS, true);
  11790. if (!DC) {
  11791. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  11792. << SS.getRange();
  11793. return nullptr;
  11794. }
  11795. }
  11796. if (RequireCompleteDeclContext(SS, DC))
  11797. return nullptr;
  11798. SearchDC = DC;
  11799. // Look-up name inside 'foo::'.
  11800. LookupQualifiedName(Previous, DC);
  11801. if (Previous.isAmbiguous())
  11802. return nullptr;
  11803. if (Previous.empty()) {
  11804. // Name lookup did not find anything. However, if the
  11805. // nested-name-specifier refers to the current instantiation,
  11806. // and that current instantiation has any dependent base
  11807. // classes, we might find something at instantiation time: treat
  11808. // this as a dependent elaborated-type-specifier.
  11809. // But this only makes any sense for reference-like lookups.
  11810. if (Previous.wasNotFoundInCurrentInstantiation() &&
  11811. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  11812. IsDependent = true;
  11813. return nullptr;
  11814. }
  11815. // A tag 'foo::bar' must already exist.
  11816. Diag(NameLoc, diag::err_not_tag_in_scope)
  11817. << Kind << Name << DC << SS.getRange();
  11818. Name = nullptr;
  11819. Invalid = true;
  11820. goto CreateNewDecl;
  11821. }
  11822. } else if (Name) {
  11823. // C++14 [class.mem]p14:
  11824. // If T is the name of a class, then each of the following shall have a
  11825. // name different from T:
  11826. // -- every member of class T that is itself a type
  11827. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  11828. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  11829. return nullptr;
  11830. // If this is a named struct, check to see if there was a previous forward
  11831. // declaration or definition.
  11832. // FIXME: We're looking into outer scopes here, even when we
  11833. // shouldn't be. Doing so can result in ambiguities that we
  11834. // shouldn't be diagnosing.
  11835. LookupName(Previous, S);
  11836. // When declaring or defining a tag, ignore ambiguities introduced
  11837. // by types using'ed into this scope.
  11838. if (Previous.isAmbiguous() &&
  11839. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  11840. LookupResult::Filter F = Previous.makeFilter();
  11841. while (F.hasNext()) {
  11842. NamedDecl *ND = F.next();
  11843. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  11844. SearchDC->getRedeclContext()))
  11845. F.erase();
  11846. }
  11847. F.done();
  11848. }
  11849. // C++11 [namespace.memdef]p3:
  11850. // If the name in a friend declaration is neither qualified nor
  11851. // a template-id and the declaration is a function or an
  11852. // elaborated-type-specifier, the lookup to determine whether
  11853. // the entity has been previously declared shall not consider
  11854. // any scopes outside the innermost enclosing namespace.
  11855. //
  11856. // MSVC doesn't implement the above rule for types, so a friend tag
  11857. // declaration may be a redeclaration of a type declared in an enclosing
  11858. // scope. They do implement this rule for friend functions.
  11859. //
  11860. // Does it matter that this should be by scope instead of by
  11861. // semantic context?
  11862. if (!Previous.empty() && TUK == TUK_Friend) {
  11863. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  11864. LookupResult::Filter F = Previous.makeFilter();
  11865. bool FriendSawTagOutsideEnclosingNamespace = false;
  11866. while (F.hasNext()) {
  11867. NamedDecl *ND = F.next();
  11868. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11869. if (DC->isFileContext() &&
  11870. !EnclosingNS->Encloses(ND->getDeclContext())) {
  11871. if (getLangOpts().MSVCCompat)
  11872. FriendSawTagOutsideEnclosingNamespace = true;
  11873. else
  11874. F.erase();
  11875. }
  11876. }
  11877. F.done();
  11878. // Diagnose this MSVC extension in the easy case where lookup would have
  11879. // unambiguously found something outside the enclosing namespace.
  11880. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  11881. NamedDecl *ND = Previous.getFoundDecl();
  11882. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  11883. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  11884. }
  11885. }
  11886. // Note: there used to be some attempt at recovery here.
  11887. if (Previous.isAmbiguous())
  11888. return nullptr;
  11889. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  11890. // FIXME: This makes sure that we ignore the contexts associated
  11891. // with C structs, unions, and enums when looking for a matching
  11892. // tag declaration or definition. See the similar lookup tweak
  11893. // in Sema::LookupName; is there a better way to deal with this?
  11894. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  11895. SearchDC = SearchDC->getParent();
  11896. }
  11897. }
  11898. if (Previous.isSingleResult() &&
  11899. Previous.getFoundDecl()->isTemplateParameter()) {
  11900. // Maybe we will complain about the shadowed template parameter.
  11901. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  11902. // Just pretend that we didn't see the previous declaration.
  11903. Previous.clear();
  11904. }
  11905. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  11906. DC->Equals(getStdNamespace())) {
  11907. if (Name->isStr("bad_alloc")) {
  11908. // This is a declaration of or a reference to "std::bad_alloc".
  11909. isStdBadAlloc = true;
  11910. // If std::bad_alloc has been implicitly declared (but made invisible to
  11911. // name lookup), fill in this implicit declaration as the previous
  11912. // declaration, so that the declarations get chained appropriately.
  11913. if (Previous.empty() && StdBadAlloc)
  11914. Previous.addDecl(getStdBadAlloc());
  11915. } else if (Name->isStr("align_val_t")) {
  11916. isStdAlignValT = true;
  11917. if (Previous.empty() && StdAlignValT)
  11918. Previous.addDecl(getStdAlignValT());
  11919. }
  11920. }
  11921. // If we didn't find a previous declaration, and this is a reference
  11922. // (or friend reference), move to the correct scope. In C++, we
  11923. // also need to do a redeclaration lookup there, just in case
  11924. // there's a shadow friend decl.
  11925. if (Name && Previous.empty() &&
  11926. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  11927. if (Invalid) goto CreateNewDecl;
  11928. assert(SS.isEmpty());
  11929. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  11930. // C++ [basic.scope.pdecl]p5:
  11931. // -- for an elaborated-type-specifier of the form
  11932. //
  11933. // class-key identifier
  11934. //
  11935. // if the elaborated-type-specifier is used in the
  11936. // decl-specifier-seq or parameter-declaration-clause of a
  11937. // function defined in namespace scope, the identifier is
  11938. // declared as a class-name in the namespace that contains
  11939. // the declaration; otherwise, except as a friend
  11940. // declaration, the identifier is declared in the smallest
  11941. // non-class, non-function-prototype scope that contains the
  11942. // declaration.
  11943. //
  11944. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  11945. // C structs and unions.
  11946. //
  11947. // It is an error in C++ to declare (rather than define) an enum
  11948. // type, including via an elaborated type specifier. We'll
  11949. // diagnose that later; for now, declare the enum in the same
  11950. // scope as we would have picked for any other tag type.
  11951. //
  11952. // GNU C also supports this behavior as part of its incomplete
  11953. // enum types extension, while GNU C++ does not.
  11954. //
  11955. // Find the context where we'll be declaring the tag.
  11956. // FIXME: We would like to maintain the current DeclContext as the
  11957. // lexical context,
  11958. SearchDC = getTagInjectionContext(SearchDC);
  11959. // Find the scope where we'll be declaring the tag.
  11960. S = getTagInjectionScope(S, getLangOpts());
  11961. } else {
  11962. assert(TUK == TUK_Friend);
  11963. // C++ [namespace.memdef]p3:
  11964. // If a friend declaration in a non-local class first declares a
  11965. // class or function, the friend class or function is a member of
  11966. // the innermost enclosing namespace.
  11967. SearchDC = SearchDC->getEnclosingNamespaceContext();
  11968. }
  11969. // In C++, we need to do a redeclaration lookup to properly
  11970. // diagnose some problems.
  11971. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  11972. // hidden declaration so that we don't get ambiguity errors when using a
  11973. // type declared by an elaborated-type-specifier. In C that is not correct
  11974. // and we should instead merge compatible types found by lookup.
  11975. if (getLangOpts().CPlusPlus) {
  11976. Previous.setRedeclarationKind(ForRedeclaration);
  11977. LookupQualifiedName(Previous, SearchDC);
  11978. } else {
  11979. Previous.setRedeclarationKind(ForRedeclaration);
  11980. LookupName(Previous, S);
  11981. }
  11982. }
  11983. // If we have a known previous declaration to use, then use it.
  11984. if (Previous.empty() && SkipBody && SkipBody->Previous)
  11985. Previous.addDecl(SkipBody->Previous);
  11986. if (!Previous.empty()) {
  11987. NamedDecl *PrevDecl = Previous.getFoundDecl();
  11988. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  11989. // It's okay to have a tag decl in the same scope as a typedef
  11990. // which hides a tag decl in the same scope. Finding this
  11991. // insanity with a redeclaration lookup can only actually happen
  11992. // in C++.
  11993. //
  11994. // This is also okay for elaborated-type-specifiers, which is
  11995. // technically forbidden by the current standard but which is
  11996. // okay according to the likely resolution of an open issue;
  11997. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  11998. if (getLangOpts().CPlusPlus) {
  11999. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12000. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  12001. TagDecl *Tag = TT->getDecl();
  12002. if (Tag->getDeclName() == Name &&
  12003. Tag->getDeclContext()->getRedeclContext()
  12004. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  12005. PrevDecl = Tag;
  12006. Previous.clear();
  12007. Previous.addDecl(Tag);
  12008. Previous.resolveKind();
  12009. }
  12010. }
  12011. }
  12012. }
  12013. // If this is a redeclaration of a using shadow declaration, it must
  12014. // declare a tag in the same context. In MSVC mode, we allow a
  12015. // redefinition if either context is within the other.
  12016. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  12017. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  12018. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  12019. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  12020. !(OldTag && isAcceptableTagRedeclContext(
  12021. *this, OldTag->getDeclContext(), SearchDC))) {
  12022. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  12023. Diag(Shadow->getTargetDecl()->getLocation(),
  12024. diag::note_using_decl_target);
  12025. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  12026. << 0;
  12027. // Recover by ignoring the old declaration.
  12028. Previous.clear();
  12029. goto CreateNewDecl;
  12030. }
  12031. }
  12032. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  12033. // If this is a use of a previous tag, or if the tag is already declared
  12034. // in the same scope (so that the definition/declaration completes or
  12035. // rementions the tag), reuse the decl.
  12036. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  12037. isDeclInScope(DirectPrevDecl, SearchDC, S,
  12038. SS.isNotEmpty() || isMemberSpecialization)) {
  12039. // Make sure that this wasn't declared as an enum and now used as a
  12040. // struct or something similar.
  12041. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  12042. TUK == TUK_Definition, KWLoc,
  12043. Name)) {
  12044. bool SafeToContinue
  12045. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  12046. Kind != TTK_Enum);
  12047. if (SafeToContinue)
  12048. Diag(KWLoc, diag::err_use_with_wrong_tag)
  12049. << Name
  12050. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  12051. PrevTagDecl->getKindName());
  12052. else
  12053. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  12054. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  12055. if (SafeToContinue)
  12056. Kind = PrevTagDecl->getTagKind();
  12057. else {
  12058. // Recover by making this an anonymous redefinition.
  12059. Name = nullptr;
  12060. Previous.clear();
  12061. Invalid = true;
  12062. }
  12063. }
  12064. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  12065. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  12066. // If this is an elaborated-type-specifier for a scoped enumeration,
  12067. // the 'class' keyword is not necessary and not permitted.
  12068. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12069. if (ScopedEnum)
  12070. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  12071. << PrevEnum->isScoped()
  12072. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  12073. return PrevTagDecl;
  12074. }
  12075. QualType EnumUnderlyingTy;
  12076. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12077. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  12078. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  12079. EnumUnderlyingTy = QualType(T, 0);
  12080. // All conflicts with previous declarations are recovered by
  12081. // returning the previous declaration, unless this is a definition,
  12082. // in which case we want the caller to bail out.
  12083. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  12084. ScopedEnum, EnumUnderlyingTy,
  12085. EnumUnderlyingIsImplicit, PrevEnum))
  12086. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  12087. }
  12088. // C++11 [class.mem]p1:
  12089. // A member shall not be declared twice in the member-specification,
  12090. // except that a nested class or member class template can be declared
  12091. // and then later defined.
  12092. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  12093. S->isDeclScope(PrevDecl)) {
  12094. Diag(NameLoc, diag::ext_member_redeclared);
  12095. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  12096. }
  12097. if (!Invalid) {
  12098. // If this is a use, just return the declaration we found, unless
  12099. // we have attributes.
  12100. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12101. if (Attr) {
  12102. // FIXME: Diagnose these attributes. For now, we create a new
  12103. // declaration to hold them.
  12104. } else if (TUK == TUK_Reference &&
  12105. (PrevTagDecl->getFriendObjectKind() ==
  12106. Decl::FOK_Undeclared ||
  12107. PrevDecl->getOwningModule() != getCurrentModule()) &&
  12108. SS.isEmpty()) {
  12109. // This declaration is a reference to an existing entity, but
  12110. // has different visibility from that entity: it either makes
  12111. // a friend visible or it makes a type visible in a new module.
  12112. // In either case, create a new declaration. We only do this if
  12113. // the declaration would have meant the same thing if no prior
  12114. // declaration were found, that is, if it was found in the same
  12115. // scope where we would have injected a declaration.
  12116. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  12117. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  12118. return PrevTagDecl;
  12119. // This is in the injected scope, create a new declaration in
  12120. // that scope.
  12121. S = getTagInjectionScope(S, getLangOpts());
  12122. } else {
  12123. return PrevTagDecl;
  12124. }
  12125. }
  12126. // Diagnose attempts to redefine a tag.
  12127. if (TUK == TUK_Definition) {
  12128. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  12129. // If we're defining a specialization and the previous definition
  12130. // is from an implicit instantiation, don't emit an error
  12131. // here; we'll catch this in the general case below.
  12132. bool IsExplicitSpecializationAfterInstantiation = false;
  12133. if (isMemberSpecialization) {
  12134. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  12135. IsExplicitSpecializationAfterInstantiation =
  12136. RD->getTemplateSpecializationKind() !=
  12137. TSK_ExplicitSpecialization;
  12138. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  12139. IsExplicitSpecializationAfterInstantiation =
  12140. ED->getTemplateSpecializationKind() !=
  12141. TSK_ExplicitSpecialization;
  12142. }
  12143. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  12144. // not keep more that one definition around (merge them). However,
  12145. // ensure the decl passes the structural compatibility check in
  12146. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  12147. NamedDecl *Hidden = nullptr;
  12148. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  12149. // There is a definition of this tag, but it is not visible. We
  12150. // explicitly make use of C++'s one definition rule here, and
  12151. // assume that this definition is identical to the hidden one
  12152. // we already have. Make the existing definition visible and
  12153. // use it in place of this one.
  12154. if (!getLangOpts().CPlusPlus) {
  12155. // Postpone making the old definition visible until after we
  12156. // complete parsing the new one and do the structural
  12157. // comparison.
  12158. SkipBody->CheckSameAsPrevious = true;
  12159. SkipBody->New = createTagFromNewDecl();
  12160. SkipBody->Previous = Hidden;
  12161. } else {
  12162. SkipBody->ShouldSkip = true;
  12163. makeMergedDefinitionVisible(Hidden);
  12164. }
  12165. return Def;
  12166. } else if (!IsExplicitSpecializationAfterInstantiation) {
  12167. // A redeclaration in function prototype scope in C isn't
  12168. // visible elsewhere, so merely issue a warning.
  12169. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  12170. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  12171. else
  12172. Diag(NameLoc, diag::err_redefinition) << Name;
  12173. notePreviousDefinition(Def,
  12174. NameLoc.isValid() ? NameLoc : KWLoc);
  12175. // If this is a redefinition, recover by making this
  12176. // struct be anonymous, which will make any later
  12177. // references get the previous definition.
  12178. Name = nullptr;
  12179. Previous.clear();
  12180. Invalid = true;
  12181. }
  12182. } else {
  12183. // If the type is currently being defined, complain
  12184. // about a nested redefinition.
  12185. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  12186. if (TD->isBeingDefined()) {
  12187. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  12188. Diag(PrevTagDecl->getLocation(),
  12189. diag::note_previous_definition);
  12190. Name = nullptr;
  12191. Previous.clear();
  12192. Invalid = true;
  12193. }
  12194. }
  12195. // Okay, this is definition of a previously declared or referenced
  12196. // tag. We're going to create a new Decl for it.
  12197. }
  12198. // Okay, we're going to make a redeclaration. If this is some kind
  12199. // of reference, make sure we build the redeclaration in the same DC
  12200. // as the original, and ignore the current access specifier.
  12201. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12202. SearchDC = PrevTagDecl->getDeclContext();
  12203. AS = AS_none;
  12204. }
  12205. }
  12206. // If we get here we have (another) forward declaration or we
  12207. // have a definition. Just create a new decl.
  12208. } else {
  12209. // If we get here, this is a definition of a new tag type in a nested
  12210. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  12211. // new decl/type. We set PrevDecl to NULL so that the entities
  12212. // have distinct types.
  12213. Previous.clear();
  12214. }
  12215. // If we get here, we're going to create a new Decl. If PrevDecl
  12216. // is non-NULL, it's a definition of the tag declared by
  12217. // PrevDecl. If it's NULL, we have a new definition.
  12218. // Otherwise, PrevDecl is not a tag, but was found with tag
  12219. // lookup. This is only actually possible in C++, where a few
  12220. // things like templates still live in the tag namespace.
  12221. } else {
  12222. // Use a better diagnostic if an elaborated-type-specifier
  12223. // found the wrong kind of type on the first
  12224. // (non-redeclaration) lookup.
  12225. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  12226. !Previous.isForRedeclaration()) {
  12227. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12228. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  12229. << Kind;
  12230. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  12231. Invalid = true;
  12232. // Otherwise, only diagnose if the declaration is in scope.
  12233. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  12234. SS.isNotEmpty() || isMemberSpecialization)) {
  12235. // do nothing
  12236. // Diagnose implicit declarations introduced by elaborated types.
  12237. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12238. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12239. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  12240. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12241. Invalid = true;
  12242. // Otherwise it's a declaration. Call out a particularly common
  12243. // case here.
  12244. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12245. unsigned Kind = 0;
  12246. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  12247. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  12248. << Name << Kind << TND->getUnderlyingType();
  12249. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12250. Invalid = true;
  12251. // Otherwise, diagnose.
  12252. } else {
  12253. // The tag name clashes with something else in the target scope,
  12254. // issue an error and recover by making this tag be anonymous.
  12255. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  12256. notePreviousDefinition(PrevDecl, NameLoc);
  12257. Name = nullptr;
  12258. Invalid = true;
  12259. }
  12260. // The existing declaration isn't relevant to us; we're in a
  12261. // new scope, so clear out the previous declaration.
  12262. Previous.clear();
  12263. }
  12264. }
  12265. CreateNewDecl:
  12266. TagDecl *PrevDecl = nullptr;
  12267. if (Previous.isSingleResult())
  12268. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  12269. // If there is an identifier, use the location of the identifier as the
  12270. // location of the decl, otherwise use the location of the struct/union
  12271. // keyword.
  12272. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12273. // Otherwise, create a new declaration. If there is a previous
  12274. // declaration of the same entity, the two will be linked via
  12275. // PrevDecl.
  12276. TagDecl *New;
  12277. bool IsForwardReference = false;
  12278. if (Kind == TTK_Enum) {
  12279. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12280. // enum X { A, B, C } D; D should chain to X.
  12281. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  12282. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  12283. ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
  12284. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  12285. StdAlignValT = cast<EnumDecl>(New);
  12286. // If this is an undefined enum, warn.
  12287. if (TUK != TUK_Definition && !Invalid) {
  12288. TagDecl *Def;
  12289. if (!EnumUnderlyingIsImplicit &&
  12290. (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  12291. cast<EnumDecl>(New)->isFixed()) {
  12292. // C++0x: 7.2p2: opaque-enum-declaration.
  12293. // Conflicts are diagnosed above. Do nothing.
  12294. }
  12295. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  12296. Diag(Loc, diag::ext_forward_ref_enum_def)
  12297. << New;
  12298. Diag(Def->getLocation(), diag::note_previous_definition);
  12299. } else {
  12300. unsigned DiagID = diag::ext_forward_ref_enum;
  12301. if (getLangOpts().MSVCCompat)
  12302. DiagID = diag::ext_ms_forward_ref_enum;
  12303. else if (getLangOpts().CPlusPlus)
  12304. DiagID = diag::err_forward_ref_enum;
  12305. Diag(Loc, DiagID);
  12306. // If this is a forward-declared reference to an enumeration, make a
  12307. // note of it; we won't actually be introducing the declaration into
  12308. // the declaration context.
  12309. if (TUK == TUK_Reference)
  12310. IsForwardReference = true;
  12311. }
  12312. }
  12313. if (EnumUnderlying) {
  12314. EnumDecl *ED = cast<EnumDecl>(New);
  12315. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12316. ED->setIntegerTypeSourceInfo(TI);
  12317. else
  12318. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  12319. ED->setPromotionType(ED->getIntegerType());
  12320. }
  12321. } else {
  12322. // struct/union/class
  12323. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12324. // struct X { int A; } D; D should chain to X.
  12325. if (getLangOpts().CPlusPlus) {
  12326. // FIXME: Look for a way to use RecordDecl for simple structs.
  12327. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12328. cast_or_null<CXXRecordDecl>(PrevDecl));
  12329. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  12330. StdBadAlloc = cast<CXXRecordDecl>(New);
  12331. } else
  12332. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12333. cast_or_null<RecordDecl>(PrevDecl));
  12334. }
  12335. // C++11 [dcl.type]p3:
  12336. // A type-specifier-seq shall not define a class or enumeration [...].
  12337. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  12338. TUK == TUK_Definition) {
  12339. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  12340. << Context.getTagDeclType(New);
  12341. Invalid = true;
  12342. }
  12343. // Maybe add qualifier info.
  12344. if (SS.isNotEmpty()) {
  12345. if (SS.isSet()) {
  12346. // If this is either a declaration or a definition, check the
  12347. // nested-name-specifier against the current context. We don't do this
  12348. // for explicit specializations, because they have similar checking
  12349. // (with more specific diagnostics) in the call to
  12350. // CheckMemberSpecialization, below.
  12351. if (!isMemberSpecialization &&
  12352. (TUK == TUK_Definition || TUK == TUK_Declaration) &&
  12353. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
  12354. Invalid = true;
  12355. New->setQualifierInfo(SS.getWithLocInContext(Context));
  12356. if (TemplateParameterLists.size() > 0) {
  12357. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  12358. }
  12359. }
  12360. else
  12361. Invalid = true;
  12362. }
  12363. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12364. // Add alignment attributes if necessary; these attributes are checked when
  12365. // the ASTContext lays out the structure.
  12366. //
  12367. // It is important for implementing the correct semantics that this
  12368. // happen here (in ActOnTag). The #pragma pack stack is
  12369. // maintained as a result of parser callbacks which can occur at
  12370. // many points during the parsing of a struct declaration (because
  12371. // the #pragma tokens are effectively skipped over during the
  12372. // parsing of the struct).
  12373. if (TUK == TUK_Definition) {
  12374. AddAlignmentAttributesForRecord(RD);
  12375. AddMsStructLayoutForRecord(RD);
  12376. }
  12377. }
  12378. if (ModulePrivateLoc.isValid()) {
  12379. if (isMemberSpecialization)
  12380. Diag(New->getLocation(), diag::err_module_private_specialization)
  12381. << 2
  12382. << FixItHint::CreateRemoval(ModulePrivateLoc);
  12383. // __module_private__ does not apply to local classes. However, we only
  12384. // diagnose this as an error when the declaration specifiers are
  12385. // freestanding. Here, we just ignore the __module_private__.
  12386. else if (!SearchDC->isFunctionOrMethod())
  12387. New->setModulePrivate();
  12388. }
  12389. // If this is a specialization of a member class (of a class template),
  12390. // check the specialization.
  12391. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  12392. Invalid = true;
  12393. // If we're declaring or defining a tag in function prototype scope in C,
  12394. // note that this type can only be used within the function and add it to
  12395. // the list of decls to inject into the function definition scope.
  12396. if ((Name || Kind == TTK_Enum) &&
  12397. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  12398. if (getLangOpts().CPlusPlus) {
  12399. // C++ [dcl.fct]p6:
  12400. // Types shall not be defined in return or parameter types.
  12401. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  12402. Diag(Loc, diag::err_type_defined_in_param_type)
  12403. << Name;
  12404. Invalid = true;
  12405. }
  12406. } else if (!PrevDecl) {
  12407. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  12408. }
  12409. }
  12410. if (Invalid)
  12411. New->setInvalidDecl();
  12412. // Set the lexical context. If the tag has a C++ scope specifier, the
  12413. // lexical context will be different from the semantic context.
  12414. New->setLexicalDeclContext(CurContext);
  12415. // Mark this as a friend decl if applicable.
  12416. // In Microsoft mode, a friend declaration also acts as a forward
  12417. // declaration so we always pass true to setObjectOfFriendDecl to make
  12418. // the tag name visible.
  12419. if (TUK == TUK_Friend)
  12420. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  12421. // Set the access specifier.
  12422. if (!Invalid && SearchDC->isRecord())
  12423. SetMemberAccessSpecifier(New, PrevDecl, AS);
  12424. if (TUK == TUK_Definition)
  12425. New->startDefinition();
  12426. if (Attr)
  12427. ProcessDeclAttributeList(S, New, Attr);
  12428. AddPragmaAttributes(S, New);
  12429. // If this has an identifier, add it to the scope stack.
  12430. if (TUK == TUK_Friend) {
  12431. // We might be replacing an existing declaration in the lookup tables;
  12432. // if so, borrow its access specifier.
  12433. if (PrevDecl)
  12434. New->setAccess(PrevDecl->getAccess());
  12435. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  12436. DC->makeDeclVisibleInContext(New);
  12437. if (Name) // can be null along some error paths
  12438. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12439. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  12440. } else if (Name) {
  12441. S = getNonFieldDeclScope(S);
  12442. PushOnScopeChains(New, S, !IsForwardReference);
  12443. if (IsForwardReference)
  12444. SearchDC->makeDeclVisibleInContext(New);
  12445. } else {
  12446. CurContext->addDecl(New);
  12447. }
  12448. // If this is the C FILE type, notify the AST context.
  12449. if (IdentifierInfo *II = New->getIdentifier())
  12450. if (!New->isInvalidDecl() &&
  12451. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  12452. II->isStr("FILE"))
  12453. Context.setFILEDecl(New);
  12454. if (PrevDecl)
  12455. mergeDeclAttributes(New, PrevDecl);
  12456. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12457. // record.
  12458. AddPushedVisibilityAttribute(New);
  12459. if (isMemberSpecialization && !New->isInvalidDecl())
  12460. CompleteMemberSpecialization(New, Previous);
  12461. OwnedDecl = true;
  12462. // In C++, don't return an invalid declaration. We can't recover well from
  12463. // the cases where we make the type anonymous.
  12464. if (Invalid && getLangOpts().CPlusPlus) {
  12465. if (New->isBeingDefined())
  12466. if (auto RD = dyn_cast<RecordDecl>(New))
  12467. RD->completeDefinition();
  12468. return nullptr;
  12469. } else {
  12470. return New;
  12471. }
  12472. }
  12473. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  12474. AdjustDeclIfTemplate(TagD);
  12475. TagDecl *Tag = cast<TagDecl>(TagD);
  12476. // Enter the tag context.
  12477. PushDeclContext(S, Tag);
  12478. ActOnDocumentableDecl(TagD);
  12479. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12480. // record.
  12481. AddPushedVisibilityAttribute(Tag);
  12482. }
  12483. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  12484. SkipBodyInfo &SkipBody) {
  12485. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  12486. return false;
  12487. // Make the previous decl visible.
  12488. makeMergedDefinitionVisible(SkipBody.Previous);
  12489. return true;
  12490. }
  12491. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  12492. assert(isa<ObjCContainerDecl>(IDecl) &&
  12493. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  12494. DeclContext *OCD = cast<DeclContext>(IDecl);
  12495. assert(getContainingDC(OCD) == CurContext &&
  12496. "The next DeclContext should be lexically contained in the current one.");
  12497. CurContext = OCD;
  12498. return IDecl;
  12499. }
  12500. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  12501. SourceLocation FinalLoc,
  12502. bool IsFinalSpelledSealed,
  12503. SourceLocation LBraceLoc) {
  12504. AdjustDeclIfTemplate(TagD);
  12505. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  12506. FieldCollector->StartClass();
  12507. if (!Record->getIdentifier())
  12508. return;
  12509. if (FinalLoc.isValid())
  12510. Record->addAttr(new (Context)
  12511. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  12512. // C++ [class]p2:
  12513. // [...] The class-name is also inserted into the scope of the
  12514. // class itself; this is known as the injected-class-name. For
  12515. // purposes of access checking, the injected-class-name is treated
  12516. // as if it were a public member name.
  12517. CXXRecordDecl *InjectedClassName
  12518. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  12519. Record->getLocStart(), Record->getLocation(),
  12520. Record->getIdentifier(),
  12521. /*PrevDecl=*/nullptr,
  12522. /*DelayTypeCreation=*/true);
  12523. Context.getTypeDeclType(InjectedClassName, Record);
  12524. InjectedClassName->setImplicit();
  12525. InjectedClassName->setAccess(AS_public);
  12526. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  12527. InjectedClassName->setDescribedClassTemplate(Template);
  12528. PushOnScopeChains(InjectedClassName, S);
  12529. assert(InjectedClassName->isInjectedClassName() &&
  12530. "Broken injected-class-name");
  12531. }
  12532. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  12533. SourceRange BraceRange) {
  12534. AdjustDeclIfTemplate(TagD);
  12535. TagDecl *Tag = cast<TagDecl>(TagD);
  12536. Tag->setBraceRange(BraceRange);
  12537. // Make sure we "complete" the definition even it is invalid.
  12538. if (Tag->isBeingDefined()) {
  12539. assert(Tag->isInvalidDecl() && "We should already have completed it");
  12540. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12541. RD->completeDefinition();
  12542. }
  12543. if (isa<CXXRecordDecl>(Tag)) {
  12544. FieldCollector->FinishClass();
  12545. }
  12546. // Exit this scope of this tag's definition.
  12547. PopDeclContext();
  12548. if (getCurLexicalContext()->isObjCContainer() &&
  12549. Tag->getDeclContext()->isFileContext())
  12550. Tag->setTopLevelDeclInObjCContainer();
  12551. // Notify the consumer that we've defined a tag.
  12552. if (!Tag->isInvalidDecl())
  12553. Consumer.HandleTagDeclDefinition(Tag);
  12554. }
  12555. void Sema::ActOnObjCContainerFinishDefinition() {
  12556. // Exit this scope of this interface definition.
  12557. PopDeclContext();
  12558. }
  12559. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  12560. assert(DC == CurContext && "Mismatch of container contexts");
  12561. OriginalLexicalContext = DC;
  12562. ActOnObjCContainerFinishDefinition();
  12563. }
  12564. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  12565. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  12566. OriginalLexicalContext = nullptr;
  12567. }
  12568. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  12569. AdjustDeclIfTemplate(TagD);
  12570. TagDecl *Tag = cast<TagDecl>(TagD);
  12571. Tag->setInvalidDecl();
  12572. // Make sure we "complete" the definition even it is invalid.
  12573. if (Tag->isBeingDefined()) {
  12574. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12575. RD->completeDefinition();
  12576. }
  12577. // We're undoing ActOnTagStartDefinition here, not
  12578. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  12579. // the FieldCollector.
  12580. PopDeclContext();
  12581. }
  12582. // Note that FieldName may be null for anonymous bitfields.
  12583. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  12584. IdentifierInfo *FieldName,
  12585. QualType FieldTy, bool IsMsStruct,
  12586. Expr *BitWidth, bool *ZeroWidth) {
  12587. // Default to true; that shouldn't confuse checks for emptiness
  12588. if (ZeroWidth)
  12589. *ZeroWidth = true;
  12590. // C99 6.7.2.1p4 - verify the field type.
  12591. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  12592. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  12593. // Handle incomplete types with specific error.
  12594. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  12595. return ExprError();
  12596. if (FieldName)
  12597. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  12598. << FieldName << FieldTy << BitWidth->getSourceRange();
  12599. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  12600. << FieldTy << BitWidth->getSourceRange();
  12601. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  12602. UPPC_BitFieldWidth))
  12603. return ExprError();
  12604. // If the bit-width is type- or value-dependent, don't try to check
  12605. // it now.
  12606. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  12607. return BitWidth;
  12608. llvm::APSInt Value;
  12609. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  12610. if (ICE.isInvalid())
  12611. return ICE;
  12612. BitWidth = ICE.get();
  12613. if (Value != 0 && ZeroWidth)
  12614. *ZeroWidth = false;
  12615. // Zero-width bitfield is ok for anonymous field.
  12616. if (Value == 0 && FieldName)
  12617. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  12618. if (Value.isSigned() && Value.isNegative()) {
  12619. if (FieldName)
  12620. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  12621. << FieldName << Value.toString(10);
  12622. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  12623. << Value.toString(10);
  12624. }
  12625. if (!FieldTy->isDependentType()) {
  12626. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  12627. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  12628. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  12629. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  12630. // ABI.
  12631. bool CStdConstraintViolation =
  12632. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  12633. bool MSBitfieldViolation =
  12634. Value.ugt(TypeStorageSize) &&
  12635. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  12636. if (CStdConstraintViolation || MSBitfieldViolation) {
  12637. unsigned DiagWidth =
  12638. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  12639. if (FieldName)
  12640. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  12641. << FieldName << (unsigned)Value.getZExtValue()
  12642. << !CStdConstraintViolation << DiagWidth;
  12643. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  12644. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  12645. << DiagWidth;
  12646. }
  12647. // Warn on types where the user might conceivably expect to get all
  12648. // specified bits as value bits: that's all integral types other than
  12649. // 'bool'.
  12650. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  12651. if (FieldName)
  12652. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  12653. << FieldName << (unsigned)Value.getZExtValue()
  12654. << (unsigned)TypeWidth;
  12655. else
  12656. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  12657. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  12658. }
  12659. }
  12660. return BitWidth;
  12661. }
  12662. /// ActOnField - Each field of a C struct/union is passed into this in order
  12663. /// to create a FieldDecl object for it.
  12664. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  12665. Declarator &D, Expr *BitfieldWidth) {
  12666. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  12667. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  12668. /*InitStyle=*/ICIS_NoInit, AS_public);
  12669. return Res;
  12670. }
  12671. /// HandleField - Analyze a field of a C struct or a C++ data member.
  12672. ///
  12673. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  12674. SourceLocation DeclStart,
  12675. Declarator &D, Expr *BitWidth,
  12676. InClassInitStyle InitStyle,
  12677. AccessSpecifier AS) {
  12678. if (D.isDecompositionDeclarator()) {
  12679. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  12680. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  12681. << Decomp.getSourceRange();
  12682. return nullptr;
  12683. }
  12684. IdentifierInfo *II = D.getIdentifier();
  12685. SourceLocation Loc = DeclStart;
  12686. if (II) Loc = D.getIdentifierLoc();
  12687. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12688. QualType T = TInfo->getType();
  12689. if (getLangOpts().CPlusPlus) {
  12690. CheckExtraCXXDefaultArguments(D);
  12691. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  12692. UPPC_DataMemberType)) {
  12693. D.setInvalidType();
  12694. T = Context.IntTy;
  12695. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  12696. }
  12697. }
  12698. // TR 18037 does not allow fields to be declared with address spaces.
  12699. if (T.getQualifiers().hasAddressSpace()) {
  12700. Diag(Loc, diag::err_field_with_address_space);
  12701. D.setInvalidType();
  12702. }
  12703. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  12704. // used as structure or union field: image, sampler, event or block types.
  12705. if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
  12706. T->isSamplerT() || T->isBlockPointerType())) {
  12707. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  12708. D.setInvalidType();
  12709. }
  12710. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  12711. if (D.getDeclSpec().isInlineSpecified())
  12712. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  12713. << getLangOpts().CPlusPlus1z;
  12714. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  12715. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  12716. diag::err_invalid_thread)
  12717. << DeclSpec::getSpecifierName(TSCS);
  12718. // Check to see if this name was declared as a member previously
  12719. NamedDecl *PrevDecl = nullptr;
  12720. LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
  12721. LookupName(Previous, S);
  12722. switch (Previous.getResultKind()) {
  12723. case LookupResult::Found:
  12724. case LookupResult::FoundUnresolvedValue:
  12725. PrevDecl = Previous.getAsSingle<NamedDecl>();
  12726. break;
  12727. case LookupResult::FoundOverloaded:
  12728. PrevDecl = Previous.getRepresentativeDecl();
  12729. break;
  12730. case LookupResult::NotFound:
  12731. case LookupResult::NotFoundInCurrentInstantiation:
  12732. case LookupResult::Ambiguous:
  12733. break;
  12734. }
  12735. Previous.suppressDiagnostics();
  12736. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  12737. // Maybe we will complain about the shadowed template parameter.
  12738. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12739. // Just pretend that we didn't see the previous declaration.
  12740. PrevDecl = nullptr;
  12741. }
  12742. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  12743. PrevDecl = nullptr;
  12744. bool Mutable
  12745. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  12746. SourceLocation TSSL = D.getLocStart();
  12747. FieldDecl *NewFD
  12748. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  12749. TSSL, AS, PrevDecl, &D);
  12750. if (NewFD->isInvalidDecl())
  12751. Record->setInvalidDecl();
  12752. if (D.getDeclSpec().isModulePrivateSpecified())
  12753. NewFD->setModulePrivate();
  12754. if (NewFD->isInvalidDecl() && PrevDecl) {
  12755. // Don't introduce NewFD into scope; there's already something
  12756. // with the same name in the same scope.
  12757. } else if (II) {
  12758. PushOnScopeChains(NewFD, S);
  12759. } else
  12760. Record->addDecl(NewFD);
  12761. return NewFD;
  12762. }
  12763. /// \brief Build a new FieldDecl and check its well-formedness.
  12764. ///
  12765. /// This routine builds a new FieldDecl given the fields name, type,
  12766. /// record, etc. \p PrevDecl should refer to any previous declaration
  12767. /// with the same name and in the same scope as the field to be
  12768. /// created.
  12769. ///
  12770. /// \returns a new FieldDecl.
  12771. ///
  12772. /// \todo The Declarator argument is a hack. It will be removed once
  12773. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  12774. TypeSourceInfo *TInfo,
  12775. RecordDecl *Record, SourceLocation Loc,
  12776. bool Mutable, Expr *BitWidth,
  12777. InClassInitStyle InitStyle,
  12778. SourceLocation TSSL,
  12779. AccessSpecifier AS, NamedDecl *PrevDecl,
  12780. Declarator *D) {
  12781. IdentifierInfo *II = Name.getAsIdentifierInfo();
  12782. bool InvalidDecl = false;
  12783. if (D) InvalidDecl = D->isInvalidType();
  12784. // If we receive a broken type, recover by assuming 'int' and
  12785. // marking this declaration as invalid.
  12786. if (T.isNull()) {
  12787. InvalidDecl = true;
  12788. T = Context.IntTy;
  12789. }
  12790. QualType EltTy = Context.getBaseElementType(T);
  12791. if (!EltTy->isDependentType()) {
  12792. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  12793. // Fields of incomplete type force their record to be invalid.
  12794. Record->setInvalidDecl();
  12795. InvalidDecl = true;
  12796. } else {
  12797. NamedDecl *Def;
  12798. EltTy->isIncompleteType(&Def);
  12799. if (Def && Def->isInvalidDecl()) {
  12800. Record->setInvalidDecl();
  12801. InvalidDecl = true;
  12802. }
  12803. }
  12804. }
  12805. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  12806. if (BitWidth && getLangOpts().OpenCL) {
  12807. Diag(Loc, diag::err_opencl_bitfields);
  12808. InvalidDecl = true;
  12809. }
  12810. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  12811. // than a variably modified type.
  12812. if (!InvalidDecl && T->isVariablyModifiedType()) {
  12813. bool SizeIsNegative;
  12814. llvm::APSInt Oversized;
  12815. TypeSourceInfo *FixedTInfo =
  12816. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  12817. SizeIsNegative,
  12818. Oversized);
  12819. if (FixedTInfo) {
  12820. Diag(Loc, diag::warn_illegal_constant_array_size);
  12821. TInfo = FixedTInfo;
  12822. T = FixedTInfo->getType();
  12823. } else {
  12824. if (SizeIsNegative)
  12825. Diag(Loc, diag::err_typecheck_negative_array_size);
  12826. else if (Oversized.getBoolValue())
  12827. Diag(Loc, diag::err_array_too_large)
  12828. << Oversized.toString(10);
  12829. else
  12830. Diag(Loc, diag::err_typecheck_field_variable_size);
  12831. InvalidDecl = true;
  12832. }
  12833. }
  12834. // Fields can not have abstract class types
  12835. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  12836. diag::err_abstract_type_in_decl,
  12837. AbstractFieldType))
  12838. InvalidDecl = true;
  12839. bool ZeroWidth = false;
  12840. if (InvalidDecl)
  12841. BitWidth = nullptr;
  12842. // If this is declared as a bit-field, check the bit-field.
  12843. if (BitWidth) {
  12844. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  12845. &ZeroWidth).get();
  12846. if (!BitWidth) {
  12847. InvalidDecl = true;
  12848. BitWidth = nullptr;
  12849. ZeroWidth = false;
  12850. }
  12851. }
  12852. // Check that 'mutable' is consistent with the type of the declaration.
  12853. if (!InvalidDecl && Mutable) {
  12854. unsigned DiagID = 0;
  12855. if (T->isReferenceType())
  12856. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  12857. : diag::err_mutable_reference;
  12858. else if (T.isConstQualified())
  12859. DiagID = diag::err_mutable_const;
  12860. if (DiagID) {
  12861. SourceLocation ErrLoc = Loc;
  12862. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  12863. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  12864. Diag(ErrLoc, DiagID);
  12865. if (DiagID != diag::ext_mutable_reference) {
  12866. Mutable = false;
  12867. InvalidDecl = true;
  12868. }
  12869. }
  12870. }
  12871. // C++11 [class.union]p8 (DR1460):
  12872. // At most one variant member of a union may have a
  12873. // brace-or-equal-initializer.
  12874. if (InitStyle != ICIS_NoInit)
  12875. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  12876. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  12877. BitWidth, Mutable, InitStyle);
  12878. if (InvalidDecl)
  12879. NewFD->setInvalidDecl();
  12880. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  12881. Diag(Loc, diag::err_duplicate_member) << II;
  12882. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12883. NewFD->setInvalidDecl();
  12884. }
  12885. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  12886. if (Record->isUnion()) {
  12887. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12888. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12889. if (RDecl->getDefinition()) {
  12890. // C++ [class.union]p1: An object of a class with a non-trivial
  12891. // constructor, a non-trivial copy constructor, a non-trivial
  12892. // destructor, or a non-trivial copy assignment operator
  12893. // cannot be a member of a union, nor can an array of such
  12894. // objects.
  12895. if (CheckNontrivialField(NewFD))
  12896. NewFD->setInvalidDecl();
  12897. }
  12898. }
  12899. // C++ [class.union]p1: If a union contains a member of reference type,
  12900. // the program is ill-formed, except when compiling with MSVC extensions
  12901. // enabled.
  12902. if (EltTy->isReferenceType()) {
  12903. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  12904. diag::ext_union_member_of_reference_type :
  12905. diag::err_union_member_of_reference_type)
  12906. << NewFD->getDeclName() << EltTy;
  12907. if (!getLangOpts().MicrosoftExt)
  12908. NewFD->setInvalidDecl();
  12909. }
  12910. }
  12911. }
  12912. // FIXME: We need to pass in the attributes given an AST
  12913. // representation, not a parser representation.
  12914. if (D) {
  12915. // FIXME: The current scope is almost... but not entirely... correct here.
  12916. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  12917. if (NewFD->hasAttrs())
  12918. CheckAlignasUnderalignment(NewFD);
  12919. }
  12920. // In auto-retain/release, infer strong retension for fields of
  12921. // retainable type.
  12922. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  12923. NewFD->setInvalidDecl();
  12924. if (T.isObjCGCWeak())
  12925. Diag(Loc, diag::warn_attribute_weak_on_field);
  12926. NewFD->setAccess(AS);
  12927. return NewFD;
  12928. }
  12929. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  12930. assert(FD);
  12931. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  12932. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  12933. return false;
  12934. QualType EltTy = Context.getBaseElementType(FD->getType());
  12935. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  12936. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  12937. if (RDecl->getDefinition()) {
  12938. // We check for copy constructors before constructors
  12939. // because otherwise we'll never get complaints about
  12940. // copy constructors.
  12941. CXXSpecialMember member = CXXInvalid;
  12942. // We're required to check for any non-trivial constructors. Since the
  12943. // implicit default constructor is suppressed if there are any
  12944. // user-declared constructors, we just need to check that there is a
  12945. // trivial default constructor and a trivial copy constructor. (We don't
  12946. // worry about move constructors here, since this is a C++98 check.)
  12947. if (RDecl->hasNonTrivialCopyConstructor())
  12948. member = CXXCopyConstructor;
  12949. else if (!RDecl->hasTrivialDefaultConstructor())
  12950. member = CXXDefaultConstructor;
  12951. else if (RDecl->hasNonTrivialCopyAssignment())
  12952. member = CXXCopyAssignment;
  12953. else if (RDecl->hasNonTrivialDestructor())
  12954. member = CXXDestructor;
  12955. if (member != CXXInvalid) {
  12956. if (!getLangOpts().CPlusPlus11 &&
  12957. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  12958. // Objective-C++ ARC: it is an error to have a non-trivial field of
  12959. // a union. However, system headers in Objective-C programs
  12960. // occasionally have Objective-C lifetime objects within unions,
  12961. // and rather than cause the program to fail, we make those
  12962. // members unavailable.
  12963. SourceLocation Loc = FD->getLocation();
  12964. if (getSourceManager().isInSystemHeader(Loc)) {
  12965. if (!FD->hasAttr<UnavailableAttr>())
  12966. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  12967. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  12968. return false;
  12969. }
  12970. }
  12971. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  12972. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  12973. diag::err_illegal_union_or_anon_struct_member)
  12974. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  12975. DiagnoseNontrivial(RDecl, member);
  12976. return !getLangOpts().CPlusPlus11;
  12977. }
  12978. }
  12979. }
  12980. return false;
  12981. }
  12982. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  12983. /// AST enum value.
  12984. static ObjCIvarDecl::AccessControl
  12985. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  12986. switch (ivarVisibility) {
  12987. default: llvm_unreachable("Unknown visitibility kind");
  12988. case tok::objc_private: return ObjCIvarDecl::Private;
  12989. case tok::objc_public: return ObjCIvarDecl::Public;
  12990. case tok::objc_protected: return ObjCIvarDecl::Protected;
  12991. case tok::objc_package: return ObjCIvarDecl::Package;
  12992. }
  12993. }
  12994. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  12995. /// in order to create an IvarDecl object for it.
  12996. Decl *Sema::ActOnIvar(Scope *S,
  12997. SourceLocation DeclStart,
  12998. Declarator &D, Expr *BitfieldWidth,
  12999. tok::ObjCKeywordKind Visibility) {
  13000. IdentifierInfo *II = D.getIdentifier();
  13001. Expr *BitWidth = (Expr*)BitfieldWidth;
  13002. SourceLocation Loc = DeclStart;
  13003. if (II) Loc = D.getIdentifierLoc();
  13004. // FIXME: Unnamed fields can be handled in various different ways, for
  13005. // example, unnamed unions inject all members into the struct namespace!
  13006. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13007. QualType T = TInfo->getType();
  13008. if (BitWidth) {
  13009. // 6.7.2.1p3, 6.7.2.1p4
  13010. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  13011. if (!BitWidth)
  13012. D.setInvalidType();
  13013. } else {
  13014. // Not a bitfield.
  13015. // validate II.
  13016. }
  13017. if (T->isReferenceType()) {
  13018. Diag(Loc, diag::err_ivar_reference_type);
  13019. D.setInvalidType();
  13020. }
  13021. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13022. // than a variably modified type.
  13023. else if (T->isVariablyModifiedType()) {
  13024. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  13025. D.setInvalidType();
  13026. }
  13027. // Get the visibility (access control) for this ivar.
  13028. ObjCIvarDecl::AccessControl ac =
  13029. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  13030. : ObjCIvarDecl::None;
  13031. // Must set ivar's DeclContext to its enclosing interface.
  13032. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  13033. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  13034. return nullptr;
  13035. ObjCContainerDecl *EnclosingContext;
  13036. if (ObjCImplementationDecl *IMPDecl =
  13037. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13038. if (LangOpts.ObjCRuntime.isFragile()) {
  13039. // Case of ivar declared in an implementation. Context is that of its class.
  13040. EnclosingContext = IMPDecl->getClassInterface();
  13041. assert(EnclosingContext && "Implementation has no class interface!");
  13042. }
  13043. else
  13044. EnclosingContext = EnclosingDecl;
  13045. } else {
  13046. if (ObjCCategoryDecl *CDecl =
  13047. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13048. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  13049. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  13050. return nullptr;
  13051. }
  13052. }
  13053. EnclosingContext = EnclosingDecl;
  13054. }
  13055. // Construct the decl.
  13056. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  13057. DeclStart, Loc, II, T,
  13058. TInfo, ac, (Expr *)BitfieldWidth);
  13059. if (II) {
  13060. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  13061. ForRedeclaration);
  13062. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  13063. && !isa<TagDecl>(PrevDecl)) {
  13064. Diag(Loc, diag::err_duplicate_member) << II;
  13065. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13066. NewID->setInvalidDecl();
  13067. }
  13068. }
  13069. // Process attributes attached to the ivar.
  13070. ProcessDeclAttributes(S, NewID, D);
  13071. if (D.isInvalidType())
  13072. NewID->setInvalidDecl();
  13073. // In ARC, infer 'retaining' for ivars of retainable type.
  13074. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  13075. NewID->setInvalidDecl();
  13076. if (D.getDeclSpec().isModulePrivateSpecified())
  13077. NewID->setModulePrivate();
  13078. if (II) {
  13079. // FIXME: When interfaces are DeclContexts, we'll need to add
  13080. // these to the interface.
  13081. S->AddDecl(NewID);
  13082. IdResolver.AddDecl(NewID);
  13083. }
  13084. if (LangOpts.ObjCRuntime.isNonFragile() &&
  13085. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  13086. Diag(Loc, diag::warn_ivars_in_interface);
  13087. return NewID;
  13088. }
  13089. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  13090. /// class and class extensions. For every class \@interface and class
  13091. /// extension \@interface, if the last ivar is a bitfield of any type,
  13092. /// then add an implicit `char :0` ivar to the end of that interface.
  13093. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  13094. SmallVectorImpl<Decl *> &AllIvarDecls) {
  13095. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  13096. return;
  13097. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  13098. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  13099. if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
  13100. return;
  13101. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  13102. if (!ID) {
  13103. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  13104. if (!CD->IsClassExtension())
  13105. return;
  13106. }
  13107. // No need to add this to end of @implementation.
  13108. else
  13109. return;
  13110. }
  13111. // All conditions are met. Add a new bitfield to the tail end of ivars.
  13112. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  13113. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  13114. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  13115. DeclLoc, DeclLoc, nullptr,
  13116. Context.CharTy,
  13117. Context.getTrivialTypeSourceInfo(Context.CharTy,
  13118. DeclLoc),
  13119. ObjCIvarDecl::Private, BW,
  13120. true);
  13121. AllIvarDecls.push_back(Ivar);
  13122. }
  13123. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  13124. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  13125. SourceLocation RBrac, AttributeList *Attr) {
  13126. assert(EnclosingDecl && "missing record or interface decl");
  13127. // If this is an Objective-C @implementation or category and we have
  13128. // new fields here we should reset the layout of the interface since
  13129. // it will now change.
  13130. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  13131. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  13132. switch (DC->getKind()) {
  13133. default: break;
  13134. case Decl::ObjCCategory:
  13135. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  13136. break;
  13137. case Decl::ObjCImplementation:
  13138. Context.
  13139. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  13140. break;
  13141. }
  13142. }
  13143. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  13144. // Start counting up the number of named members; make sure to include
  13145. // members of anonymous structs and unions in the total.
  13146. unsigned NumNamedMembers = 0;
  13147. if (Record) {
  13148. for (const auto *I : Record->decls()) {
  13149. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  13150. if (IFD->getDeclName())
  13151. ++NumNamedMembers;
  13152. }
  13153. }
  13154. // Verify that all the fields are okay.
  13155. SmallVector<FieldDecl*, 32> RecFields;
  13156. bool ObjCFieldLifetimeErrReported = false;
  13157. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  13158. i != end; ++i) {
  13159. FieldDecl *FD = cast<FieldDecl>(*i);
  13160. // Get the type for the field.
  13161. const Type *FDTy = FD->getType().getTypePtr();
  13162. if (!FD->isAnonymousStructOrUnion()) {
  13163. // Remember all fields written by the user.
  13164. RecFields.push_back(FD);
  13165. }
  13166. // If the field is already invalid for some reason, don't emit more
  13167. // diagnostics about it.
  13168. if (FD->isInvalidDecl()) {
  13169. EnclosingDecl->setInvalidDecl();
  13170. continue;
  13171. }
  13172. // C99 6.7.2.1p2:
  13173. // A structure or union shall not contain a member with
  13174. // incomplete or function type (hence, a structure shall not
  13175. // contain an instance of itself, but may contain a pointer to
  13176. // an instance of itself), except that the last member of a
  13177. // structure with more than one named member may have incomplete
  13178. // array type; such a structure (and any union containing,
  13179. // possibly recursively, a member that is such a structure)
  13180. // shall not be a member of a structure or an element of an
  13181. // array.
  13182. if (FDTy->isFunctionType()) {
  13183. // Field declared as a function.
  13184. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  13185. << FD->getDeclName();
  13186. FD->setInvalidDecl();
  13187. EnclosingDecl->setInvalidDecl();
  13188. continue;
  13189. } else if (FDTy->isIncompleteArrayType() && Record &&
  13190. ((i + 1 == Fields.end() && !Record->isUnion()) ||
  13191. ((getLangOpts().MicrosoftExt ||
  13192. getLangOpts().CPlusPlus) &&
  13193. (i + 1 == Fields.end() || Record->isUnion())))) {
  13194. // Flexible array member.
  13195. // Microsoft and g++ is more permissive regarding flexible array.
  13196. // It will accept flexible array in union and also
  13197. // as the sole element of a struct/class.
  13198. unsigned DiagID = 0;
  13199. if (Record->isUnion())
  13200. DiagID = getLangOpts().MicrosoftExt
  13201. ? diag::ext_flexible_array_union_ms
  13202. : getLangOpts().CPlusPlus
  13203. ? diag::ext_flexible_array_union_gnu
  13204. : diag::err_flexible_array_union;
  13205. else if (NumNamedMembers < 1)
  13206. DiagID = getLangOpts().MicrosoftExt
  13207. ? diag::ext_flexible_array_empty_aggregate_ms
  13208. : getLangOpts().CPlusPlus
  13209. ? diag::ext_flexible_array_empty_aggregate_gnu
  13210. : diag::err_flexible_array_empty_aggregate;
  13211. if (DiagID)
  13212. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  13213. << Record->getTagKind();
  13214. // While the layout of types that contain virtual bases is not specified
  13215. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  13216. // virtual bases after the derived members. This would make a flexible
  13217. // array member declared at the end of an object not adjacent to the end
  13218. // of the type.
  13219. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  13220. if (RD->getNumVBases() != 0)
  13221. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  13222. << FD->getDeclName() << Record->getTagKind();
  13223. if (!getLangOpts().C99)
  13224. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  13225. << FD->getDeclName() << Record->getTagKind();
  13226. // If the element type has a non-trivial destructor, we would not
  13227. // implicitly destroy the elements, so disallow it for now.
  13228. //
  13229. // FIXME: GCC allows this. We should probably either implicitly delete
  13230. // the destructor of the containing class, or just allow this.
  13231. QualType BaseElem = Context.getBaseElementType(FD->getType());
  13232. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  13233. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  13234. << FD->getDeclName() << FD->getType();
  13235. FD->setInvalidDecl();
  13236. EnclosingDecl->setInvalidDecl();
  13237. continue;
  13238. }
  13239. // Okay, we have a legal flexible array member at the end of the struct.
  13240. Record->setHasFlexibleArrayMember(true);
  13241. } else if (!FDTy->isDependentType() &&
  13242. RequireCompleteType(FD->getLocation(), FD->getType(),
  13243. diag::err_field_incomplete)) {
  13244. // Incomplete type
  13245. FD->setInvalidDecl();
  13246. EnclosingDecl->setInvalidDecl();
  13247. continue;
  13248. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  13249. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  13250. // A type which contains a flexible array member is considered to be a
  13251. // flexible array member.
  13252. Record->setHasFlexibleArrayMember(true);
  13253. if (!Record->isUnion()) {
  13254. // If this is a struct/class and this is not the last element, reject
  13255. // it. Note that GCC supports variable sized arrays in the middle of
  13256. // structures.
  13257. if (i + 1 != Fields.end())
  13258. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  13259. << FD->getDeclName() << FD->getType();
  13260. else {
  13261. // We support flexible arrays at the end of structs in
  13262. // other structs as an extension.
  13263. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  13264. << FD->getDeclName();
  13265. }
  13266. }
  13267. }
  13268. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  13269. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  13270. diag::err_abstract_type_in_decl,
  13271. AbstractIvarType)) {
  13272. // Ivars can not have abstract class types
  13273. FD->setInvalidDecl();
  13274. }
  13275. if (Record && FDTTy->getDecl()->hasObjectMember())
  13276. Record->setHasObjectMember(true);
  13277. if (Record && FDTTy->getDecl()->hasVolatileMember())
  13278. Record->setHasVolatileMember(true);
  13279. } else if (FDTy->isObjCObjectType()) {
  13280. /// A field cannot be an Objective-c object
  13281. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  13282. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  13283. QualType T = Context.getObjCObjectPointerType(FD->getType());
  13284. FD->setType(T);
  13285. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  13286. Record && !ObjCFieldLifetimeErrReported &&
  13287. (!getLangOpts().CPlusPlus || Record->isUnion())) {
  13288. // It's an error in ARC or Weak if a field has lifetime.
  13289. // We don't want to report this in a system header, though,
  13290. // so we just make the field unavailable.
  13291. // FIXME: that's really not sufficient; we need to make the type
  13292. // itself invalid to, say, initialize or copy.
  13293. QualType T = FD->getType();
  13294. if (T.hasNonTrivialObjCLifetime()) {
  13295. SourceLocation loc = FD->getLocation();
  13296. if (getSourceManager().isInSystemHeader(loc)) {
  13297. if (!FD->hasAttr<UnavailableAttr>()) {
  13298. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13299. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  13300. }
  13301. } else {
  13302. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  13303. << T->isBlockPointerType() << Record->getTagKind();
  13304. }
  13305. ObjCFieldLifetimeErrReported = true;
  13306. }
  13307. } else if (getLangOpts().ObjC1 &&
  13308. getLangOpts().getGC() != LangOptions::NonGC &&
  13309. Record && !Record->hasObjectMember()) {
  13310. if (FD->getType()->isObjCObjectPointerType() ||
  13311. FD->getType().isObjCGCStrong())
  13312. Record->setHasObjectMember(true);
  13313. else if (Context.getAsArrayType(FD->getType())) {
  13314. QualType BaseType = Context.getBaseElementType(FD->getType());
  13315. if (BaseType->isRecordType() &&
  13316. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  13317. Record->setHasObjectMember(true);
  13318. else if (BaseType->isObjCObjectPointerType() ||
  13319. BaseType.isObjCGCStrong())
  13320. Record->setHasObjectMember(true);
  13321. }
  13322. }
  13323. if (Record && FD->getType().isVolatileQualified())
  13324. Record->setHasVolatileMember(true);
  13325. // Keep track of the number of named members.
  13326. if (FD->getIdentifier())
  13327. ++NumNamedMembers;
  13328. }
  13329. // Okay, we successfully defined 'Record'.
  13330. if (Record) {
  13331. bool Completed = false;
  13332. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13333. if (!CXXRecord->isInvalidDecl()) {
  13334. // Set access bits correctly on the directly-declared conversions.
  13335. for (CXXRecordDecl::conversion_iterator
  13336. I = CXXRecord->conversion_begin(),
  13337. E = CXXRecord->conversion_end(); I != E; ++I)
  13338. I.setAccess((*I)->getAccess());
  13339. }
  13340. if (!CXXRecord->isDependentType()) {
  13341. if (CXXRecord->hasUserDeclaredDestructor()) {
  13342. // Adjust user-defined destructor exception spec.
  13343. if (getLangOpts().CPlusPlus11)
  13344. AdjustDestructorExceptionSpec(CXXRecord,
  13345. CXXRecord->getDestructor());
  13346. }
  13347. if (!CXXRecord->isInvalidDecl()) {
  13348. // Add any implicitly-declared members to this class.
  13349. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  13350. // If we have virtual base classes, we may end up finding multiple
  13351. // final overriders for a given virtual function. Check for this
  13352. // problem now.
  13353. if (CXXRecord->getNumVBases()) {
  13354. CXXFinalOverriderMap FinalOverriders;
  13355. CXXRecord->getFinalOverriders(FinalOverriders);
  13356. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  13357. MEnd = FinalOverriders.end();
  13358. M != MEnd; ++M) {
  13359. for (OverridingMethods::iterator SO = M->second.begin(),
  13360. SOEnd = M->second.end();
  13361. SO != SOEnd; ++SO) {
  13362. assert(SO->second.size() > 0 &&
  13363. "Virtual function without overridding functions?");
  13364. if (SO->second.size() == 1)
  13365. continue;
  13366. // C++ [class.virtual]p2:
  13367. // In a derived class, if a virtual member function of a base
  13368. // class subobject has more than one final overrider the
  13369. // program is ill-formed.
  13370. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  13371. << (const NamedDecl *)M->first << Record;
  13372. Diag(M->first->getLocation(),
  13373. diag::note_overridden_virtual_function);
  13374. for (OverridingMethods::overriding_iterator
  13375. OM = SO->second.begin(),
  13376. OMEnd = SO->second.end();
  13377. OM != OMEnd; ++OM)
  13378. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  13379. << (const NamedDecl *)M->first << OM->Method->getParent();
  13380. Record->setInvalidDecl();
  13381. }
  13382. }
  13383. CXXRecord->completeDefinition(&FinalOverriders);
  13384. Completed = true;
  13385. }
  13386. }
  13387. }
  13388. }
  13389. if (!Completed)
  13390. Record->completeDefinition();
  13391. // We may have deferred checking for a deleted destructor. Check now.
  13392. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13393. auto *Dtor = CXXRecord->getDestructor();
  13394. if (Dtor && Dtor->isImplicit() &&
  13395. ShouldDeleteSpecialMember(Dtor, CXXDestructor))
  13396. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  13397. }
  13398. if (Record->hasAttrs()) {
  13399. CheckAlignasUnderalignment(Record);
  13400. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  13401. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  13402. IA->getRange(), IA->getBestCase(),
  13403. IA->getSemanticSpelling());
  13404. }
  13405. // Check if the structure/union declaration is a type that can have zero
  13406. // size in C. For C this is a language extension, for C++ it may cause
  13407. // compatibility problems.
  13408. bool CheckForZeroSize;
  13409. if (!getLangOpts().CPlusPlus) {
  13410. CheckForZeroSize = true;
  13411. } else {
  13412. // For C++ filter out types that cannot be referenced in C code.
  13413. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  13414. CheckForZeroSize =
  13415. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  13416. !CXXRecord->isDependentType() &&
  13417. CXXRecord->isCLike();
  13418. }
  13419. if (CheckForZeroSize) {
  13420. bool ZeroSize = true;
  13421. bool IsEmpty = true;
  13422. unsigned NonBitFields = 0;
  13423. for (RecordDecl::field_iterator I = Record->field_begin(),
  13424. E = Record->field_end();
  13425. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  13426. IsEmpty = false;
  13427. if (I->isUnnamedBitfield()) {
  13428. if (I->getBitWidthValue(Context) > 0)
  13429. ZeroSize = false;
  13430. } else {
  13431. ++NonBitFields;
  13432. QualType FieldType = I->getType();
  13433. if (FieldType->isIncompleteType() ||
  13434. !Context.getTypeSizeInChars(FieldType).isZero())
  13435. ZeroSize = false;
  13436. }
  13437. }
  13438. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  13439. // allowed in C++, but warn if its declaration is inside
  13440. // extern "C" block.
  13441. if (ZeroSize) {
  13442. Diag(RecLoc, getLangOpts().CPlusPlus ?
  13443. diag::warn_zero_size_struct_union_in_extern_c :
  13444. diag::warn_zero_size_struct_union_compat)
  13445. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  13446. }
  13447. // Structs without named members are extension in C (C99 6.7.2.1p7),
  13448. // but are accepted by GCC.
  13449. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  13450. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  13451. diag::ext_no_named_members_in_struct_union)
  13452. << Record->isUnion();
  13453. }
  13454. }
  13455. } else {
  13456. ObjCIvarDecl **ClsFields =
  13457. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  13458. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  13459. ID->setEndOfDefinitionLoc(RBrac);
  13460. // Add ivar's to class's DeclContext.
  13461. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13462. ClsFields[i]->setLexicalDeclContext(ID);
  13463. ID->addDecl(ClsFields[i]);
  13464. }
  13465. // Must enforce the rule that ivars in the base classes may not be
  13466. // duplicates.
  13467. if (ID->getSuperClass())
  13468. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  13469. } else if (ObjCImplementationDecl *IMPDecl =
  13470. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13471. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  13472. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  13473. // Ivar declared in @implementation never belongs to the implementation.
  13474. // Only it is in implementation's lexical context.
  13475. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  13476. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  13477. IMPDecl->setIvarLBraceLoc(LBrac);
  13478. IMPDecl->setIvarRBraceLoc(RBrac);
  13479. } else if (ObjCCategoryDecl *CDecl =
  13480. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13481. // case of ivars in class extension; all other cases have been
  13482. // reported as errors elsewhere.
  13483. // FIXME. Class extension does not have a LocEnd field.
  13484. // CDecl->setLocEnd(RBrac);
  13485. // Add ivar's to class extension's DeclContext.
  13486. // Diagnose redeclaration of private ivars.
  13487. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  13488. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13489. if (IDecl) {
  13490. if (const ObjCIvarDecl *ClsIvar =
  13491. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13492. Diag(ClsFields[i]->getLocation(),
  13493. diag::err_duplicate_ivar_declaration);
  13494. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  13495. continue;
  13496. }
  13497. for (const auto *Ext : IDecl->known_extensions()) {
  13498. if (const ObjCIvarDecl *ClsExtIvar
  13499. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13500. Diag(ClsFields[i]->getLocation(),
  13501. diag::err_duplicate_ivar_declaration);
  13502. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  13503. continue;
  13504. }
  13505. }
  13506. }
  13507. ClsFields[i]->setLexicalDeclContext(CDecl);
  13508. CDecl->addDecl(ClsFields[i]);
  13509. }
  13510. CDecl->setIvarLBraceLoc(LBrac);
  13511. CDecl->setIvarRBraceLoc(RBrac);
  13512. }
  13513. }
  13514. if (Attr)
  13515. ProcessDeclAttributeList(S, Record, Attr);
  13516. }
  13517. /// \brief Determine whether the given integral value is representable within
  13518. /// the given type T.
  13519. static bool isRepresentableIntegerValue(ASTContext &Context,
  13520. llvm::APSInt &Value,
  13521. QualType T) {
  13522. assert(T->isIntegralType(Context) && "Integral type required!");
  13523. unsigned BitWidth = Context.getIntWidth(T);
  13524. if (Value.isUnsigned() || Value.isNonNegative()) {
  13525. if (T->isSignedIntegerOrEnumerationType())
  13526. --BitWidth;
  13527. return Value.getActiveBits() <= BitWidth;
  13528. }
  13529. return Value.getMinSignedBits() <= BitWidth;
  13530. }
  13531. // \brief Given an integral type, return the next larger integral type
  13532. // (or a NULL type of no such type exists).
  13533. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  13534. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  13535. // enum checking below.
  13536. assert(T->isIntegralType(Context) && "Integral type required!");
  13537. const unsigned NumTypes = 4;
  13538. QualType SignedIntegralTypes[NumTypes] = {
  13539. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  13540. };
  13541. QualType UnsignedIntegralTypes[NumTypes] = {
  13542. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  13543. Context.UnsignedLongLongTy
  13544. };
  13545. unsigned BitWidth = Context.getTypeSize(T);
  13546. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  13547. : UnsignedIntegralTypes;
  13548. for (unsigned I = 0; I != NumTypes; ++I)
  13549. if (Context.getTypeSize(Types[I]) > BitWidth)
  13550. return Types[I];
  13551. return QualType();
  13552. }
  13553. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  13554. EnumConstantDecl *LastEnumConst,
  13555. SourceLocation IdLoc,
  13556. IdentifierInfo *Id,
  13557. Expr *Val) {
  13558. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13559. llvm::APSInt EnumVal(IntWidth);
  13560. QualType EltTy;
  13561. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  13562. Val = nullptr;
  13563. if (Val)
  13564. Val = DefaultLvalueConversion(Val).get();
  13565. if (Val) {
  13566. if (Enum->isDependentType() || Val->isTypeDependent())
  13567. EltTy = Context.DependentTy;
  13568. else {
  13569. SourceLocation ExpLoc;
  13570. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  13571. !getLangOpts().MSVCCompat) {
  13572. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  13573. // constant-expression in the enumerator-definition shall be a converted
  13574. // constant expression of the underlying type.
  13575. EltTy = Enum->getIntegerType();
  13576. ExprResult Converted =
  13577. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  13578. CCEK_Enumerator);
  13579. if (Converted.isInvalid())
  13580. Val = nullptr;
  13581. else
  13582. Val = Converted.get();
  13583. } else if (!Val->isValueDependent() &&
  13584. !(Val = VerifyIntegerConstantExpression(Val,
  13585. &EnumVal).get())) {
  13586. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  13587. } else {
  13588. if (Enum->isFixed()) {
  13589. EltTy = Enum->getIntegerType();
  13590. // In Obj-C and Microsoft mode, require the enumeration value to be
  13591. // representable in the underlying type of the enumeration. In C++11,
  13592. // we perform a non-narrowing conversion as part of converted constant
  13593. // expression checking.
  13594. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13595. if (getLangOpts().MSVCCompat) {
  13596. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  13597. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  13598. } else
  13599. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  13600. } else
  13601. Val = ImpCastExprToType(Val, EltTy,
  13602. EltTy->isBooleanType() ?
  13603. CK_IntegralToBoolean : CK_IntegralCast)
  13604. .get();
  13605. } else if (getLangOpts().CPlusPlus) {
  13606. // C++11 [dcl.enum]p5:
  13607. // If the underlying type is not fixed, the type of each enumerator
  13608. // is the type of its initializing value:
  13609. // - If an initializer is specified for an enumerator, the
  13610. // initializing value has the same type as the expression.
  13611. EltTy = Val->getType();
  13612. } else {
  13613. // C99 6.7.2.2p2:
  13614. // The expression that defines the value of an enumeration constant
  13615. // shall be an integer constant expression that has a value
  13616. // representable as an int.
  13617. // Complain if the value is not representable in an int.
  13618. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  13619. Diag(IdLoc, diag::ext_enum_value_not_int)
  13620. << EnumVal.toString(10) << Val->getSourceRange()
  13621. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  13622. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  13623. // Force the type of the expression to 'int'.
  13624. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  13625. }
  13626. EltTy = Val->getType();
  13627. }
  13628. }
  13629. }
  13630. }
  13631. if (!Val) {
  13632. if (Enum->isDependentType())
  13633. EltTy = Context.DependentTy;
  13634. else if (!LastEnumConst) {
  13635. // C++0x [dcl.enum]p5:
  13636. // If the underlying type is not fixed, the type of each enumerator
  13637. // is the type of its initializing value:
  13638. // - If no initializer is specified for the first enumerator, the
  13639. // initializing value has an unspecified integral type.
  13640. //
  13641. // GCC uses 'int' for its unspecified integral type, as does
  13642. // C99 6.7.2.2p3.
  13643. if (Enum->isFixed()) {
  13644. EltTy = Enum->getIntegerType();
  13645. }
  13646. else {
  13647. EltTy = Context.IntTy;
  13648. }
  13649. } else {
  13650. // Assign the last value + 1.
  13651. EnumVal = LastEnumConst->getInitVal();
  13652. ++EnumVal;
  13653. EltTy = LastEnumConst->getType();
  13654. // Check for overflow on increment.
  13655. if (EnumVal < LastEnumConst->getInitVal()) {
  13656. // C++0x [dcl.enum]p5:
  13657. // If the underlying type is not fixed, the type of each enumerator
  13658. // is the type of its initializing value:
  13659. //
  13660. // - Otherwise the type of the initializing value is the same as
  13661. // the type of the initializing value of the preceding enumerator
  13662. // unless the incremented value is not representable in that type,
  13663. // in which case the type is an unspecified integral type
  13664. // sufficient to contain the incremented value. If no such type
  13665. // exists, the program is ill-formed.
  13666. QualType T = getNextLargerIntegralType(Context, EltTy);
  13667. if (T.isNull() || Enum->isFixed()) {
  13668. // There is no integral type larger enough to represent this
  13669. // value. Complain, then allow the value to wrap around.
  13670. EnumVal = LastEnumConst->getInitVal();
  13671. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  13672. ++EnumVal;
  13673. if (Enum->isFixed())
  13674. // When the underlying type is fixed, this is ill-formed.
  13675. Diag(IdLoc, diag::err_enumerator_wrapped)
  13676. << EnumVal.toString(10)
  13677. << EltTy;
  13678. else
  13679. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  13680. << EnumVal.toString(10);
  13681. } else {
  13682. EltTy = T;
  13683. }
  13684. // Retrieve the last enumerator's value, extent that type to the
  13685. // type that is supposed to be large enough to represent the incremented
  13686. // value, then increment.
  13687. EnumVal = LastEnumConst->getInitVal();
  13688. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13689. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  13690. ++EnumVal;
  13691. // If we're not in C++, diagnose the overflow of enumerator values,
  13692. // which in C99 means that the enumerator value is not representable in
  13693. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  13694. // permits enumerator values that are representable in some larger
  13695. // integral type.
  13696. if (!getLangOpts().CPlusPlus && !T.isNull())
  13697. Diag(IdLoc, diag::warn_enum_value_overflow);
  13698. } else if (!getLangOpts().CPlusPlus &&
  13699. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  13700. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  13701. Diag(IdLoc, diag::ext_enum_value_not_int)
  13702. << EnumVal.toString(10) << 1;
  13703. }
  13704. }
  13705. }
  13706. if (!EltTy->isDependentType()) {
  13707. // Make the enumerator value match the signedness and size of the
  13708. // enumerator's type.
  13709. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  13710. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  13711. }
  13712. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  13713. Val, EnumVal);
  13714. }
  13715. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  13716. SourceLocation IILoc) {
  13717. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  13718. !getLangOpts().CPlusPlus)
  13719. return SkipBodyInfo();
  13720. // We have an anonymous enum definition. Look up the first enumerator to
  13721. // determine if we should merge the definition with an existing one and
  13722. // skip the body.
  13723. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  13724. ForRedeclaration);
  13725. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  13726. if (!PrevECD)
  13727. return SkipBodyInfo();
  13728. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  13729. NamedDecl *Hidden;
  13730. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  13731. SkipBodyInfo Skip;
  13732. Skip.Previous = Hidden;
  13733. return Skip;
  13734. }
  13735. return SkipBodyInfo();
  13736. }
  13737. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  13738. SourceLocation IdLoc, IdentifierInfo *Id,
  13739. AttributeList *Attr,
  13740. SourceLocation EqualLoc, Expr *Val) {
  13741. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  13742. EnumConstantDecl *LastEnumConst =
  13743. cast_or_null<EnumConstantDecl>(lastEnumConst);
  13744. // The scope passed in may not be a decl scope. Zip up the scope tree until
  13745. // we find one that is.
  13746. S = getNonFieldDeclScope(S);
  13747. // Verify that there isn't already something declared with this name in this
  13748. // scope.
  13749. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  13750. ForRedeclaration);
  13751. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13752. // Maybe we will complain about the shadowed template parameter.
  13753. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  13754. // Just pretend that we didn't see the previous declaration.
  13755. PrevDecl = nullptr;
  13756. }
  13757. // C++ [class.mem]p15:
  13758. // If T is the name of a class, then each of the following shall have a name
  13759. // different from T:
  13760. // - every enumerator of every member of class T that is an unscoped
  13761. // enumerated type
  13762. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  13763. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  13764. DeclarationNameInfo(Id, IdLoc));
  13765. EnumConstantDecl *New =
  13766. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  13767. if (!New)
  13768. return nullptr;
  13769. if (PrevDecl) {
  13770. // When in C++, we may get a TagDecl with the same name; in this case the
  13771. // enum constant will 'hide' the tag.
  13772. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  13773. "Received TagDecl when not in C++!");
  13774. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
  13775. shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
  13776. if (isa<EnumConstantDecl>(PrevDecl))
  13777. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  13778. else
  13779. Diag(IdLoc, diag::err_redefinition) << Id;
  13780. notePreviousDefinition(PrevDecl, IdLoc);
  13781. return nullptr;
  13782. }
  13783. }
  13784. // Process attributes.
  13785. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  13786. AddPragmaAttributes(S, New);
  13787. // Register this decl in the current scope stack.
  13788. New->setAccess(TheEnumDecl->getAccess());
  13789. PushOnScopeChains(New, S);
  13790. ActOnDocumentableDecl(New);
  13791. return New;
  13792. }
  13793. // Returns true when the enum initial expression does not trigger the
  13794. // duplicate enum warning. A few common cases are exempted as follows:
  13795. // Element2 = Element1
  13796. // Element2 = Element1 + 1
  13797. // Element2 = Element1 - 1
  13798. // Where Element2 and Element1 are from the same enum.
  13799. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  13800. Expr *InitExpr = ECD->getInitExpr();
  13801. if (!InitExpr)
  13802. return true;
  13803. InitExpr = InitExpr->IgnoreImpCasts();
  13804. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  13805. if (!BO->isAdditiveOp())
  13806. return true;
  13807. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  13808. if (!IL)
  13809. return true;
  13810. if (IL->getValue() != 1)
  13811. return true;
  13812. InitExpr = BO->getLHS();
  13813. }
  13814. // This checks if the elements are from the same enum.
  13815. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  13816. if (!DRE)
  13817. return true;
  13818. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  13819. if (!EnumConstant)
  13820. return true;
  13821. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  13822. Enum)
  13823. return true;
  13824. return false;
  13825. }
  13826. namespace {
  13827. struct DupKey {
  13828. int64_t val;
  13829. bool isTombstoneOrEmptyKey;
  13830. DupKey(int64_t val, bool isTombstoneOrEmptyKey)
  13831. : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
  13832. };
  13833. static DupKey GetDupKey(const llvm::APSInt& Val) {
  13834. return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
  13835. false);
  13836. }
  13837. struct DenseMapInfoDupKey {
  13838. static DupKey getEmptyKey() { return DupKey(0, true); }
  13839. static DupKey getTombstoneKey() { return DupKey(1, true); }
  13840. static unsigned getHashValue(const DupKey Key) {
  13841. return (unsigned)(Key.val * 37);
  13842. }
  13843. static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
  13844. return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
  13845. LHS.val == RHS.val;
  13846. }
  13847. };
  13848. } // end anonymous namespace
  13849. // Emits a warning when an element is implicitly set a value that
  13850. // a previous element has already been set to.
  13851. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  13852. EnumDecl *Enum,
  13853. QualType EnumType) {
  13854. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  13855. return;
  13856. // Avoid anonymous enums
  13857. if (!Enum->getIdentifier())
  13858. return;
  13859. // Only check for small enums.
  13860. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  13861. return;
  13862. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  13863. typedef SmallVector<ECDVector *, 3> DuplicatesVector;
  13864. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  13865. typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
  13866. ValueToVectorMap;
  13867. DuplicatesVector DupVector;
  13868. ValueToVectorMap EnumMap;
  13869. // Populate the EnumMap with all values represented by enum constants without
  13870. // an initialier.
  13871. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13872. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
  13873. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  13874. // this constant. Skip this enum since it may be ill-formed.
  13875. if (!ECD) {
  13876. return;
  13877. }
  13878. if (ECD->getInitExpr())
  13879. continue;
  13880. DupKey Key = GetDupKey(ECD->getInitVal());
  13881. DeclOrVector &Entry = EnumMap[Key];
  13882. // First time encountering this value.
  13883. if (Entry.isNull())
  13884. Entry = ECD;
  13885. }
  13886. // Create vectors for any values that has duplicates.
  13887. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13888. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
  13889. if (!ValidDuplicateEnum(ECD, Enum))
  13890. continue;
  13891. DupKey Key = GetDupKey(ECD->getInitVal());
  13892. DeclOrVector& Entry = EnumMap[Key];
  13893. if (Entry.isNull())
  13894. continue;
  13895. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  13896. // Ensure constants are different.
  13897. if (D == ECD)
  13898. continue;
  13899. // Create new vector and push values onto it.
  13900. ECDVector *Vec = new ECDVector();
  13901. Vec->push_back(D);
  13902. Vec->push_back(ECD);
  13903. // Update entry to point to the duplicates vector.
  13904. Entry = Vec;
  13905. // Store the vector somewhere we can consult later for quick emission of
  13906. // diagnostics.
  13907. DupVector.push_back(Vec);
  13908. continue;
  13909. }
  13910. ECDVector *Vec = Entry.get<ECDVector*>();
  13911. // Make sure constants are not added more than once.
  13912. if (*Vec->begin() == ECD)
  13913. continue;
  13914. Vec->push_back(ECD);
  13915. }
  13916. // Emit diagnostics.
  13917. for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
  13918. DupVectorEnd = DupVector.end();
  13919. DupVectorIter != DupVectorEnd; ++DupVectorIter) {
  13920. ECDVector *Vec = *DupVectorIter;
  13921. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  13922. // Emit warning for one enum constant.
  13923. ECDVector::iterator I = Vec->begin();
  13924. S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
  13925. << (*I)->getName() << (*I)->getInitVal().toString(10)
  13926. << (*I)->getSourceRange();
  13927. ++I;
  13928. // Emit one note for each of the remaining enum constants with
  13929. // the same value.
  13930. for (ECDVector::iterator E = Vec->end(); I != E; ++I)
  13931. S.Diag((*I)->getLocation(), diag::note_duplicate_element)
  13932. << (*I)->getName() << (*I)->getInitVal().toString(10)
  13933. << (*I)->getSourceRange();
  13934. delete Vec;
  13935. }
  13936. }
  13937. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  13938. bool AllowMask) const {
  13939. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  13940. assert(ED->isCompleteDefinition() && "expected enum definition");
  13941. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  13942. llvm::APInt &FlagBits = R.first->second;
  13943. if (R.second) {
  13944. for (auto *E : ED->enumerators()) {
  13945. const auto &EVal = E->getInitVal();
  13946. // Only single-bit enumerators introduce new flag values.
  13947. if (EVal.isPowerOf2())
  13948. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  13949. }
  13950. }
  13951. // A value is in a flag enum if either its bits are a subset of the enum's
  13952. // flag bits (the first condition) or we are allowing masks and the same is
  13953. // true of its complement (the second condition). When masks are allowed, we
  13954. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  13955. //
  13956. // While it's true that any value could be used as a mask, the assumption is
  13957. // that a mask will have all of the insignificant bits set. Anything else is
  13958. // likely a logic error.
  13959. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  13960. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  13961. }
  13962. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  13963. Decl *EnumDeclX,
  13964. ArrayRef<Decl *> Elements,
  13965. Scope *S, AttributeList *Attr) {
  13966. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  13967. QualType EnumType = Context.getTypeDeclType(Enum);
  13968. if (Attr)
  13969. ProcessDeclAttributeList(S, Enum, Attr);
  13970. if (Enum->isDependentType()) {
  13971. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13972. EnumConstantDecl *ECD =
  13973. cast_or_null<EnumConstantDecl>(Elements[i]);
  13974. if (!ECD) continue;
  13975. ECD->setType(EnumType);
  13976. }
  13977. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  13978. return;
  13979. }
  13980. // TODO: If the result value doesn't fit in an int, it must be a long or long
  13981. // long value. ISO C does not support this, but GCC does as an extension,
  13982. // emit a warning.
  13983. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13984. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  13985. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  13986. // Verify that all the values are okay, compute the size of the values, and
  13987. // reverse the list.
  13988. unsigned NumNegativeBits = 0;
  13989. unsigned NumPositiveBits = 0;
  13990. // Keep track of whether all elements have type int.
  13991. bool AllElementsInt = true;
  13992. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  13993. EnumConstantDecl *ECD =
  13994. cast_or_null<EnumConstantDecl>(Elements[i]);
  13995. if (!ECD) continue; // Already issued a diagnostic.
  13996. const llvm::APSInt &InitVal = ECD->getInitVal();
  13997. // Keep track of the size of positive and negative values.
  13998. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  13999. NumPositiveBits = std::max(NumPositiveBits,
  14000. (unsigned)InitVal.getActiveBits());
  14001. else
  14002. NumNegativeBits = std::max(NumNegativeBits,
  14003. (unsigned)InitVal.getMinSignedBits());
  14004. // Keep track of whether every enum element has type int (very commmon).
  14005. if (AllElementsInt)
  14006. AllElementsInt = ECD->getType() == Context.IntTy;
  14007. }
  14008. // Figure out the type that should be used for this enum.
  14009. QualType BestType;
  14010. unsigned BestWidth;
  14011. // C++0x N3000 [conv.prom]p3:
  14012. // An rvalue of an unscoped enumeration type whose underlying
  14013. // type is not fixed can be converted to an rvalue of the first
  14014. // of the following types that can represent all the values of
  14015. // the enumeration: int, unsigned int, long int, unsigned long
  14016. // int, long long int, or unsigned long long int.
  14017. // C99 6.4.4.3p2:
  14018. // An identifier declared as an enumeration constant has type int.
  14019. // The C99 rule is modified by a gcc extension
  14020. QualType BestPromotionType;
  14021. bool Packed = Enum->hasAttr<PackedAttr>();
  14022. // -fshort-enums is the equivalent to specifying the packed attribute on all
  14023. // enum definitions.
  14024. if (LangOpts.ShortEnums)
  14025. Packed = true;
  14026. if (Enum->isFixed()) {
  14027. BestType = Enum->getIntegerType();
  14028. if (BestType->isPromotableIntegerType())
  14029. BestPromotionType = Context.getPromotedIntegerType(BestType);
  14030. else
  14031. BestPromotionType = BestType;
  14032. BestWidth = Context.getIntWidth(BestType);
  14033. }
  14034. else if (NumNegativeBits) {
  14035. // If there is a negative value, figure out the smallest integer type (of
  14036. // int/long/longlong) that fits.
  14037. // If it's packed, check also if it fits a char or a short.
  14038. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  14039. BestType = Context.SignedCharTy;
  14040. BestWidth = CharWidth;
  14041. } else if (Packed && NumNegativeBits <= ShortWidth &&
  14042. NumPositiveBits < ShortWidth) {
  14043. BestType = Context.ShortTy;
  14044. BestWidth = ShortWidth;
  14045. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  14046. BestType = Context.IntTy;
  14047. BestWidth = IntWidth;
  14048. } else {
  14049. BestWidth = Context.getTargetInfo().getLongWidth();
  14050. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  14051. BestType = Context.LongTy;
  14052. } else {
  14053. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14054. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  14055. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  14056. BestType = Context.LongLongTy;
  14057. }
  14058. }
  14059. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  14060. } else {
  14061. // If there is no negative value, figure out the smallest type that fits
  14062. // all of the enumerator values.
  14063. // If it's packed, check also if it fits a char or a short.
  14064. if (Packed && NumPositiveBits <= CharWidth) {
  14065. BestType = Context.UnsignedCharTy;
  14066. BestPromotionType = Context.IntTy;
  14067. BestWidth = CharWidth;
  14068. } else if (Packed && NumPositiveBits <= ShortWidth) {
  14069. BestType = Context.UnsignedShortTy;
  14070. BestPromotionType = Context.IntTy;
  14071. BestWidth = ShortWidth;
  14072. } else if (NumPositiveBits <= IntWidth) {
  14073. BestType = Context.UnsignedIntTy;
  14074. BestWidth = IntWidth;
  14075. BestPromotionType
  14076. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14077. ? Context.UnsignedIntTy : Context.IntTy;
  14078. } else if (NumPositiveBits <=
  14079. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  14080. BestType = Context.UnsignedLongTy;
  14081. BestPromotionType
  14082. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14083. ? Context.UnsignedLongTy : Context.LongTy;
  14084. } else {
  14085. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14086. assert(NumPositiveBits <= BestWidth &&
  14087. "How could an initializer get larger than ULL?");
  14088. BestType = Context.UnsignedLongLongTy;
  14089. BestPromotionType
  14090. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14091. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  14092. }
  14093. }
  14094. // Loop over all of the enumerator constants, changing their types to match
  14095. // the type of the enum if needed.
  14096. for (auto *D : Elements) {
  14097. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  14098. if (!ECD) continue; // Already issued a diagnostic.
  14099. // Standard C says the enumerators have int type, but we allow, as an
  14100. // extension, the enumerators to be larger than int size. If each
  14101. // enumerator value fits in an int, type it as an int, otherwise type it the
  14102. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  14103. // that X has type 'int', not 'unsigned'.
  14104. // Determine whether the value fits into an int.
  14105. llvm::APSInt InitVal = ECD->getInitVal();
  14106. // If it fits into an integer type, force it. Otherwise force it to match
  14107. // the enum decl type.
  14108. QualType NewTy;
  14109. unsigned NewWidth;
  14110. bool NewSign;
  14111. if (!getLangOpts().CPlusPlus &&
  14112. !Enum->isFixed() &&
  14113. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  14114. NewTy = Context.IntTy;
  14115. NewWidth = IntWidth;
  14116. NewSign = true;
  14117. } else if (ECD->getType() == BestType) {
  14118. // Already the right type!
  14119. if (getLangOpts().CPlusPlus)
  14120. // C++ [dcl.enum]p4: Following the closing brace of an
  14121. // enum-specifier, each enumerator has the type of its
  14122. // enumeration.
  14123. ECD->setType(EnumType);
  14124. continue;
  14125. } else {
  14126. NewTy = BestType;
  14127. NewWidth = BestWidth;
  14128. NewSign = BestType->isSignedIntegerOrEnumerationType();
  14129. }
  14130. // Adjust the APSInt value.
  14131. InitVal = InitVal.extOrTrunc(NewWidth);
  14132. InitVal.setIsSigned(NewSign);
  14133. ECD->setInitVal(InitVal);
  14134. // Adjust the Expr initializer and type.
  14135. if (ECD->getInitExpr() &&
  14136. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  14137. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  14138. CK_IntegralCast,
  14139. ECD->getInitExpr(),
  14140. /*base paths*/ nullptr,
  14141. VK_RValue));
  14142. if (getLangOpts().CPlusPlus)
  14143. // C++ [dcl.enum]p4: Following the closing brace of an
  14144. // enum-specifier, each enumerator has the type of its
  14145. // enumeration.
  14146. ECD->setType(EnumType);
  14147. else
  14148. ECD->setType(NewTy);
  14149. }
  14150. Enum->completeDefinition(BestType, BestPromotionType,
  14151. NumPositiveBits, NumNegativeBits);
  14152. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  14153. if (Enum->isClosedFlag()) {
  14154. for (Decl *D : Elements) {
  14155. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  14156. if (!ECD) continue; // Already issued a diagnostic.
  14157. llvm::APSInt InitVal = ECD->getInitVal();
  14158. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  14159. !IsValueInFlagEnum(Enum, InitVal, true))
  14160. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  14161. << ECD << Enum;
  14162. }
  14163. }
  14164. // Now that the enum type is defined, ensure it's not been underaligned.
  14165. if (Enum->hasAttrs())
  14166. CheckAlignasUnderalignment(Enum);
  14167. }
  14168. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  14169. SourceLocation StartLoc,
  14170. SourceLocation EndLoc) {
  14171. StringLiteral *AsmString = cast<StringLiteral>(expr);
  14172. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  14173. AsmString, StartLoc,
  14174. EndLoc);
  14175. CurContext->addDecl(New);
  14176. return New;
  14177. }
  14178. static void checkModuleImportContext(Sema &S, Module *M,
  14179. SourceLocation ImportLoc, DeclContext *DC,
  14180. bool FromInclude = false) {
  14181. SourceLocation ExternCLoc;
  14182. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  14183. switch (LSD->getLanguage()) {
  14184. case LinkageSpecDecl::lang_c:
  14185. if (ExternCLoc.isInvalid())
  14186. ExternCLoc = LSD->getLocStart();
  14187. break;
  14188. case LinkageSpecDecl::lang_cxx:
  14189. break;
  14190. }
  14191. DC = LSD->getParent();
  14192. }
  14193. while (isa<LinkageSpecDecl>(DC))
  14194. DC = DC->getParent();
  14195. if (!isa<TranslationUnitDecl>(DC)) {
  14196. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  14197. ? diag::ext_module_import_not_at_top_level_noop
  14198. : diag::err_module_import_not_at_top_level_fatal)
  14199. << M->getFullModuleName() << DC;
  14200. S.Diag(cast<Decl>(DC)->getLocStart(),
  14201. diag::note_module_import_not_at_top_level) << DC;
  14202. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  14203. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  14204. << M->getFullModuleName();
  14205. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  14206. }
  14207. }
  14208. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
  14209. SourceLocation ModuleLoc,
  14210. ModuleDeclKind MDK,
  14211. ModuleIdPath Path) {
  14212. assert(getLangOpts().ModulesTS &&
  14213. "should only have module decl in modules TS");
  14214. // A module implementation unit requires that we are not compiling a module
  14215. // of any kind. A module interface unit requires that we are not compiling a
  14216. // module map.
  14217. switch (getLangOpts().getCompilingModule()) {
  14218. case LangOptions::CMK_None:
  14219. // It's OK to compile a module interface as a normal translation unit.
  14220. break;
  14221. case LangOptions::CMK_ModuleInterface:
  14222. if (MDK != ModuleDeclKind::Implementation)
  14223. break;
  14224. // We were asked to compile a module interface unit but this is a module
  14225. // implementation unit. That indicates the 'export' is missing.
  14226. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  14227. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  14228. break;
  14229. case LangOptions::CMK_ModuleMap:
  14230. Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
  14231. return nullptr;
  14232. }
  14233. // FIXME: Most of this work should be done by the preprocessor rather than
  14234. // here, in order to support macro import.
  14235. // Flatten the dots in a module name. Unlike Clang's hierarchical module map
  14236. // modules, the dots here are just another character that can appear in a
  14237. // module name.
  14238. std::string ModuleName;
  14239. for (auto &Piece : Path) {
  14240. if (!ModuleName.empty())
  14241. ModuleName += ".";
  14242. ModuleName += Piece.first->getName();
  14243. }
  14244. // FIXME: If we've already seen a module-declaration, report an error.
  14245. // If a module name was explicitly specified on the command line, it must be
  14246. // correct.
  14247. if (!getLangOpts().CurrentModule.empty() &&
  14248. getLangOpts().CurrentModule != ModuleName) {
  14249. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  14250. << SourceRange(Path.front().second, Path.back().second)
  14251. << getLangOpts().CurrentModule;
  14252. return nullptr;
  14253. }
  14254. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  14255. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  14256. Module *Mod;
  14257. assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
  14258. switch (MDK) {
  14259. case ModuleDeclKind::Module: {
  14260. // We can't have parsed or imported a definition of this module or parsed a
  14261. // module map defining it already.
  14262. if (auto *M = Map.findModule(ModuleName)) {
  14263. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  14264. if (M->DefinitionLoc.isValid())
  14265. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  14266. else if (const auto *FE = M->getASTFile())
  14267. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  14268. << FE->getName();
  14269. return nullptr;
  14270. }
  14271. // Create a Module for the module that we're defining.
  14272. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14273. ModuleScopes.front().Module);
  14274. assert(Mod && "module creation should not fail");
  14275. break;
  14276. }
  14277. case ModuleDeclKind::Partition:
  14278. // FIXME: Check we are in a submodule of the named module.
  14279. return nullptr;
  14280. case ModuleDeclKind::Implementation:
  14281. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  14282. PP.getIdentifierInfo(ModuleName), Path[0].second);
  14283. Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
  14284. /*IsIncludeDirective=*/false);
  14285. if (!Mod)
  14286. return nullptr;
  14287. break;
  14288. }
  14289. // Switch from the global module to the named module.
  14290. ModuleScopes.back().Module = Mod;
  14291. VisibleModules.setVisible(Mod, ModuleLoc);
  14292. // From now on, we have an owning module for all declarations we see.
  14293. // However, those declarations are module-private unless explicitly
  14294. // exported.
  14295. auto *TU = Context.getTranslationUnitDecl();
  14296. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  14297. TU->setLocalOwningModule(Mod);
  14298. // FIXME: Create a ModuleDecl.
  14299. return nullptr;
  14300. }
  14301. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  14302. SourceLocation ImportLoc,
  14303. ModuleIdPath Path) {
  14304. Module *Mod =
  14305. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  14306. /*IsIncludeDirective=*/false);
  14307. if (!Mod)
  14308. return true;
  14309. VisibleModules.setVisible(Mod, ImportLoc);
  14310. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  14311. // FIXME: we should support importing a submodule within a different submodule
  14312. // of the same top-level module. Until we do, make it an error rather than
  14313. // silently ignoring the import.
  14314. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  14315. // warn on a redundant import of the current module?
  14316. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  14317. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  14318. Diag(ImportLoc, getLangOpts().isCompilingModule()
  14319. ? diag::err_module_self_import
  14320. : diag::err_module_import_in_implementation)
  14321. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  14322. SmallVector<SourceLocation, 2> IdentifierLocs;
  14323. Module *ModCheck = Mod;
  14324. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  14325. // If we've run out of module parents, just drop the remaining identifiers.
  14326. // We need the length to be consistent.
  14327. if (!ModCheck)
  14328. break;
  14329. ModCheck = ModCheck->Parent;
  14330. IdentifierLocs.push_back(Path[I].second);
  14331. }
  14332. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14333. ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
  14334. Mod, IdentifierLocs);
  14335. if (!ModuleScopes.empty())
  14336. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  14337. TU->addDecl(Import);
  14338. return Import;
  14339. }
  14340. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14341. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14342. BuildModuleInclude(DirectiveLoc, Mod);
  14343. }
  14344. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14345. // Determine whether we're in the #include buffer for a module. The #includes
  14346. // in that buffer do not qualify as module imports; they're just an
  14347. // implementation detail of us building the module.
  14348. //
  14349. // FIXME: Should we even get ActOnModuleInclude calls for those?
  14350. bool IsInModuleIncludes =
  14351. TUKind == TU_Module &&
  14352. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  14353. bool ShouldAddImport = !IsInModuleIncludes;
  14354. // If this module import was due to an inclusion directive, create an
  14355. // implicit import declaration to capture it in the AST.
  14356. if (ShouldAddImport) {
  14357. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14358. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14359. DirectiveLoc, Mod,
  14360. DirectiveLoc);
  14361. if (!ModuleScopes.empty())
  14362. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  14363. TU->addDecl(ImportD);
  14364. Consumer.HandleImplicitImportDecl(ImportD);
  14365. }
  14366. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  14367. VisibleModules.setVisible(Mod, DirectiveLoc);
  14368. }
  14369. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  14370. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14371. ModuleScopes.push_back({});
  14372. ModuleScopes.back().Module = Mod;
  14373. if (getLangOpts().ModulesLocalVisibility)
  14374. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  14375. VisibleModules.setVisible(Mod, DirectiveLoc);
  14376. // The enclosing context is now part of this module.
  14377. // FIXME: Consider creating a child DeclContext to hold the entities
  14378. // lexically within the module.
  14379. if (getLangOpts().trackLocalOwningModule()) {
  14380. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14381. cast<Decl>(DC)->setModuleOwnershipKind(
  14382. getLangOpts().ModulesLocalVisibility
  14383. ? Decl::ModuleOwnershipKind::VisibleWhenImported
  14384. : Decl::ModuleOwnershipKind::Visible);
  14385. cast<Decl>(DC)->setLocalOwningModule(Mod);
  14386. }
  14387. }
  14388. }
  14389. void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
  14390. if (getLangOpts().ModulesLocalVisibility) {
  14391. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  14392. // Leaving a module hides namespace names, so our visible namespace cache
  14393. // is now out of date.
  14394. VisibleNamespaceCache.clear();
  14395. }
  14396. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  14397. "left the wrong module scope");
  14398. ModuleScopes.pop_back();
  14399. // We got to the end of processing a local module. Create an
  14400. // ImportDecl as we would for an imported module.
  14401. FileID File = getSourceManager().getFileID(EomLoc);
  14402. SourceLocation DirectiveLoc;
  14403. if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
  14404. // We reached the end of a #included module header. Use the #include loc.
  14405. assert(File != getSourceManager().getMainFileID() &&
  14406. "end of submodule in main source file");
  14407. DirectiveLoc = getSourceManager().getIncludeLoc(File);
  14408. } else {
  14409. // We reached an EOM pragma. Use the pragma location.
  14410. DirectiveLoc = EomLoc;
  14411. }
  14412. BuildModuleInclude(DirectiveLoc, Mod);
  14413. // Any further declarations are in whatever module we returned to.
  14414. if (getLangOpts().trackLocalOwningModule()) {
  14415. // The parser guarantees that this is the same context that we entered
  14416. // the module within.
  14417. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14418. cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
  14419. if (!getCurrentModule())
  14420. cast<Decl>(DC)->setModuleOwnershipKind(
  14421. Decl::ModuleOwnershipKind::Unowned);
  14422. }
  14423. }
  14424. }
  14425. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  14426. Module *Mod) {
  14427. // Bail if we're not allowed to implicitly import a module here.
  14428. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
  14429. VisibleModules.isVisible(Mod))
  14430. return;
  14431. // Create the implicit import declaration.
  14432. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14433. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14434. Loc, Mod, Loc);
  14435. TU->addDecl(ImportD);
  14436. Consumer.HandleImplicitImportDecl(ImportD);
  14437. // Make the module visible.
  14438. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  14439. VisibleModules.setVisible(Mod, Loc);
  14440. }
  14441. /// We have parsed the start of an export declaration, including the '{'
  14442. /// (if present).
  14443. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  14444. SourceLocation LBraceLoc) {
  14445. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  14446. // C++ Modules TS draft:
  14447. // An export-declaration shall appear in the purview of a module other than
  14448. // the global module.
  14449. if (ModuleScopes.empty() ||
  14450. ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
  14451. Diag(ExportLoc, diag::err_export_not_in_module_interface);
  14452. // An export-declaration [...] shall not contain more than one
  14453. // export keyword.
  14454. //
  14455. // The intent here is that an export-declaration cannot appear within another
  14456. // export-declaration.
  14457. if (D->isExported())
  14458. Diag(ExportLoc, diag::err_export_within_export);
  14459. CurContext->addDecl(D);
  14460. PushDeclContext(S, D);
  14461. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  14462. return D;
  14463. }
  14464. /// Complete the definition of an export declaration.
  14465. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  14466. auto *ED = cast<ExportDecl>(D);
  14467. if (RBraceLoc.isValid())
  14468. ED->setRBraceLoc(RBraceLoc);
  14469. // FIXME: Diagnose export of internal-linkage declaration (including
  14470. // anonymous namespace).
  14471. PopDeclContext();
  14472. return D;
  14473. }
  14474. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  14475. IdentifierInfo* AliasName,
  14476. SourceLocation PragmaLoc,
  14477. SourceLocation NameLoc,
  14478. SourceLocation AliasNameLoc) {
  14479. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  14480. LookupOrdinaryName);
  14481. AsmLabelAttr *Attr =
  14482. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  14483. // If a declaration that:
  14484. // 1) declares a function or a variable
  14485. // 2) has external linkage
  14486. // already exists, add a label attribute to it.
  14487. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14488. if (isDeclExternC(PrevDecl))
  14489. PrevDecl->addAttr(Attr);
  14490. else
  14491. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  14492. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  14493. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  14494. } else
  14495. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  14496. }
  14497. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  14498. SourceLocation PragmaLoc,
  14499. SourceLocation NameLoc) {
  14500. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  14501. if (PrevDecl) {
  14502. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  14503. } else {
  14504. (void)WeakUndeclaredIdentifiers.insert(
  14505. std::pair<IdentifierInfo*,WeakInfo>
  14506. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  14507. }
  14508. }
  14509. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  14510. IdentifierInfo* AliasName,
  14511. SourceLocation PragmaLoc,
  14512. SourceLocation NameLoc,
  14513. SourceLocation AliasNameLoc) {
  14514. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  14515. LookupOrdinaryName);
  14516. WeakInfo W = WeakInfo(Name, NameLoc);
  14517. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14518. if (!PrevDecl->hasAttr<AliasAttr>())
  14519. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  14520. DeclApplyPragmaWeak(TUScope, ND, W);
  14521. } else {
  14522. (void)WeakUndeclaredIdentifiers.insert(
  14523. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  14524. }
  14525. }
  14526. Decl *Sema::getObjCDeclContext() const {
  14527. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  14528. }