SemaDecl.cpp 687 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CommentDiagnostic.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/NonTrivialTypeVisitor.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 final : 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. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  96. return std::make_unique<TypeNameValidatorCCC>(*this);
  97. }
  98. private:
  99. bool AllowInvalidDecl;
  100. bool WantClassName;
  101. bool AllowTemplates;
  102. bool AllowNonTemplates;
  103. };
  104. } // end anonymous namespace
  105. /// Determine whether the token kind starts a simple-type-specifier.
  106. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  107. switch (Kind) {
  108. // FIXME: Take into account the current language when deciding whether a
  109. // token kind is a valid type specifier
  110. case tok::kw_short:
  111. case tok::kw_long:
  112. case tok::kw___int64:
  113. case tok::kw___int128:
  114. case tok::kw_signed:
  115. case tok::kw_unsigned:
  116. case tok::kw_void:
  117. case tok::kw_char:
  118. case tok::kw_int:
  119. case tok::kw_half:
  120. case tok::kw_float:
  121. case tok::kw_double:
  122. case tok::kw__Float16:
  123. case tok::kw___float128:
  124. case tok::kw_wchar_t:
  125. case tok::kw_bool:
  126. case tok::kw___underlying_type:
  127. case tok::kw___auto_type:
  128. return true;
  129. case tok::annot_typename:
  130. case tok::kw_char16_t:
  131. case tok::kw_char32_t:
  132. case tok::kw_typeof:
  133. case tok::annot_decltype:
  134. case tok::kw_decltype:
  135. return getLangOpts().CPlusPlus;
  136. case tok::kw_char8_t:
  137. return getLangOpts().Char8;
  138. default:
  139. break;
  140. }
  141. return false;
  142. }
  143. namespace {
  144. enum class UnqualifiedTypeNameLookupResult {
  145. NotFound,
  146. FoundNonType,
  147. FoundType
  148. };
  149. } // end anonymous namespace
  150. /// Tries to perform unqualified lookup of the type decls in bases for
  151. /// dependent class.
  152. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  153. /// type decl, \a FoundType if only type decls are found.
  154. static UnqualifiedTypeNameLookupResult
  155. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  156. SourceLocation NameLoc,
  157. const CXXRecordDecl *RD) {
  158. if (!RD->hasDefinition())
  159. return UnqualifiedTypeNameLookupResult::NotFound;
  160. // Look for type decls in base classes.
  161. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  162. UnqualifiedTypeNameLookupResult::NotFound;
  163. for (const auto &Base : RD->bases()) {
  164. const CXXRecordDecl *BaseRD = nullptr;
  165. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  166. BaseRD = BaseTT->getAsCXXRecordDecl();
  167. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  168. // Look for type decls in dependent base classes that have known primary
  169. // templates.
  170. if (!TST || !TST->isDependentType())
  171. continue;
  172. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  173. if (!TD)
  174. continue;
  175. if (auto *BasePrimaryTemplate =
  176. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  177. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  178. BaseRD = BasePrimaryTemplate;
  179. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  180. if (const ClassTemplatePartialSpecializationDecl *PS =
  181. CTD->findPartialSpecialization(Base.getType()))
  182. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  183. BaseRD = PS;
  184. }
  185. }
  186. }
  187. if (BaseRD) {
  188. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  189. if (!isa<TypeDecl>(ND))
  190. return UnqualifiedTypeNameLookupResult::FoundNonType;
  191. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  192. }
  193. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  194. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  195. case UnqualifiedTypeNameLookupResult::FoundNonType:
  196. return UnqualifiedTypeNameLookupResult::FoundNonType;
  197. case UnqualifiedTypeNameLookupResult::FoundType:
  198. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  199. break;
  200. case UnqualifiedTypeNameLookupResult::NotFound:
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. return FoundTypeDecl;
  207. }
  208. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  209. const IdentifierInfo &II,
  210. SourceLocation NameLoc) {
  211. // Lookup in the parent class template context, if any.
  212. const CXXRecordDecl *RD = nullptr;
  213. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  214. UnqualifiedTypeNameLookupResult::NotFound;
  215. for (DeclContext *DC = S.CurContext;
  216. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  217. DC = DC->getParent()) {
  218. // Look for type decls in dependent base classes that have known primary
  219. // templates.
  220. RD = dyn_cast<CXXRecordDecl>(DC);
  221. if (RD && RD->getDescribedClassTemplate())
  222. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  223. }
  224. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  225. return nullptr;
  226. // We found some types in dependent base classes. Recover as if the user
  227. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  228. // lookup during template instantiation.
  229. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  230. ASTContext &Context = S.Context;
  231. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  232. cast<Type>(Context.getRecordType(RD)));
  233. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  234. CXXScopeSpec SS;
  235. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  236. TypeLocBuilder Builder;
  237. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  238. DepTL.setNameLoc(NameLoc);
  239. DepTL.setElaboratedKeywordLoc(SourceLocation());
  240. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  241. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  242. }
  243. /// If the identifier refers to a type name within this scope,
  244. /// return the declaration of that type.
  245. ///
  246. /// This routine performs ordinary name lookup of the identifier II
  247. /// within the given scope, with optional C++ scope specifier SS, to
  248. /// determine whether the name refers to a type. If so, returns an
  249. /// opaque pointer (actually a QualType) corresponding to that
  250. /// type. Otherwise, returns NULL.
  251. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  252. Scope *S, CXXScopeSpec *SS,
  253. bool isClassName, bool HasTrailingDot,
  254. ParsedType ObjectTypePtr,
  255. bool IsCtorOrDtorName,
  256. bool WantNontrivialTypeSourceInfo,
  257. bool IsClassTemplateDeductionContext,
  258. IdentifierInfo **CorrectedII) {
  259. // FIXME: Consider allowing this outside C++1z mode as an extension.
  260. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  261. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  262. !isClassName && !HasTrailingDot;
  263. // Determine where we will perform name lookup.
  264. DeclContext *LookupCtx = nullptr;
  265. if (ObjectTypePtr) {
  266. QualType ObjectType = ObjectTypePtr.get();
  267. if (ObjectType->isRecordType())
  268. LookupCtx = computeDeclContext(ObjectType);
  269. } else if (SS && SS->isNotEmpty()) {
  270. LookupCtx = computeDeclContext(*SS, false);
  271. if (!LookupCtx) {
  272. if (isDependentScopeSpecifier(*SS)) {
  273. // C++ [temp.res]p3:
  274. // A qualified-id that refers to a type and in which the
  275. // nested-name-specifier depends on a template-parameter (14.6.2)
  276. // shall be prefixed by the keyword typename to indicate that the
  277. // qualified-id denotes a type, forming an
  278. // elaborated-type-specifier (7.1.5.3).
  279. //
  280. // We therefore do not perform any name lookup if the result would
  281. // refer to a member of an unknown specialization.
  282. if (!isClassName && !IsCtorOrDtorName)
  283. return nullptr;
  284. // We know from the grammar that this name refers to a type,
  285. // so build a dependent node to describe the type.
  286. if (WantNontrivialTypeSourceInfo)
  287. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  288. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  289. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  290. II, NameLoc);
  291. return ParsedType::make(T);
  292. }
  293. return nullptr;
  294. }
  295. if (!LookupCtx->isDependentContext() &&
  296. RequireCompleteDeclContext(*SS, LookupCtx))
  297. return nullptr;
  298. }
  299. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  300. // lookup for class-names.
  301. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  302. LookupOrdinaryName;
  303. LookupResult Result(*this, &II, NameLoc, Kind);
  304. if (LookupCtx) {
  305. // Perform "qualified" name lookup into the declaration context we
  306. // computed, which is either the type of the base of a member access
  307. // expression or the declaration context associated with a prior
  308. // nested-name-specifier.
  309. LookupQualifiedName(Result, LookupCtx);
  310. if (ObjectTypePtr && Result.empty()) {
  311. // C++ [basic.lookup.classref]p3:
  312. // If the unqualified-id is ~type-name, the type-name is looked up
  313. // in the context of the entire postfix-expression. If the type T of
  314. // the object expression is of a class type C, the type-name is also
  315. // looked up in the scope of class C. At least one of the lookups shall
  316. // find a name that refers to (possibly cv-qualified) T.
  317. LookupName(Result, S);
  318. }
  319. } else {
  320. // Perform unqualified name lookup.
  321. LookupName(Result, S);
  322. // For unqualified lookup in a class template in MSVC mode, look into
  323. // dependent base classes where the primary class template is known.
  324. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  325. if (ParsedType TypeInBase =
  326. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  327. return TypeInBase;
  328. }
  329. }
  330. NamedDecl *IIDecl = nullptr;
  331. switch (Result.getResultKind()) {
  332. case LookupResult::NotFound:
  333. case LookupResult::NotFoundInCurrentInstantiation:
  334. if (CorrectedII) {
  335. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  336. AllowDeducedTemplate);
  337. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  338. S, SS, CCC, CTK_ErrorRecovery);
  339. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  340. TemplateTy Template;
  341. bool MemberOfUnknownSpecialization;
  342. UnqualifiedId TemplateName;
  343. TemplateName.setIdentifier(NewII, NameLoc);
  344. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  345. CXXScopeSpec NewSS, *NewSSPtr = SS;
  346. if (SS && NNS) {
  347. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  348. NewSSPtr = &NewSS;
  349. }
  350. if (Correction && (NNS || NewII != &II) &&
  351. // Ignore a correction to a template type as the to-be-corrected
  352. // identifier is not a template (typo correction for template names
  353. // is handled elsewhere).
  354. !(getLangOpts().CPlusPlus && NewSSPtr &&
  355. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  356. Template, MemberOfUnknownSpecialization))) {
  357. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  358. isClassName, HasTrailingDot, ObjectTypePtr,
  359. IsCtorOrDtorName,
  360. WantNontrivialTypeSourceInfo,
  361. IsClassTemplateDeductionContext);
  362. if (Ty) {
  363. diagnoseTypo(Correction,
  364. PDiag(diag::err_unknown_type_or_class_name_suggest)
  365. << Result.getLookupName() << isClassName);
  366. if (SS && NNS)
  367. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  368. *CorrectedII = NewII;
  369. return Ty;
  370. }
  371. }
  372. }
  373. // If typo correction failed or was not performed, fall through
  374. LLVM_FALLTHROUGH;
  375. case LookupResult::FoundOverloaded:
  376. case LookupResult::FoundUnresolvedValue:
  377. Result.suppressDiagnostics();
  378. return nullptr;
  379. case LookupResult::Ambiguous:
  380. // Recover from type-hiding ambiguities by hiding the type. We'll
  381. // do the lookup again when looking for an object, and we can
  382. // diagnose the error then. If we don't do this, then the error
  383. // about hiding the type will be immediately followed by an error
  384. // that only makes sense if the identifier was treated like a type.
  385. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  386. Result.suppressDiagnostics();
  387. return nullptr;
  388. }
  389. // Look to see if we have a type anywhere in the list of results.
  390. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  391. Res != ResEnd; ++Res) {
  392. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  393. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  394. if (!IIDecl ||
  395. (*Res)->getLocation().getRawEncoding() <
  396. IIDecl->getLocation().getRawEncoding())
  397. IIDecl = *Res;
  398. }
  399. }
  400. if (!IIDecl) {
  401. // None of the entities we found is a type, so there is no way
  402. // to even assume that the result is a type. In this case, don't
  403. // complain about the ambiguity. The parser will either try to
  404. // perform this lookup again (e.g., as an object name), which
  405. // will produce the ambiguity, or will complain that it expected
  406. // a type name.
  407. Result.suppressDiagnostics();
  408. return nullptr;
  409. }
  410. // We found a type within the ambiguous lookup; diagnose the
  411. // ambiguity and then return that type. This might be the right
  412. // answer, or it might not be, but it suppresses any attempt to
  413. // perform the name lookup again.
  414. break;
  415. case LookupResult::Found:
  416. IIDecl = Result.getFoundDecl();
  417. break;
  418. }
  419. assert(IIDecl && "Didn't find decl");
  420. QualType T;
  421. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  422. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  423. // instead names the constructors of the class, except when naming a class.
  424. // This is ill-formed when we're not actually forming a ctor or dtor name.
  425. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  426. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  427. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  428. FoundRD->isInjectedClassName() &&
  429. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  430. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  431. << &II << /*Type*/1;
  432. DiagnoseUseOfDecl(IIDecl, NameLoc);
  433. T = Context.getTypeDeclType(TD);
  434. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  435. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  436. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  437. if (!HasTrailingDot)
  438. T = Context.getObjCInterfaceType(IDecl);
  439. } else if (AllowDeducedTemplate) {
  440. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  441. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  442. QualType(), false);
  443. }
  444. if (T.isNull()) {
  445. // If it's not plausibly a type, suppress diagnostics.
  446. Result.suppressDiagnostics();
  447. return nullptr;
  448. }
  449. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  450. // constructor or destructor name (in such a case, the scope specifier
  451. // will be attached to the enclosing Expr or Decl node).
  452. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  453. !isa<ObjCInterfaceDecl>(IIDecl)) {
  454. if (WantNontrivialTypeSourceInfo) {
  455. // Construct a type with type-source information.
  456. TypeLocBuilder Builder;
  457. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  458. T = getElaboratedType(ETK_None, *SS, T);
  459. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  460. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  461. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  462. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  463. } else {
  464. T = getElaboratedType(ETK_None, *SS, T);
  465. }
  466. }
  467. return ParsedType::make(T);
  468. }
  469. // Builds a fake NNS for the given decl context.
  470. static NestedNameSpecifier *
  471. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  472. for (;; DC = DC->getLookupParent()) {
  473. DC = DC->getPrimaryContext();
  474. auto *ND = dyn_cast<NamespaceDecl>(DC);
  475. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  476. return NestedNameSpecifier::Create(Context, nullptr, ND);
  477. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  478. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  479. RD->getTypeForDecl());
  480. else if (isa<TranslationUnitDecl>(DC))
  481. return NestedNameSpecifier::GlobalSpecifier(Context);
  482. }
  483. llvm_unreachable("something isn't in TU scope?");
  484. }
  485. /// Find the parent class with dependent bases of the innermost enclosing method
  486. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  487. /// up allowing unqualified dependent type names at class-level, which MSVC
  488. /// correctly rejects.
  489. static const CXXRecordDecl *
  490. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  491. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  492. DC = DC->getPrimaryContext();
  493. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  494. if (MD->getParent()->hasAnyDependentBases())
  495. return MD->getParent();
  496. }
  497. return nullptr;
  498. }
  499. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  500. SourceLocation NameLoc,
  501. bool IsTemplateTypeArg) {
  502. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  503. NestedNameSpecifier *NNS = nullptr;
  504. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  505. // If we weren't able to parse a default template argument, delay lookup
  506. // until instantiation time by making a non-dependent DependentTypeName. We
  507. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  508. // lookup is retried.
  509. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  510. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  511. // name specifiers.
  512. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  513. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  514. } else if (const CXXRecordDecl *RD =
  515. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  516. // Build a DependentNameType that will perform lookup into RD at
  517. // instantiation time.
  518. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  519. RD->getTypeForDecl());
  520. // Diagnose that this identifier was undeclared, and retry the lookup during
  521. // template instantiation.
  522. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  523. << RD;
  524. } else {
  525. // This is not a situation that we should recover from.
  526. return ParsedType();
  527. }
  528. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  529. // Build type location information. We synthesized the qualifier, so we have
  530. // to build a fake NestedNameSpecifierLoc.
  531. NestedNameSpecifierLocBuilder NNSLocBuilder;
  532. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  533. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  534. TypeLocBuilder Builder;
  535. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  536. DepTL.setNameLoc(NameLoc);
  537. DepTL.setElaboratedKeywordLoc(SourceLocation());
  538. DepTL.setQualifierLoc(QualifierLoc);
  539. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  540. }
  541. /// isTagName() - This method is called *for error recovery purposes only*
  542. /// to determine if the specified name is a valid tag name ("struct foo"). If
  543. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  544. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  545. /// cases in C where the user forgot to specify the tag.
  546. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  547. // Do a tag name lookup in this scope.
  548. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  549. LookupName(R, S, false);
  550. R.suppressDiagnostics();
  551. if (R.getResultKind() == LookupResult::Found)
  552. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  553. switch (TD->getTagKind()) {
  554. case TTK_Struct: return DeclSpec::TST_struct;
  555. case TTK_Interface: return DeclSpec::TST_interface;
  556. case TTK_Union: return DeclSpec::TST_union;
  557. case TTK_Class: return DeclSpec::TST_class;
  558. case TTK_Enum: return DeclSpec::TST_enum;
  559. }
  560. }
  561. return DeclSpec::TST_unspecified;
  562. }
  563. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  564. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  565. /// then downgrade the missing typename error to a warning.
  566. /// This is needed for MSVC compatibility; Example:
  567. /// @code
  568. /// template<class T> class A {
  569. /// public:
  570. /// typedef int TYPE;
  571. /// };
  572. /// template<class T> class B : public A<T> {
  573. /// public:
  574. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  575. /// };
  576. /// @endcode
  577. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  578. if (CurContext->isRecord()) {
  579. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  580. return true;
  581. const Type *Ty = SS->getScopeRep()->getAsType();
  582. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  583. for (const auto &Base : RD->bases())
  584. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  585. return true;
  586. return S->isFunctionPrototypeScope();
  587. }
  588. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  589. }
  590. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  591. SourceLocation IILoc,
  592. Scope *S,
  593. CXXScopeSpec *SS,
  594. ParsedType &SuggestedType,
  595. bool IsTemplateName) {
  596. // Don't report typename errors for editor placeholders.
  597. if (II->isEditorPlaceholder())
  598. return;
  599. // We don't have anything to suggest (yet).
  600. SuggestedType = nullptr;
  601. // There may have been a typo in the name of the type. Look up typo
  602. // results, in case we have something that we can suggest.
  603. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  604. /*AllowTemplates=*/IsTemplateName,
  605. /*AllowNonTemplates=*/!IsTemplateName);
  606. if (TypoCorrection Corrected =
  607. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  608. CCC, CTK_ErrorRecovery)) {
  609. // FIXME: Support error recovery for the template-name case.
  610. bool CanRecover = !IsTemplateName;
  611. if (Corrected.isKeyword()) {
  612. // We corrected to a keyword.
  613. diagnoseTypo(Corrected,
  614. PDiag(IsTemplateName ? diag::err_no_template_suggest
  615. : diag::err_unknown_typename_suggest)
  616. << II);
  617. II = Corrected.getCorrectionAsIdentifierInfo();
  618. } else {
  619. // We found a similarly-named type or interface; suggest that.
  620. if (!SS || !SS->isSet()) {
  621. diagnoseTypo(Corrected,
  622. PDiag(IsTemplateName ? diag::err_no_template_suggest
  623. : diag::err_unknown_typename_suggest)
  624. << II, CanRecover);
  625. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  626. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  627. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  628. II->getName().equals(CorrectedStr);
  629. diagnoseTypo(Corrected,
  630. PDiag(IsTemplateName
  631. ? diag::err_no_member_template_suggest
  632. : diag::err_unknown_nested_typename_suggest)
  633. << II << DC << DroppedSpecifier << SS->getRange(),
  634. CanRecover);
  635. } else {
  636. llvm_unreachable("could not have corrected a typo here");
  637. }
  638. if (!CanRecover)
  639. return;
  640. CXXScopeSpec tmpSS;
  641. if (Corrected.getCorrectionSpecifier())
  642. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  643. SourceRange(IILoc));
  644. // FIXME: Support class template argument deduction here.
  645. SuggestedType =
  646. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  647. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  648. /*IsCtorOrDtorName=*/false,
  649. /*WantNontrivialTypeSourceInfo=*/true);
  650. }
  651. return;
  652. }
  653. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  654. // See if II is a class template that the user forgot to pass arguments to.
  655. UnqualifiedId Name;
  656. Name.setIdentifier(II, IILoc);
  657. CXXScopeSpec EmptySS;
  658. TemplateTy TemplateResult;
  659. bool MemberOfUnknownSpecialization;
  660. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  661. Name, nullptr, true, TemplateResult,
  662. MemberOfUnknownSpecialization) == TNK_Type_template) {
  663. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  664. return;
  665. }
  666. }
  667. // FIXME: Should we move the logic that tries to recover from a missing tag
  668. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  669. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  670. Diag(IILoc, IsTemplateName ? diag::err_no_template
  671. : diag::err_unknown_typename)
  672. << II;
  673. else if (DeclContext *DC = computeDeclContext(*SS, false))
  674. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  675. : diag::err_typename_nested_not_found)
  676. << II << DC << SS->getRange();
  677. else if (isDependentScopeSpecifier(*SS)) {
  678. unsigned DiagID = diag::err_typename_missing;
  679. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  680. DiagID = diag::ext_typename_missing;
  681. Diag(SS->getRange().getBegin(), DiagID)
  682. << SS->getScopeRep() << II->getName()
  683. << SourceRange(SS->getRange().getBegin(), IILoc)
  684. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  685. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  686. *SS, *II, IILoc).get();
  687. } else {
  688. assert(SS && SS->isInvalid() &&
  689. "Invalid scope specifier has already been diagnosed");
  690. }
  691. }
  692. /// Determine whether the given result set contains either a type name
  693. /// or
  694. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  695. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  696. NextToken.is(tok::less);
  697. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  698. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  699. return true;
  700. if (CheckTemplate && isa<TemplateDecl>(*I))
  701. return true;
  702. }
  703. return false;
  704. }
  705. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  706. Scope *S, CXXScopeSpec &SS,
  707. IdentifierInfo *&Name,
  708. SourceLocation NameLoc) {
  709. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  710. SemaRef.LookupParsedName(R, S, &SS);
  711. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  712. StringRef FixItTagName;
  713. switch (Tag->getTagKind()) {
  714. case TTK_Class:
  715. FixItTagName = "class ";
  716. break;
  717. case TTK_Enum:
  718. FixItTagName = "enum ";
  719. break;
  720. case TTK_Struct:
  721. FixItTagName = "struct ";
  722. break;
  723. case TTK_Interface:
  724. FixItTagName = "__interface ";
  725. break;
  726. case TTK_Union:
  727. FixItTagName = "union ";
  728. break;
  729. }
  730. StringRef TagName = FixItTagName.drop_back();
  731. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  732. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  733. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  734. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  735. I != IEnd; ++I)
  736. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  737. << Name << TagName;
  738. // Replace lookup results with just the tag decl.
  739. Result.clear(Sema::LookupTagName);
  740. SemaRef.LookupParsedName(Result, S, &SS);
  741. return true;
  742. }
  743. return false;
  744. }
  745. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  746. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  747. QualType T, SourceLocation NameLoc) {
  748. ASTContext &Context = S.Context;
  749. TypeLocBuilder Builder;
  750. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  751. T = S.getElaboratedType(ETK_None, SS, T);
  752. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  753. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  754. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  755. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  756. }
  757. Sema::NameClassification
  758. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  759. SourceLocation NameLoc, const Token &NextToken,
  760. bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
  761. DeclarationNameInfo NameInfo(Name, NameLoc);
  762. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  763. if (NextToken.is(tok::coloncolon)) {
  764. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  765. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  766. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  767. isCurrentClassName(*Name, S, &SS)) {
  768. // Per [class.qual]p2, this names the constructors of SS, not the
  769. // injected-class-name. We don't have a classification for that.
  770. // There's not much point caching this result, since the parser
  771. // will reject it later.
  772. return NameClassification::Unknown();
  773. }
  774. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  775. LookupParsedName(Result, S, &SS, !CurMethod);
  776. // For unqualified lookup in a class template in MSVC mode, look into
  777. // dependent base classes where the primary class template is known.
  778. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  779. if (ParsedType TypeInBase =
  780. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  781. return TypeInBase;
  782. }
  783. // Perform lookup for Objective-C instance variables (including automatically
  784. // synthesized instance variables), if we're in an Objective-C method.
  785. // FIXME: This lookup really, really needs to be folded in to the normal
  786. // unqualified lookup mechanism.
  787. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  788. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  789. if (E.get() || E.isInvalid())
  790. return E;
  791. }
  792. bool SecondTry = false;
  793. bool IsFilteredTemplateName = false;
  794. Corrected:
  795. switch (Result.getResultKind()) {
  796. case LookupResult::NotFound:
  797. // If an unqualified-id is followed by a '(', then we have a function
  798. // call.
  799. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  800. // In C++, this is an ADL-only call.
  801. // FIXME: Reference?
  802. if (getLangOpts().CPlusPlus)
  803. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  804. // C90 6.3.2.2:
  805. // If the expression that precedes the parenthesized argument list in a
  806. // function call consists solely of an identifier, and if no
  807. // declaration is visible for this identifier, the identifier is
  808. // implicitly declared exactly as if, in the innermost block containing
  809. // the function call, the declaration
  810. //
  811. // extern int identifier ();
  812. //
  813. // appeared.
  814. //
  815. // We also allow this in C99 as an extension.
  816. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  817. Result.addDecl(D);
  818. Result.resolveKind();
  819. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  820. }
  821. }
  822. if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
  823. // In C++20 onwards, this could be an ADL-only call to a function
  824. // template, and we're required to assume that this is a template name.
  825. //
  826. // FIXME: Find a way to still do typo correction in this case.
  827. TemplateName Template =
  828. Context.getAssumedTemplateName(NameInfo.getName());
  829. return NameClassification::UndeclaredTemplate(Template);
  830. }
  831. // In C, we first see whether there is a tag type by the same name, in
  832. // which case it's likely that the user just forgot to write "enum",
  833. // "struct", or "union".
  834. if (!getLangOpts().CPlusPlus && !SecondTry &&
  835. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  836. break;
  837. }
  838. // Perform typo correction to determine if there is another name that is
  839. // close to this name.
  840. if (!SecondTry && CCC) {
  841. SecondTry = true;
  842. if (TypoCorrection Corrected =
  843. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  844. &SS, *CCC, CTK_ErrorRecovery)) {
  845. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  846. unsigned QualifiedDiag = diag::err_no_member_suggest;
  847. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  848. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  849. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  850. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  851. UnqualifiedDiag = diag::err_no_template_suggest;
  852. QualifiedDiag = diag::err_no_member_template_suggest;
  853. } else if (UnderlyingFirstDecl &&
  854. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  855. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  856. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  857. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  858. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  859. }
  860. if (SS.isEmpty()) {
  861. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  862. } else {// FIXME: is this even reachable? Test it.
  863. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  864. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  865. Name->getName().equals(CorrectedStr);
  866. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  867. << Name << computeDeclContext(SS, false)
  868. << DroppedSpecifier << SS.getRange());
  869. }
  870. // Update the name, so that the caller has the new name.
  871. Name = Corrected.getCorrectionAsIdentifierInfo();
  872. // Typo correction corrected to a keyword.
  873. if (Corrected.isKeyword())
  874. return Name;
  875. // Also update the LookupResult...
  876. // FIXME: This should probably go away at some point
  877. Result.clear();
  878. Result.setLookupName(Corrected.getCorrection());
  879. if (FirstDecl)
  880. Result.addDecl(FirstDecl);
  881. // If we found an Objective-C instance variable, let
  882. // LookupInObjCMethod build the appropriate expression to
  883. // reference the ivar.
  884. // FIXME: This is a gross hack.
  885. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  886. Result.clear();
  887. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  888. return E;
  889. }
  890. goto Corrected;
  891. }
  892. }
  893. // We failed to correct; just fall through and let the parser deal with it.
  894. Result.suppressDiagnostics();
  895. return NameClassification::Unknown();
  896. case LookupResult::NotFoundInCurrentInstantiation: {
  897. // We performed name lookup into the current instantiation, and there were
  898. // dependent bases, so we treat this result the same way as any other
  899. // dependent nested-name-specifier.
  900. // C++ [temp.res]p2:
  901. // A name used in a template declaration or definition and that is
  902. // dependent on a template-parameter is assumed not to name a type
  903. // unless the applicable name lookup finds a type name or the name is
  904. // qualified by the keyword typename.
  905. //
  906. // FIXME: If the next token is '<', we might want to ask the parser to
  907. // perform some heroics to see if we actually have a
  908. // template-argument-list, which would indicate a missing 'template'
  909. // keyword here.
  910. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  911. NameInfo, IsAddressOfOperand,
  912. /*TemplateArgs=*/nullptr);
  913. }
  914. case LookupResult::Found:
  915. case LookupResult::FoundOverloaded:
  916. case LookupResult::FoundUnresolvedValue:
  917. break;
  918. case LookupResult::Ambiguous:
  919. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  920. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  921. /*AllowDependent=*/false)) {
  922. // C++ [temp.local]p3:
  923. // A lookup that finds an injected-class-name (10.2) can result in an
  924. // ambiguity in certain cases (for example, if it is found in more than
  925. // one base class). If all of the injected-class-names that are found
  926. // refer to specializations of the same class template, and if the name
  927. // is followed by a template-argument-list, the reference refers to the
  928. // class template itself and not a specialization thereof, and is not
  929. // ambiguous.
  930. //
  931. // This filtering can make an ambiguous result into an unambiguous one,
  932. // so try again after filtering out template names.
  933. FilterAcceptableTemplateNames(Result);
  934. if (!Result.isAmbiguous()) {
  935. IsFilteredTemplateName = true;
  936. break;
  937. }
  938. }
  939. // Diagnose the ambiguity and return an error.
  940. return NameClassification::Error();
  941. }
  942. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  943. (IsFilteredTemplateName ||
  944. hasAnyAcceptableTemplateNames(
  945. Result, /*AllowFunctionTemplates=*/true,
  946. /*AllowDependent=*/false,
  947. /*AllowNonTemplateFunctions*/ !SS.isSet() &&
  948. getLangOpts().CPlusPlus2a))) {
  949. // C++ [temp.names]p3:
  950. // After name lookup (3.4) finds that a name is a template-name or that
  951. // an operator-function-id or a literal- operator-id refers to a set of
  952. // overloaded functions any member of which is a function template if
  953. // this is followed by a <, the < is always taken as the delimiter of a
  954. // template-argument-list and never as the less-than operator.
  955. // C++2a [temp.names]p2:
  956. // A name is also considered to refer to a template if it is an
  957. // unqualified-id followed by a < and name lookup finds either one
  958. // or more functions or finds nothing.
  959. if (!IsFilteredTemplateName)
  960. FilterAcceptableTemplateNames(Result);
  961. bool IsFunctionTemplate;
  962. bool IsVarTemplate;
  963. TemplateName Template;
  964. if (Result.end() - Result.begin() > 1) {
  965. IsFunctionTemplate = true;
  966. Template = Context.getOverloadedTemplateName(Result.begin(),
  967. Result.end());
  968. } else if (!Result.empty()) {
  969. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  970. *Result.begin(), /*AllowFunctionTemplates=*/true,
  971. /*AllowDependent=*/false));
  972. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  973. IsVarTemplate = isa<VarTemplateDecl>(TD);
  974. if (SS.isSet() && !SS.isInvalid())
  975. Template =
  976. Context.getQualifiedTemplateName(SS.getScopeRep(),
  977. /*TemplateKeyword=*/false, TD);
  978. else
  979. Template = TemplateName(TD);
  980. } else {
  981. // All results were non-template functions. This is a function template
  982. // name.
  983. IsFunctionTemplate = true;
  984. Template = Context.getAssumedTemplateName(NameInfo.getName());
  985. }
  986. if (IsFunctionTemplate) {
  987. // Function templates always go through overload resolution, at which
  988. // point we'll perform the various checks (e.g., accessibility) we need
  989. // to based on which function we selected.
  990. Result.suppressDiagnostics();
  991. return NameClassification::FunctionTemplate(Template);
  992. }
  993. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  994. : NameClassification::TypeTemplate(Template);
  995. }
  996. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  997. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  998. DiagnoseUseOfDecl(Type, NameLoc);
  999. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  1000. QualType T = Context.getTypeDeclType(Type);
  1001. if (SS.isNotEmpty())
  1002. return buildNestedType(*this, SS, T, NameLoc);
  1003. return ParsedType::make(T);
  1004. }
  1005. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1006. if (!Class) {
  1007. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1008. if (ObjCCompatibleAliasDecl *Alias =
  1009. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1010. Class = Alias->getClassInterface();
  1011. }
  1012. if (Class) {
  1013. DiagnoseUseOfDecl(Class, NameLoc);
  1014. if (NextToken.is(tok::period)) {
  1015. // Interface. <something> is parsed as a property reference expression.
  1016. // Just return "unknown" as a fall-through for now.
  1017. Result.suppressDiagnostics();
  1018. return NameClassification::Unknown();
  1019. }
  1020. QualType T = Context.getObjCInterfaceType(Class);
  1021. return ParsedType::make(T);
  1022. }
  1023. // We can have a type template here if we're classifying a template argument.
  1024. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1025. !isa<VarTemplateDecl>(FirstDecl))
  1026. return NameClassification::TypeTemplate(
  1027. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1028. // Check for a tag type hidden by a non-type decl in a few cases where it
  1029. // seems likely a type is wanted instead of the non-type that was found.
  1030. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1031. if ((NextToken.is(tok::identifier) ||
  1032. (NextIsOp &&
  1033. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1034. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1035. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1036. DiagnoseUseOfDecl(Type, NameLoc);
  1037. QualType T = Context.getTypeDeclType(Type);
  1038. if (SS.isNotEmpty())
  1039. return buildNestedType(*this, SS, T, NameLoc);
  1040. return ParsedType::make(T);
  1041. }
  1042. if (FirstDecl->isCXXClassMember())
  1043. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1044. nullptr, S);
  1045. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1046. return BuildDeclarationNameExpr(SS, Result, ADL);
  1047. }
  1048. Sema::TemplateNameKindForDiagnostics
  1049. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1050. auto *TD = Name.getAsTemplateDecl();
  1051. if (!TD)
  1052. return TemplateNameKindForDiagnostics::DependentTemplate;
  1053. if (isa<ClassTemplateDecl>(TD))
  1054. return TemplateNameKindForDiagnostics::ClassTemplate;
  1055. if (isa<FunctionTemplateDecl>(TD))
  1056. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1057. if (isa<VarTemplateDecl>(TD))
  1058. return TemplateNameKindForDiagnostics::VarTemplate;
  1059. if (isa<TypeAliasTemplateDecl>(TD))
  1060. return TemplateNameKindForDiagnostics::AliasTemplate;
  1061. if (isa<TemplateTemplateParmDecl>(TD))
  1062. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1063. if (isa<ConceptDecl>(TD))
  1064. return TemplateNameKindForDiagnostics::Concept;
  1065. return TemplateNameKindForDiagnostics::DependentTemplate;
  1066. }
  1067. // Determines the context to return to after temporarily entering a
  1068. // context. This depends in an unnecessarily complicated way on the
  1069. // exact ordering of callbacks from the parser.
  1070. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1071. // Functions defined inline within classes aren't parsed until we've
  1072. // finished parsing the top-level class, so the top-level class is
  1073. // the context we'll need to return to.
  1074. // A Lambda call operator whose parent is a class must not be treated
  1075. // as an inline member function. A Lambda can be used legally
  1076. // either as an in-class member initializer or a default argument. These
  1077. // are parsed once the class has been marked complete and so the containing
  1078. // context would be the nested class (when the lambda is defined in one);
  1079. // If the class is not complete, then the lambda is being used in an
  1080. // ill-formed fashion (such as to specify the width of a bit-field, or
  1081. // in an array-bound) - in which case we still want to return the
  1082. // lexically containing DC (which could be a nested class).
  1083. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1084. DC = DC->getLexicalParent();
  1085. // A function not defined within a class will always return to its
  1086. // lexical context.
  1087. if (!isa<CXXRecordDecl>(DC))
  1088. return DC;
  1089. // A C++ inline method/friend is parsed *after* the topmost class
  1090. // it was declared in is fully parsed ("complete"); the topmost
  1091. // class is the context we need to return to.
  1092. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1093. DC = RD;
  1094. // Return the declaration context of the topmost class the inline method is
  1095. // declared in.
  1096. return DC;
  1097. }
  1098. return DC->getLexicalParent();
  1099. }
  1100. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1101. assert(getContainingDC(DC) == CurContext &&
  1102. "The next DeclContext should be lexically contained in the current one.");
  1103. CurContext = DC;
  1104. S->setEntity(DC);
  1105. }
  1106. void Sema::PopDeclContext() {
  1107. assert(CurContext && "DeclContext imbalance!");
  1108. CurContext = getContainingDC(CurContext);
  1109. assert(CurContext && "Popped translation unit!");
  1110. }
  1111. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1112. Decl *D) {
  1113. // Unlike PushDeclContext, the context to which we return is not necessarily
  1114. // the containing DC of TD, because the new context will be some pre-existing
  1115. // TagDecl definition instead of a fresh one.
  1116. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1117. CurContext = cast<TagDecl>(D)->getDefinition();
  1118. assert(CurContext && "skipping definition of undefined tag");
  1119. // Start lookups from the parent of the current context; we don't want to look
  1120. // into the pre-existing complete definition.
  1121. S->setEntity(CurContext->getLookupParent());
  1122. return Result;
  1123. }
  1124. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1125. CurContext = static_cast<decltype(CurContext)>(Context);
  1126. }
  1127. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1128. /// of a declarator's nested name specifier.
  1129. ///
  1130. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1131. // C++0x [basic.lookup.unqual]p13:
  1132. // A name used in the definition of a static data member of class
  1133. // X (after the qualified-id of the static member) is looked up as
  1134. // if the name was used in a member function of X.
  1135. // C++0x [basic.lookup.unqual]p14:
  1136. // If a variable member of a namespace is defined outside of the
  1137. // scope of its namespace then any name used in the definition of
  1138. // the variable member (after the declarator-id) is looked up as
  1139. // if the definition of the variable member occurred in its
  1140. // namespace.
  1141. // Both of these imply that we should push a scope whose context
  1142. // is the semantic context of the declaration. We can't use
  1143. // PushDeclContext here because that context is not necessarily
  1144. // lexically contained in the current context. Fortunately,
  1145. // the containing scope should have the appropriate information.
  1146. assert(!S->getEntity() && "scope already has entity");
  1147. #ifndef NDEBUG
  1148. Scope *Ancestor = S->getParent();
  1149. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1150. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1151. #endif
  1152. CurContext = DC;
  1153. S->setEntity(DC);
  1154. }
  1155. void Sema::ExitDeclaratorContext(Scope *S) {
  1156. assert(S->getEntity() == CurContext && "Context imbalance!");
  1157. // Switch back to the lexical context. The safety of this is
  1158. // enforced by an assert in EnterDeclaratorContext.
  1159. Scope *Ancestor = S->getParent();
  1160. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1161. CurContext = Ancestor->getEntity();
  1162. // We don't need to do anything with the scope, which is going to
  1163. // disappear.
  1164. }
  1165. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1166. // We assume that the caller has already called
  1167. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1168. FunctionDecl *FD = D->getAsFunction();
  1169. if (!FD)
  1170. return;
  1171. // Same implementation as PushDeclContext, but enters the context
  1172. // from the lexical parent, rather than the top-level class.
  1173. assert(CurContext == FD->getLexicalParent() &&
  1174. "The next DeclContext should be lexically contained in the current one.");
  1175. CurContext = FD;
  1176. S->setEntity(CurContext);
  1177. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1178. ParmVarDecl *Param = FD->getParamDecl(P);
  1179. // If the parameter has an identifier, then add it to the scope
  1180. if (Param->getIdentifier()) {
  1181. S->AddDecl(Param);
  1182. IdResolver.AddDecl(Param);
  1183. }
  1184. }
  1185. }
  1186. void Sema::ActOnExitFunctionContext() {
  1187. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1188. // rather than the top-level class.
  1189. assert(CurContext && "DeclContext imbalance!");
  1190. CurContext = CurContext->getLexicalParent();
  1191. assert(CurContext && "Popped translation unit!");
  1192. }
  1193. /// Determine whether we allow overloading of the function
  1194. /// PrevDecl with another declaration.
  1195. ///
  1196. /// This routine determines whether overloading is possible, not
  1197. /// whether some new function is actually an overload. It will return
  1198. /// true in C++ (where we can always provide overloads) or, as an
  1199. /// extension, in C when the previous function is already an
  1200. /// overloaded function declaration or has the "overloadable"
  1201. /// attribute.
  1202. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1203. ASTContext &Context,
  1204. const FunctionDecl *New) {
  1205. if (Context.getLangOpts().CPlusPlus)
  1206. return true;
  1207. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1208. return true;
  1209. return Previous.getResultKind() == LookupResult::Found &&
  1210. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1211. New->hasAttr<OverloadableAttr>());
  1212. }
  1213. /// Add this decl to the scope shadowed decl chains.
  1214. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1215. // Move up the scope chain until we find the nearest enclosing
  1216. // non-transparent context. The declaration will be introduced into this
  1217. // scope.
  1218. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1219. S = S->getParent();
  1220. // Add scoped declarations into their context, so that they can be
  1221. // found later. Declarations without a context won't be inserted
  1222. // into any context.
  1223. if (AddToContext)
  1224. CurContext->addDecl(D);
  1225. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1226. // are function-local declarations.
  1227. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1228. !D->getDeclContext()->getRedeclContext()->Equals(
  1229. D->getLexicalDeclContext()->getRedeclContext()) &&
  1230. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1231. return;
  1232. // Template instantiations should also not be pushed into scope.
  1233. if (isa<FunctionDecl>(D) &&
  1234. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1235. return;
  1236. // If this replaces anything in the current scope,
  1237. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1238. IEnd = IdResolver.end();
  1239. for (; I != IEnd; ++I) {
  1240. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1241. S->RemoveDecl(*I);
  1242. IdResolver.RemoveDecl(*I);
  1243. // Should only need to replace one decl.
  1244. break;
  1245. }
  1246. }
  1247. S->AddDecl(D);
  1248. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1249. // Implicitly-generated labels may end up getting generated in an order that
  1250. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1251. // the label at the appropriate place in the identifier chain.
  1252. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1253. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1254. if (IDC == CurContext) {
  1255. if (!S->isDeclScope(*I))
  1256. continue;
  1257. } else if (IDC->Encloses(CurContext))
  1258. break;
  1259. }
  1260. IdResolver.InsertDeclAfter(I, D);
  1261. } else {
  1262. IdResolver.AddDecl(D);
  1263. }
  1264. }
  1265. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1266. bool AllowInlineNamespace) {
  1267. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1268. }
  1269. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1270. DeclContext *TargetDC = DC->getPrimaryContext();
  1271. do {
  1272. if (DeclContext *ScopeDC = S->getEntity())
  1273. if (ScopeDC->getPrimaryContext() == TargetDC)
  1274. return S;
  1275. } while ((S = S->getParent()));
  1276. return nullptr;
  1277. }
  1278. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1279. DeclContext*,
  1280. ASTContext&);
  1281. /// Filters out lookup results that don't fall within the given scope
  1282. /// as determined by isDeclInScope.
  1283. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1284. bool ConsiderLinkage,
  1285. bool AllowInlineNamespace) {
  1286. LookupResult::Filter F = R.makeFilter();
  1287. while (F.hasNext()) {
  1288. NamedDecl *D = F.next();
  1289. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1290. continue;
  1291. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1292. continue;
  1293. F.erase();
  1294. }
  1295. F.done();
  1296. }
  1297. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1298. /// have compatible owning modules.
  1299. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1300. // FIXME: The Modules TS is not clear about how friend declarations are
  1301. // to be treated. It's not meaningful to have different owning modules for
  1302. // linkage in redeclarations of the same entity, so for now allow the
  1303. // redeclaration and change the owning modules to match.
  1304. if (New->getFriendObjectKind() &&
  1305. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1306. New->setLocalOwningModule(Old->getOwningModule());
  1307. makeMergedDefinitionVisible(New);
  1308. return false;
  1309. }
  1310. Module *NewM = New->getOwningModule();
  1311. Module *OldM = Old->getOwningModule();
  1312. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1313. NewM = NewM->Parent;
  1314. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1315. OldM = OldM->Parent;
  1316. if (NewM == OldM)
  1317. return false;
  1318. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1319. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1320. if (NewIsModuleInterface || OldIsModuleInterface) {
  1321. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1322. // if a declaration of D [...] appears in the purview of a module, all
  1323. // other such declarations shall appear in the purview of the same module
  1324. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1325. << New
  1326. << NewIsModuleInterface
  1327. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1328. << OldIsModuleInterface
  1329. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1330. Diag(Old->getLocation(), diag::note_previous_declaration);
  1331. New->setInvalidDecl();
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. static bool isUsingDecl(NamedDecl *D) {
  1337. return isa<UsingShadowDecl>(D) ||
  1338. isa<UnresolvedUsingTypenameDecl>(D) ||
  1339. isa<UnresolvedUsingValueDecl>(D);
  1340. }
  1341. /// Removes using shadow declarations from the lookup results.
  1342. static void RemoveUsingDecls(LookupResult &R) {
  1343. LookupResult::Filter F = R.makeFilter();
  1344. while (F.hasNext())
  1345. if (isUsingDecl(F.next()))
  1346. F.erase();
  1347. F.done();
  1348. }
  1349. /// Check for this common pattern:
  1350. /// @code
  1351. /// class S {
  1352. /// S(const S&); // DO NOT IMPLEMENT
  1353. /// void operator=(const S&); // DO NOT IMPLEMENT
  1354. /// };
  1355. /// @endcode
  1356. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1357. // FIXME: Should check for private access too but access is set after we get
  1358. // the decl here.
  1359. if (D->doesThisDeclarationHaveABody())
  1360. return false;
  1361. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1362. return CD->isCopyConstructor();
  1363. return D->isCopyAssignmentOperator();
  1364. }
  1365. // We need this to handle
  1366. //
  1367. // typedef struct {
  1368. // void *foo() { return 0; }
  1369. // } A;
  1370. //
  1371. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1372. // for example. If 'A', foo will have external linkage. If we have '*A',
  1373. // foo will have no linkage. Since we can't know until we get to the end
  1374. // of the typedef, this function finds out if D might have non-external linkage.
  1375. // Callers should verify at the end of the TU if it D has external linkage or
  1376. // not.
  1377. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1378. const DeclContext *DC = D->getDeclContext();
  1379. while (!DC->isTranslationUnit()) {
  1380. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1381. if (!RD->hasNameForLinkage())
  1382. return true;
  1383. }
  1384. DC = DC->getParent();
  1385. }
  1386. return !D->isExternallyVisible();
  1387. }
  1388. // FIXME: This needs to be refactored; some other isInMainFile users want
  1389. // these semantics.
  1390. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1391. if (S.TUKind != TU_Complete)
  1392. return false;
  1393. return S.SourceMgr.isInMainFile(Loc);
  1394. }
  1395. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1396. assert(D);
  1397. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1398. return false;
  1399. // Ignore all entities declared within templates, and out-of-line definitions
  1400. // of members of class templates.
  1401. if (D->getDeclContext()->isDependentContext() ||
  1402. D->getLexicalDeclContext()->isDependentContext())
  1403. return false;
  1404. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1405. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1406. return false;
  1407. // A non-out-of-line declaration of a member specialization was implicitly
  1408. // instantiated; it's the out-of-line declaration that we're interested in.
  1409. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1410. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1411. return false;
  1412. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1413. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1414. return false;
  1415. } else {
  1416. // 'static inline' functions are defined in headers; don't warn.
  1417. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1418. return false;
  1419. }
  1420. if (FD->doesThisDeclarationHaveABody() &&
  1421. Context.DeclMustBeEmitted(FD))
  1422. return false;
  1423. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1424. // Constants and utility variables are defined in headers with internal
  1425. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1426. // like "inline".)
  1427. if (!isMainFileLoc(*this, VD->getLocation()))
  1428. return false;
  1429. if (Context.DeclMustBeEmitted(VD))
  1430. return false;
  1431. if (VD->isStaticDataMember() &&
  1432. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1433. return false;
  1434. if (VD->isStaticDataMember() &&
  1435. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1436. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1437. return false;
  1438. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1439. return false;
  1440. } else {
  1441. return false;
  1442. }
  1443. // Only warn for unused decls internal to the translation unit.
  1444. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1445. // for inline functions defined in the main source file, for instance.
  1446. return mightHaveNonExternalLinkage(D);
  1447. }
  1448. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1449. if (!D)
  1450. return;
  1451. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1452. const FunctionDecl *First = FD->getFirstDecl();
  1453. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1454. return; // First should already be in the vector.
  1455. }
  1456. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1457. const VarDecl *First = VD->getFirstDecl();
  1458. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1459. return; // First should already be in the vector.
  1460. }
  1461. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1462. UnusedFileScopedDecls.push_back(D);
  1463. }
  1464. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1465. if (D->isInvalidDecl())
  1466. return false;
  1467. bool Referenced = false;
  1468. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1469. // For a decomposition declaration, warn if none of the bindings are
  1470. // referenced, instead of if the variable itself is referenced (which
  1471. // it is, by the bindings' expressions).
  1472. for (auto *BD : DD->bindings()) {
  1473. if (BD->isReferenced()) {
  1474. Referenced = true;
  1475. break;
  1476. }
  1477. }
  1478. } else if (!D->getDeclName()) {
  1479. return false;
  1480. } else if (D->isReferenced() || D->isUsed()) {
  1481. Referenced = true;
  1482. }
  1483. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1484. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1485. return false;
  1486. if (isa<LabelDecl>(D))
  1487. return true;
  1488. // Except for labels, we only care about unused decls that are local to
  1489. // functions.
  1490. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1491. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1492. // For dependent types, the diagnostic is deferred.
  1493. WithinFunction =
  1494. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1495. if (!WithinFunction)
  1496. return false;
  1497. if (isa<TypedefNameDecl>(D))
  1498. return true;
  1499. // White-list anything that isn't a local variable.
  1500. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1501. return false;
  1502. // Types of valid local variables should be complete, so this should succeed.
  1503. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1504. // White-list anything with an __attribute__((unused)) type.
  1505. const auto *Ty = VD->getType().getTypePtr();
  1506. // Only look at the outermost level of typedef.
  1507. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1508. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1509. return false;
  1510. }
  1511. // If we failed to complete the type for some reason, or if the type is
  1512. // dependent, don't diagnose the variable.
  1513. if (Ty->isIncompleteType() || Ty->isDependentType())
  1514. return false;
  1515. // Look at the element type to ensure that the warning behaviour is
  1516. // consistent for both scalars and arrays.
  1517. Ty = Ty->getBaseElementTypeUnsafe();
  1518. if (const TagType *TT = Ty->getAs<TagType>()) {
  1519. const TagDecl *Tag = TT->getDecl();
  1520. if (Tag->hasAttr<UnusedAttr>())
  1521. return false;
  1522. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1523. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1524. return false;
  1525. if (const Expr *Init = VD->getInit()) {
  1526. if (const ExprWithCleanups *Cleanups =
  1527. dyn_cast<ExprWithCleanups>(Init))
  1528. Init = Cleanups->getSubExpr();
  1529. const CXXConstructExpr *Construct =
  1530. dyn_cast<CXXConstructExpr>(Init);
  1531. if (Construct && !Construct->isElidable()) {
  1532. CXXConstructorDecl *CD = Construct->getConstructor();
  1533. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1534. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1535. return false;
  1536. }
  1537. }
  1538. }
  1539. }
  1540. // TODO: __attribute__((unused)) templates?
  1541. }
  1542. return true;
  1543. }
  1544. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1545. FixItHint &Hint) {
  1546. if (isa<LabelDecl>(D)) {
  1547. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1548. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1549. true);
  1550. if (AfterColon.isInvalid())
  1551. return;
  1552. Hint = FixItHint::CreateRemoval(
  1553. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1554. }
  1555. }
  1556. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1557. if (D->getTypeForDecl()->isDependentType())
  1558. return;
  1559. for (auto *TmpD : D->decls()) {
  1560. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1561. DiagnoseUnusedDecl(T);
  1562. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1563. DiagnoseUnusedNestedTypedefs(R);
  1564. }
  1565. }
  1566. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1567. /// unless they are marked attr(unused).
  1568. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1569. if (!ShouldDiagnoseUnusedDecl(D))
  1570. return;
  1571. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1572. // typedefs can be referenced later on, so the diagnostics are emitted
  1573. // at end-of-translation-unit.
  1574. UnusedLocalTypedefNameCandidates.insert(TD);
  1575. return;
  1576. }
  1577. FixItHint Hint;
  1578. GenerateFixForUnusedDecl(D, Context, Hint);
  1579. unsigned DiagID;
  1580. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1581. DiagID = diag::warn_unused_exception_param;
  1582. else if (isa<LabelDecl>(D))
  1583. DiagID = diag::warn_unused_label;
  1584. else
  1585. DiagID = diag::warn_unused_variable;
  1586. Diag(D->getLocation(), DiagID) << D << Hint;
  1587. }
  1588. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1589. // Verify that we have no forward references left. If so, there was a goto
  1590. // or address of a label taken, but no definition of it. Label fwd
  1591. // definitions are indicated with a null substmt which is also not a resolved
  1592. // MS inline assembly label name.
  1593. bool Diagnose = false;
  1594. if (L->isMSAsmLabel())
  1595. Diagnose = !L->isResolvedMSAsmLabel();
  1596. else
  1597. Diagnose = L->getStmt() == nullptr;
  1598. if (Diagnose)
  1599. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1600. }
  1601. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1602. S->mergeNRVOIntoParent();
  1603. if (S->decl_empty()) return;
  1604. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1605. "Scope shouldn't contain decls!");
  1606. for (auto *TmpD : S->decls()) {
  1607. assert(TmpD && "This decl didn't get pushed??");
  1608. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1609. NamedDecl *D = cast<NamedDecl>(TmpD);
  1610. // Diagnose unused variables in this scope.
  1611. if (!S->hasUnrecoverableErrorOccurred()) {
  1612. DiagnoseUnusedDecl(D);
  1613. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1614. DiagnoseUnusedNestedTypedefs(RD);
  1615. }
  1616. if (!D->getDeclName()) continue;
  1617. // If this was a forward reference to a label, verify it was defined.
  1618. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1619. CheckPoppedLabel(LD, *this);
  1620. // Remove this name from our lexical scope, and warn on it if we haven't
  1621. // already.
  1622. IdResolver.RemoveDecl(D);
  1623. auto ShadowI = ShadowingDecls.find(D);
  1624. if (ShadowI != ShadowingDecls.end()) {
  1625. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1626. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1627. << D << FD << FD->getParent();
  1628. Diag(FD->getLocation(), diag::note_previous_declaration);
  1629. }
  1630. ShadowingDecls.erase(ShadowI);
  1631. }
  1632. }
  1633. }
  1634. /// Look for an Objective-C class in the translation unit.
  1635. ///
  1636. /// \param Id The name of the Objective-C class we're looking for. If
  1637. /// typo-correction fixes this name, the Id will be updated
  1638. /// to the fixed name.
  1639. ///
  1640. /// \param IdLoc The location of the name in the translation unit.
  1641. ///
  1642. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1643. /// if there is no class with the given name.
  1644. ///
  1645. /// \returns The declaration of the named Objective-C class, or NULL if the
  1646. /// class could not be found.
  1647. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1648. SourceLocation IdLoc,
  1649. bool DoTypoCorrection) {
  1650. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1651. // creation from this context.
  1652. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1653. if (!IDecl && DoTypoCorrection) {
  1654. // Perform typo correction at the given location, but only if we
  1655. // find an Objective-C class name.
  1656. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1657. if (TypoCorrection C =
  1658. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1659. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1660. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1661. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1662. Id = IDecl->getIdentifier();
  1663. }
  1664. }
  1665. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1666. // This routine must always return a class definition, if any.
  1667. if (Def && Def->getDefinition())
  1668. Def = Def->getDefinition();
  1669. return Def;
  1670. }
  1671. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1672. /// from S, where a non-field would be declared. This routine copes
  1673. /// with the difference between C and C++ scoping rules in structs and
  1674. /// unions. For example, the following code is well-formed in C but
  1675. /// ill-formed in C++:
  1676. /// @code
  1677. /// struct S6 {
  1678. /// enum { BAR } e;
  1679. /// };
  1680. ///
  1681. /// void test_S6() {
  1682. /// struct S6 a;
  1683. /// a.e = BAR;
  1684. /// }
  1685. /// @endcode
  1686. /// For the declaration of BAR, this routine will return a different
  1687. /// scope. The scope S will be the scope of the unnamed enumeration
  1688. /// within S6. In C++, this routine will return the scope associated
  1689. /// with S6, because the enumeration's scope is a transparent
  1690. /// context but structures can contain non-field names. In C, this
  1691. /// routine will return the translation unit scope, since the
  1692. /// enumeration's scope is a transparent context and structures cannot
  1693. /// contain non-field names.
  1694. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1695. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1696. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1697. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1698. S = S->getParent();
  1699. return S;
  1700. }
  1701. /// Looks up the declaration of "struct objc_super" and
  1702. /// saves it for later use in building builtin declaration of
  1703. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1704. /// pre-existing declaration exists no action takes place.
  1705. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1706. IdentifierInfo *II) {
  1707. if (!II->isStr("objc_msgSendSuper"))
  1708. return;
  1709. ASTContext &Context = ThisSema.Context;
  1710. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1711. SourceLocation(), Sema::LookupTagName);
  1712. ThisSema.LookupName(Result, S);
  1713. if (Result.getResultKind() == LookupResult::Found)
  1714. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1715. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1716. }
  1717. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1718. ASTContext::GetBuiltinTypeError Error) {
  1719. switch (Error) {
  1720. case ASTContext::GE_None:
  1721. return "";
  1722. case ASTContext::GE_Missing_type:
  1723. return BuiltinInfo.getHeaderName(ID);
  1724. case ASTContext::GE_Missing_stdio:
  1725. return "stdio.h";
  1726. case ASTContext::GE_Missing_setjmp:
  1727. return "setjmp.h";
  1728. case ASTContext::GE_Missing_ucontext:
  1729. return "ucontext.h";
  1730. }
  1731. llvm_unreachable("unhandled error kind");
  1732. }
  1733. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1734. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1735. /// if we're creating this built-in in anticipation of redeclaring the
  1736. /// built-in.
  1737. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1738. Scope *S, bool ForRedeclaration,
  1739. SourceLocation Loc) {
  1740. LookupPredefedObjCSuperType(*this, S, II);
  1741. ASTContext::GetBuiltinTypeError Error;
  1742. QualType R = Context.GetBuiltinType(ID, Error);
  1743. if (Error) {
  1744. if (!ForRedeclaration)
  1745. return nullptr;
  1746. // If we have a builtin without an associated type we should not emit a
  1747. // warning when we were not able to find a type for it.
  1748. if (Error == ASTContext::GE_Missing_type)
  1749. return nullptr;
  1750. // If we could not find a type for setjmp it is because the jmp_buf type was
  1751. // not defined prior to the setjmp declaration.
  1752. if (Error == ASTContext::GE_Missing_setjmp) {
  1753. Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
  1754. << Context.BuiltinInfo.getName(ID);
  1755. return nullptr;
  1756. }
  1757. // Generally, we emit a warning that the declaration requires the
  1758. // appropriate header.
  1759. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1760. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1761. << Context.BuiltinInfo.getName(ID);
  1762. return nullptr;
  1763. }
  1764. if (!ForRedeclaration &&
  1765. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1766. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1767. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1768. << Context.BuiltinInfo.getName(ID) << R;
  1769. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1770. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1771. Diag(Loc, diag::note_include_header_or_declare)
  1772. << Context.BuiltinInfo.getHeaderName(ID)
  1773. << Context.BuiltinInfo.getName(ID);
  1774. }
  1775. if (R.isNull())
  1776. return nullptr;
  1777. DeclContext *Parent = Context.getTranslationUnitDecl();
  1778. if (getLangOpts().CPlusPlus) {
  1779. LinkageSpecDecl *CLinkageDecl =
  1780. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1781. LinkageSpecDecl::lang_c, false);
  1782. CLinkageDecl->setImplicit();
  1783. Parent->addDecl(CLinkageDecl);
  1784. Parent = CLinkageDecl;
  1785. }
  1786. FunctionDecl *New = FunctionDecl::Create(Context,
  1787. Parent,
  1788. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1789. SC_Extern,
  1790. false,
  1791. R->isFunctionProtoType());
  1792. New->setImplicit();
  1793. // Create Decl objects for each parameter, adding them to the
  1794. // FunctionDecl.
  1795. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1796. SmallVector<ParmVarDecl*, 16> Params;
  1797. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1798. ParmVarDecl *parm =
  1799. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1800. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1801. SC_None, nullptr);
  1802. parm->setScopeInfo(0, i);
  1803. Params.push_back(parm);
  1804. }
  1805. New->setParams(Params);
  1806. }
  1807. AddKnownFunctionAttributes(New);
  1808. RegisterLocallyScopedExternCDecl(New, S);
  1809. // TUScope is the translation-unit scope to insert this function into.
  1810. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1811. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1812. // entirely, but we're not there yet.
  1813. DeclContext *SavedContext = CurContext;
  1814. CurContext = Parent;
  1815. PushOnScopeChains(New, TUScope);
  1816. CurContext = SavedContext;
  1817. return New;
  1818. }
  1819. /// Typedef declarations don't have linkage, but they still denote the same
  1820. /// entity if their types are the same.
  1821. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1822. /// isSameEntity.
  1823. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1824. TypedefNameDecl *Decl,
  1825. LookupResult &Previous) {
  1826. // This is only interesting when modules are enabled.
  1827. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1828. return;
  1829. // Empty sets are uninteresting.
  1830. if (Previous.empty())
  1831. return;
  1832. LookupResult::Filter Filter = Previous.makeFilter();
  1833. while (Filter.hasNext()) {
  1834. NamedDecl *Old = Filter.next();
  1835. // Non-hidden declarations are never ignored.
  1836. if (S.isVisible(Old))
  1837. continue;
  1838. // Declarations of the same entity are not ignored, even if they have
  1839. // different linkages.
  1840. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1841. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1842. Decl->getUnderlyingType()))
  1843. continue;
  1844. // If both declarations give a tag declaration a typedef name for linkage
  1845. // purposes, then they declare the same entity.
  1846. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1847. Decl->getAnonDeclWithTypedefName())
  1848. continue;
  1849. }
  1850. Filter.erase();
  1851. }
  1852. Filter.done();
  1853. }
  1854. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1855. QualType OldType;
  1856. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1857. OldType = OldTypedef->getUnderlyingType();
  1858. else
  1859. OldType = Context.getTypeDeclType(Old);
  1860. QualType NewType = New->getUnderlyingType();
  1861. if (NewType->isVariablyModifiedType()) {
  1862. // Must not redefine a typedef with a variably-modified type.
  1863. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1864. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1865. << Kind << NewType;
  1866. if (Old->getLocation().isValid())
  1867. notePreviousDefinition(Old, New->getLocation());
  1868. New->setInvalidDecl();
  1869. return true;
  1870. }
  1871. if (OldType != NewType &&
  1872. !OldType->isDependentType() &&
  1873. !NewType->isDependentType() &&
  1874. !Context.hasSameType(OldType, NewType)) {
  1875. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1876. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1877. << Kind << NewType << OldType;
  1878. if (Old->getLocation().isValid())
  1879. notePreviousDefinition(Old, New->getLocation());
  1880. New->setInvalidDecl();
  1881. return true;
  1882. }
  1883. return false;
  1884. }
  1885. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1886. /// same name and scope as a previous declaration 'Old'. Figure out
  1887. /// how to resolve this situation, merging decls or emitting
  1888. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1889. ///
  1890. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1891. LookupResult &OldDecls) {
  1892. // If the new decl is known invalid already, don't bother doing any
  1893. // merging checks.
  1894. if (New->isInvalidDecl()) return;
  1895. // Allow multiple definitions for ObjC built-in typedefs.
  1896. // FIXME: Verify the underlying types are equivalent!
  1897. if (getLangOpts().ObjC) {
  1898. const IdentifierInfo *TypeID = New->getIdentifier();
  1899. switch (TypeID->getLength()) {
  1900. default: break;
  1901. case 2:
  1902. {
  1903. if (!TypeID->isStr("id"))
  1904. break;
  1905. QualType T = New->getUnderlyingType();
  1906. if (!T->isPointerType())
  1907. break;
  1908. if (!T->isVoidPointerType()) {
  1909. QualType PT = T->castAs<PointerType>()->getPointeeType();
  1910. if (!PT->isStructureType())
  1911. break;
  1912. }
  1913. Context.setObjCIdRedefinitionType(T);
  1914. // Install the built-in type for 'id', ignoring the current definition.
  1915. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1916. return;
  1917. }
  1918. case 5:
  1919. if (!TypeID->isStr("Class"))
  1920. break;
  1921. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1922. // Install the built-in type for 'Class', ignoring the current definition.
  1923. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1924. return;
  1925. case 3:
  1926. if (!TypeID->isStr("SEL"))
  1927. break;
  1928. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1929. // Install the built-in type for 'SEL', ignoring the current definition.
  1930. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1931. return;
  1932. }
  1933. // Fall through - the typedef name was not a builtin type.
  1934. }
  1935. // Verify the old decl was also a type.
  1936. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1937. if (!Old) {
  1938. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1939. << New->getDeclName();
  1940. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1941. if (OldD->getLocation().isValid())
  1942. notePreviousDefinition(OldD, New->getLocation());
  1943. return New->setInvalidDecl();
  1944. }
  1945. // If the old declaration is invalid, just give up here.
  1946. if (Old->isInvalidDecl())
  1947. return New->setInvalidDecl();
  1948. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1949. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1950. auto *NewTag = New->getAnonDeclWithTypedefName();
  1951. NamedDecl *Hidden = nullptr;
  1952. if (OldTag && NewTag &&
  1953. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1954. !hasVisibleDefinition(OldTag, &Hidden)) {
  1955. // There is a definition of this tag, but it is not visible. Use it
  1956. // instead of our tag.
  1957. New->setTypeForDecl(OldTD->getTypeForDecl());
  1958. if (OldTD->isModed())
  1959. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1960. OldTD->getUnderlyingType());
  1961. else
  1962. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1963. // Make the old tag definition visible.
  1964. makeMergedDefinitionVisible(Hidden);
  1965. // If this was an unscoped enumeration, yank all of its enumerators
  1966. // out of the scope.
  1967. if (isa<EnumDecl>(NewTag)) {
  1968. Scope *EnumScope = getNonFieldDeclScope(S);
  1969. for (auto *D : NewTag->decls()) {
  1970. auto *ED = cast<EnumConstantDecl>(D);
  1971. assert(EnumScope->isDeclScope(ED));
  1972. EnumScope->RemoveDecl(ED);
  1973. IdResolver.RemoveDecl(ED);
  1974. ED->getLexicalDeclContext()->removeDecl(ED);
  1975. }
  1976. }
  1977. }
  1978. }
  1979. // If the typedef types are not identical, reject them in all languages and
  1980. // with any extensions enabled.
  1981. if (isIncompatibleTypedef(Old, New))
  1982. return;
  1983. // The types match. Link up the redeclaration chain and merge attributes if
  1984. // the old declaration was a typedef.
  1985. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1986. New->setPreviousDecl(Typedef);
  1987. mergeDeclAttributes(New, Old);
  1988. }
  1989. if (getLangOpts().MicrosoftExt)
  1990. return;
  1991. if (getLangOpts().CPlusPlus) {
  1992. // C++ [dcl.typedef]p2:
  1993. // In a given non-class scope, a typedef specifier can be used to
  1994. // redefine the name of any type declared in that scope to refer
  1995. // to the type to which it already refers.
  1996. if (!isa<CXXRecordDecl>(CurContext))
  1997. return;
  1998. // C++0x [dcl.typedef]p4:
  1999. // In a given class scope, a typedef specifier can be used to redefine
  2000. // any class-name declared in that scope that is not also a typedef-name
  2001. // to refer to the type to which it already refers.
  2002. //
  2003. // This wording came in via DR424, which was a correction to the
  2004. // wording in DR56, which accidentally banned code like:
  2005. //
  2006. // struct S {
  2007. // typedef struct A { } A;
  2008. // };
  2009. //
  2010. // in the C++03 standard. We implement the C++0x semantics, which
  2011. // allow the above but disallow
  2012. //
  2013. // struct S {
  2014. // typedef int I;
  2015. // typedef int I;
  2016. // };
  2017. //
  2018. // since that was the intent of DR56.
  2019. if (!isa<TypedefNameDecl>(Old))
  2020. return;
  2021. Diag(New->getLocation(), diag::err_redefinition)
  2022. << New->getDeclName();
  2023. notePreviousDefinition(Old, New->getLocation());
  2024. return New->setInvalidDecl();
  2025. }
  2026. // Modules always permit redefinition of typedefs, as does C11.
  2027. if (getLangOpts().Modules || getLangOpts().C11)
  2028. return;
  2029. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2030. // is normally mapped to an error, but can be controlled with
  2031. // -Wtypedef-redefinition. If either the original or the redefinition is
  2032. // in a system header, don't emit this for compatibility with GCC.
  2033. if (getDiagnostics().getSuppressSystemWarnings() &&
  2034. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2035. (Old->isImplicit() ||
  2036. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2037. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2038. return;
  2039. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2040. << New->getDeclName();
  2041. notePreviousDefinition(Old, New->getLocation());
  2042. }
  2043. /// DeclhasAttr - returns true if decl Declaration already has the target
  2044. /// attribute.
  2045. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2046. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2047. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2048. for (const auto *i : D->attrs())
  2049. if (i->getKind() == A->getKind()) {
  2050. if (Ann) {
  2051. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2052. return true;
  2053. continue;
  2054. }
  2055. // FIXME: Don't hardcode this check
  2056. if (OA && isa<OwnershipAttr>(i))
  2057. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2058. return true;
  2059. }
  2060. return false;
  2061. }
  2062. static bool isAttributeTargetADefinition(Decl *D) {
  2063. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2064. return VD->isThisDeclarationADefinition();
  2065. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2066. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2067. return true;
  2068. }
  2069. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2070. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2071. ///
  2072. /// \return \c true if any attributes were added to \p New.
  2073. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2074. // Look for alignas attributes on Old, and pick out whichever attribute
  2075. // specifies the strictest alignment requirement.
  2076. AlignedAttr *OldAlignasAttr = nullptr;
  2077. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2078. unsigned OldAlign = 0;
  2079. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2080. // FIXME: We have no way of representing inherited dependent alignments
  2081. // in a case like:
  2082. // template<int A, int B> struct alignas(A) X;
  2083. // template<int A, int B> struct alignas(B) X {};
  2084. // For now, we just ignore any alignas attributes which are not on the
  2085. // definition in such a case.
  2086. if (I->isAlignmentDependent())
  2087. return false;
  2088. if (I->isAlignas())
  2089. OldAlignasAttr = I;
  2090. unsigned Align = I->getAlignment(S.Context);
  2091. if (Align > OldAlign) {
  2092. OldAlign = Align;
  2093. OldStrictestAlignAttr = I;
  2094. }
  2095. }
  2096. // Look for alignas attributes on New.
  2097. AlignedAttr *NewAlignasAttr = nullptr;
  2098. unsigned NewAlign = 0;
  2099. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2100. if (I->isAlignmentDependent())
  2101. return false;
  2102. if (I->isAlignas())
  2103. NewAlignasAttr = I;
  2104. unsigned Align = I->getAlignment(S.Context);
  2105. if (Align > NewAlign)
  2106. NewAlign = Align;
  2107. }
  2108. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2109. // Both declarations have 'alignas' attributes. We require them to match.
  2110. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2111. // fall short. (If two declarations both have alignas, they must both match
  2112. // every definition, and so must match each other if there is a definition.)
  2113. // If either declaration only contains 'alignas(0)' specifiers, then it
  2114. // specifies the natural alignment for the type.
  2115. if (OldAlign == 0 || NewAlign == 0) {
  2116. QualType Ty;
  2117. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2118. Ty = VD->getType();
  2119. else
  2120. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2121. if (OldAlign == 0)
  2122. OldAlign = S.Context.getTypeAlign(Ty);
  2123. if (NewAlign == 0)
  2124. NewAlign = S.Context.getTypeAlign(Ty);
  2125. }
  2126. if (OldAlign != NewAlign) {
  2127. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2128. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2129. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2130. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2131. }
  2132. }
  2133. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2134. // C++11 [dcl.align]p6:
  2135. // if any declaration of an entity has an alignment-specifier,
  2136. // every defining declaration of that entity shall specify an
  2137. // equivalent alignment.
  2138. // C11 6.7.5/7:
  2139. // If the definition of an object does not have an alignment
  2140. // specifier, any other declaration of that object shall also
  2141. // have no alignment specifier.
  2142. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2143. << OldAlignasAttr;
  2144. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2145. << OldAlignasAttr;
  2146. }
  2147. bool AnyAdded = false;
  2148. // Ensure we have an attribute representing the strictest alignment.
  2149. if (OldAlign > NewAlign) {
  2150. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2151. Clone->setInherited(true);
  2152. New->addAttr(Clone);
  2153. AnyAdded = true;
  2154. }
  2155. // Ensure we have an alignas attribute if the old declaration had one.
  2156. if (OldAlignasAttr && !NewAlignasAttr &&
  2157. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2158. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2159. Clone->setInherited(true);
  2160. New->addAttr(Clone);
  2161. AnyAdded = true;
  2162. }
  2163. return AnyAdded;
  2164. }
  2165. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2166. const InheritableAttr *Attr,
  2167. Sema::AvailabilityMergeKind AMK) {
  2168. // This function copies an attribute Attr from a previous declaration to the
  2169. // new declaration D if the new declaration doesn't itself have that attribute
  2170. // yet or if that attribute allows duplicates.
  2171. // If you're adding a new attribute that requires logic different from
  2172. // "use explicit attribute on decl if present, else use attribute from
  2173. // previous decl", for example if the attribute needs to be consistent
  2174. // between redeclarations, you need to call a custom merge function here.
  2175. InheritableAttr *NewAttr = nullptr;
  2176. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2177. NewAttr = S.mergeAvailabilityAttr(
  2178. D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
  2179. AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
  2180. AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
  2181. AA->getPriority());
  2182. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2183. NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
  2184. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2185. NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
  2186. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2187. NewAttr = S.mergeDLLImportAttr(D, *ImportA);
  2188. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2189. NewAttr = S.mergeDLLExportAttr(D, *ExportA);
  2190. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2191. NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
  2192. FA->getFirstArg());
  2193. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2194. NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
  2195. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2196. NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
  2197. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2198. NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
  2199. IA->getSemanticSpelling());
  2200. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2201. NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
  2202. &S.Context.Idents.get(AA->getSpelling()));
  2203. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2204. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2205. isa<CUDAGlobalAttr>(Attr))) {
  2206. // CUDA target attributes are part of function signature for
  2207. // overloading purposes and must not be merged.
  2208. return false;
  2209. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2210. NewAttr = S.mergeMinSizeAttr(D, *MA);
  2211. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2212. NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
  2213. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2214. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2215. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2216. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2217. else if (isa<AlignedAttr>(Attr))
  2218. // AlignedAttrs are handled separately, because we need to handle all
  2219. // such attributes on a declaration at the same time.
  2220. NewAttr = nullptr;
  2221. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2222. (AMK == Sema::AMK_Override ||
  2223. AMK == Sema::AMK_ProtocolImplementation))
  2224. NewAttr = nullptr;
  2225. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2226. NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
  2227. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2228. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2229. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2230. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2231. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2232. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2233. if (NewAttr) {
  2234. NewAttr->setInherited(true);
  2235. D->addAttr(NewAttr);
  2236. if (isa<MSInheritanceAttr>(NewAttr))
  2237. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2238. return true;
  2239. }
  2240. return false;
  2241. }
  2242. static const NamedDecl *getDefinition(const Decl *D) {
  2243. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2244. return TD->getDefinition();
  2245. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2246. const VarDecl *Def = VD->getDefinition();
  2247. if (Def)
  2248. return Def;
  2249. return VD->getActingDefinition();
  2250. }
  2251. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2252. return FD->getDefinition();
  2253. return nullptr;
  2254. }
  2255. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2256. for (const auto *Attribute : D->attrs())
  2257. if (Attribute->getKind() == Kind)
  2258. return true;
  2259. return false;
  2260. }
  2261. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2262. /// there are no new attributes in this declaration.
  2263. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2264. if (!New->hasAttrs())
  2265. return;
  2266. const NamedDecl *Def = getDefinition(Old);
  2267. if (!Def || Def == New)
  2268. return;
  2269. AttrVec &NewAttributes = New->getAttrs();
  2270. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2271. const Attr *NewAttribute = NewAttributes[I];
  2272. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2273. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2274. Sema::SkipBodyInfo SkipBody;
  2275. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2276. // If we're skipping this definition, drop the "alias" attribute.
  2277. if (SkipBody.ShouldSkip) {
  2278. NewAttributes.erase(NewAttributes.begin() + I);
  2279. --E;
  2280. continue;
  2281. }
  2282. } else {
  2283. VarDecl *VD = cast<VarDecl>(New);
  2284. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2285. VarDecl::TentativeDefinition
  2286. ? diag::err_alias_after_tentative
  2287. : diag::err_redefinition;
  2288. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2289. if (Diag == diag::err_redefinition)
  2290. S.notePreviousDefinition(Def, VD->getLocation());
  2291. else
  2292. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2293. VD->setInvalidDecl();
  2294. }
  2295. ++I;
  2296. continue;
  2297. }
  2298. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2299. // Tentative definitions are only interesting for the alias check above.
  2300. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2301. ++I;
  2302. continue;
  2303. }
  2304. }
  2305. if (hasAttribute(Def, NewAttribute->getKind())) {
  2306. ++I;
  2307. continue; // regular attr merging will take care of validating this.
  2308. }
  2309. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2310. // C's _Noreturn is allowed to be added to a function after it is defined.
  2311. ++I;
  2312. continue;
  2313. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2314. if (AA->isAlignas()) {
  2315. // C++11 [dcl.align]p6:
  2316. // if any declaration of an entity has an alignment-specifier,
  2317. // every defining declaration of that entity shall specify an
  2318. // equivalent alignment.
  2319. // C11 6.7.5/7:
  2320. // If the definition of an object does not have an alignment
  2321. // specifier, any other declaration of that object shall also
  2322. // have no alignment specifier.
  2323. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2324. << AA;
  2325. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2326. << AA;
  2327. NewAttributes.erase(NewAttributes.begin() + I);
  2328. --E;
  2329. continue;
  2330. }
  2331. } else if (isa<SelectAnyAttr>(NewAttribute) &&
  2332. cast<VarDecl>(New)->isInline() &&
  2333. !cast<VarDecl>(New)->isInlineSpecified()) {
  2334. // Don't warn about applying selectany to implicitly inline variables.
  2335. // Older compilers and language modes would require the use of selectany
  2336. // to make such variables inline, and it would have no effect if we
  2337. // honored it.
  2338. ++I;
  2339. continue;
  2340. }
  2341. S.Diag(NewAttribute->getLocation(),
  2342. diag::warn_attribute_precede_definition);
  2343. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2344. NewAttributes.erase(NewAttributes.begin() + I);
  2345. --E;
  2346. }
  2347. }
  2348. static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
  2349. const ConstInitAttr *CIAttr,
  2350. bool AttrBeforeInit) {
  2351. SourceLocation InsertLoc = InitDecl->getInnerLocStart();
  2352. // Figure out a good way to write this specifier on the old declaration.
  2353. // FIXME: We should just use the spelling of CIAttr, but we don't preserve
  2354. // enough of the attribute list spelling information to extract that without
  2355. // heroics.
  2356. std::string SuitableSpelling;
  2357. if (S.getLangOpts().CPlusPlus2a)
  2358. SuitableSpelling =
  2359. S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
  2360. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2361. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2362. InsertLoc,
  2363. {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
  2364. tok::coloncolon,
  2365. S.PP.getIdentifierInfo("require_constant_initialization"),
  2366. tok::r_square, tok::r_square});
  2367. if (SuitableSpelling.empty())
  2368. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2369. InsertLoc,
  2370. {tok::kw___attribute, tok::l_paren, tok::r_paren,
  2371. S.PP.getIdentifierInfo("require_constant_initialization"),
  2372. tok::r_paren, tok::r_paren});
  2373. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
  2374. SuitableSpelling = "constinit";
  2375. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2376. SuitableSpelling = "[[clang::require_constant_initialization]]";
  2377. if (SuitableSpelling.empty())
  2378. SuitableSpelling = "__attribute__((require_constant_initialization))";
  2379. SuitableSpelling += " ";
  2380. if (AttrBeforeInit) {
  2381. // extern constinit int a;
  2382. // int a = 0; // error (missing 'constinit'), accepted as extension
  2383. assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
  2384. S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
  2385. << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2386. S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
  2387. } else {
  2388. // int a = 0;
  2389. // constinit extern int a; // error (missing 'constinit')
  2390. S.Diag(CIAttr->getLocation(),
  2391. CIAttr->isConstinit() ? diag::err_constinit_added_too_late
  2392. : diag::warn_require_const_init_added_too_late)
  2393. << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
  2394. S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
  2395. << CIAttr->isConstinit()
  2396. << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2397. }
  2398. }
  2399. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2400. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2401. AvailabilityMergeKind AMK) {
  2402. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2403. UsedAttr *NewAttr = OldAttr->clone(Context);
  2404. NewAttr->setInherited(true);
  2405. New->addAttr(NewAttr);
  2406. }
  2407. if (!Old->hasAttrs() && !New->hasAttrs())
  2408. return;
  2409. // [dcl.constinit]p1:
  2410. // If the [constinit] specifier is applied to any declaration of a
  2411. // variable, it shall be applied to the initializing declaration.
  2412. const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
  2413. const auto *NewConstInit = New->getAttr<ConstInitAttr>();
  2414. if (bool(OldConstInit) != bool(NewConstInit)) {
  2415. const auto *OldVD = cast<VarDecl>(Old);
  2416. auto *NewVD = cast<VarDecl>(New);
  2417. // Find the initializing declaration. Note that we might not have linked
  2418. // the new declaration into the redeclaration chain yet.
  2419. const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
  2420. if (!InitDecl &&
  2421. (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
  2422. InitDecl = NewVD;
  2423. if (InitDecl == NewVD) {
  2424. // This is the initializing declaration. If it would inherit 'constinit',
  2425. // that's ill-formed. (Note that we do not apply this to the attribute
  2426. // form).
  2427. if (OldConstInit && OldConstInit->isConstinit())
  2428. diagnoseMissingConstinit(*this, NewVD, OldConstInit,
  2429. /*AttrBeforeInit=*/true);
  2430. } else if (NewConstInit) {
  2431. // This is the first time we've been told that this declaration should
  2432. // have a constant initializer. If we already saw the initializing
  2433. // declaration, this is too late.
  2434. if (InitDecl && InitDecl != NewVD) {
  2435. diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
  2436. /*AttrBeforeInit=*/false);
  2437. NewVD->dropAttr<ConstInitAttr>();
  2438. }
  2439. }
  2440. }
  2441. // Attributes declared post-definition are currently ignored.
  2442. checkNewAttributesAfterDef(*this, New, Old);
  2443. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2444. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2445. if (!OldA->isEquivalent(NewA)) {
  2446. // This redeclaration changes __asm__ label.
  2447. Diag(New->getLocation(), diag::err_different_asm_label);
  2448. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2449. }
  2450. } else if (Old->isUsed()) {
  2451. // This redeclaration adds an __asm__ label to a declaration that has
  2452. // already been ODR-used.
  2453. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2454. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2455. }
  2456. }
  2457. // Re-declaration cannot add abi_tag's.
  2458. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2459. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2460. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2461. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2462. NewTag) == OldAbiTagAttr->tags_end()) {
  2463. Diag(NewAbiTagAttr->getLocation(),
  2464. diag::err_new_abi_tag_on_redeclaration)
  2465. << NewTag;
  2466. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2467. }
  2468. }
  2469. } else {
  2470. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2471. Diag(Old->getLocation(), diag::note_previous_declaration);
  2472. }
  2473. }
  2474. // This redeclaration adds a section attribute.
  2475. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2476. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2477. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2478. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2479. Diag(Old->getLocation(), diag::note_previous_declaration);
  2480. }
  2481. }
  2482. }
  2483. // Redeclaration adds code-seg attribute.
  2484. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2485. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2486. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2487. Diag(New->getLocation(), diag::warn_mismatched_section)
  2488. << 0 /*codeseg*/;
  2489. Diag(Old->getLocation(), diag::note_previous_declaration);
  2490. }
  2491. if (!Old->hasAttrs())
  2492. return;
  2493. bool foundAny = New->hasAttrs();
  2494. // Ensure that any moving of objects within the allocated map is done before
  2495. // we process them.
  2496. if (!foundAny) New->setAttrs(AttrVec());
  2497. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2498. // Ignore deprecated/unavailable/availability attributes if requested.
  2499. AvailabilityMergeKind LocalAMK = AMK_None;
  2500. if (isa<DeprecatedAttr>(I) ||
  2501. isa<UnavailableAttr>(I) ||
  2502. isa<AvailabilityAttr>(I)) {
  2503. switch (AMK) {
  2504. case AMK_None:
  2505. continue;
  2506. case AMK_Redeclaration:
  2507. case AMK_Override:
  2508. case AMK_ProtocolImplementation:
  2509. LocalAMK = AMK;
  2510. break;
  2511. }
  2512. }
  2513. // Already handled.
  2514. if (isa<UsedAttr>(I))
  2515. continue;
  2516. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2517. foundAny = true;
  2518. }
  2519. if (mergeAlignedAttrs(*this, New, Old))
  2520. foundAny = true;
  2521. if (!foundAny) New->dropAttrs();
  2522. }
  2523. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2524. /// to the new one.
  2525. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2526. const ParmVarDecl *oldDecl,
  2527. Sema &S) {
  2528. // C++11 [dcl.attr.depend]p2:
  2529. // The first declaration of a function shall specify the
  2530. // carries_dependency attribute for its declarator-id if any declaration
  2531. // of the function specifies the carries_dependency attribute.
  2532. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2533. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2534. S.Diag(CDA->getLocation(),
  2535. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2536. // Find the first declaration of the parameter.
  2537. // FIXME: Should we build redeclaration chains for function parameters?
  2538. const FunctionDecl *FirstFD =
  2539. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2540. const ParmVarDecl *FirstVD =
  2541. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2542. S.Diag(FirstVD->getLocation(),
  2543. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2544. }
  2545. if (!oldDecl->hasAttrs())
  2546. return;
  2547. bool foundAny = newDecl->hasAttrs();
  2548. // Ensure that any moving of objects within the allocated map is
  2549. // done before we process them.
  2550. if (!foundAny) newDecl->setAttrs(AttrVec());
  2551. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2552. if (!DeclHasAttr(newDecl, I)) {
  2553. InheritableAttr *newAttr =
  2554. cast<InheritableParamAttr>(I->clone(S.Context));
  2555. newAttr->setInherited(true);
  2556. newDecl->addAttr(newAttr);
  2557. foundAny = true;
  2558. }
  2559. }
  2560. if (!foundAny) newDecl->dropAttrs();
  2561. }
  2562. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2563. const ParmVarDecl *OldParam,
  2564. Sema &S) {
  2565. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2566. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2567. if (*Oldnullability != *Newnullability) {
  2568. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2569. << DiagNullabilityKind(
  2570. *Newnullability,
  2571. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2572. != 0))
  2573. << DiagNullabilityKind(
  2574. *Oldnullability,
  2575. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2576. != 0));
  2577. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2578. }
  2579. } else {
  2580. QualType NewT = NewParam->getType();
  2581. NewT = S.Context.getAttributedType(
  2582. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2583. NewT, NewT);
  2584. NewParam->setType(NewT);
  2585. }
  2586. }
  2587. }
  2588. namespace {
  2589. /// Used in MergeFunctionDecl to keep track of function parameters in
  2590. /// C.
  2591. struct GNUCompatibleParamWarning {
  2592. ParmVarDecl *OldParm;
  2593. ParmVarDecl *NewParm;
  2594. QualType PromotedType;
  2595. };
  2596. } // end anonymous namespace
  2597. /// getSpecialMember - get the special member enum for a method.
  2598. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2599. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2600. if (Ctor->isDefaultConstructor())
  2601. return Sema::CXXDefaultConstructor;
  2602. if (Ctor->isCopyConstructor())
  2603. return Sema::CXXCopyConstructor;
  2604. if (Ctor->isMoveConstructor())
  2605. return Sema::CXXMoveConstructor;
  2606. } else if (isa<CXXDestructorDecl>(MD)) {
  2607. return Sema::CXXDestructor;
  2608. } else if (MD->isCopyAssignmentOperator()) {
  2609. return Sema::CXXCopyAssignment;
  2610. } else if (MD->isMoveAssignmentOperator()) {
  2611. return Sema::CXXMoveAssignment;
  2612. }
  2613. return Sema::CXXInvalid;
  2614. }
  2615. // Determine whether the previous declaration was a definition, implicit
  2616. // declaration, or a declaration.
  2617. template <typename T>
  2618. static std::pair<diag::kind, SourceLocation>
  2619. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2620. diag::kind PrevDiag;
  2621. SourceLocation OldLocation = Old->getLocation();
  2622. if (Old->isThisDeclarationADefinition())
  2623. PrevDiag = diag::note_previous_definition;
  2624. else if (Old->isImplicit()) {
  2625. PrevDiag = diag::note_previous_implicit_declaration;
  2626. if (OldLocation.isInvalid())
  2627. OldLocation = New->getLocation();
  2628. } else
  2629. PrevDiag = diag::note_previous_declaration;
  2630. return std::make_pair(PrevDiag, OldLocation);
  2631. }
  2632. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2633. /// only extern inline functions can be redefined, and even then only in
  2634. /// GNU89 mode.
  2635. static bool canRedefineFunction(const FunctionDecl *FD,
  2636. const LangOptions& LangOpts) {
  2637. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2638. !LangOpts.CPlusPlus &&
  2639. FD->isInlineSpecified() &&
  2640. FD->getStorageClass() == SC_Extern);
  2641. }
  2642. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2643. const AttributedType *AT = T->getAs<AttributedType>();
  2644. while (AT && !AT->isCallingConv())
  2645. AT = AT->getModifiedType()->getAs<AttributedType>();
  2646. return AT;
  2647. }
  2648. template <typename T>
  2649. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2650. const DeclContext *DC = Old->getDeclContext();
  2651. if (DC->isRecord())
  2652. return false;
  2653. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2654. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2655. return true;
  2656. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2657. return true;
  2658. return false;
  2659. }
  2660. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2661. static bool isExternC(VarTemplateDecl *) { return false; }
  2662. /// Check whether a redeclaration of an entity introduced by a
  2663. /// using-declaration is valid, given that we know it's not an overload
  2664. /// (nor a hidden tag declaration).
  2665. template<typename ExpectedDecl>
  2666. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2667. ExpectedDecl *New) {
  2668. // C++11 [basic.scope.declarative]p4:
  2669. // Given a set of declarations in a single declarative region, each of
  2670. // which specifies the same unqualified name,
  2671. // -- they shall all refer to the same entity, or all refer to functions
  2672. // and function templates; or
  2673. // -- exactly one declaration shall declare a class name or enumeration
  2674. // name that is not a typedef name and the other declarations shall all
  2675. // refer to the same variable or enumerator, or all refer to functions
  2676. // and function templates; in this case the class name or enumeration
  2677. // name is hidden (3.3.10).
  2678. // C++11 [namespace.udecl]p14:
  2679. // If a function declaration in namespace scope or block scope has the
  2680. // same name and the same parameter-type-list as a function introduced
  2681. // by a using-declaration, and the declarations do not declare the same
  2682. // function, the program is ill-formed.
  2683. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2684. if (Old &&
  2685. !Old->getDeclContext()->getRedeclContext()->Equals(
  2686. New->getDeclContext()->getRedeclContext()) &&
  2687. !(isExternC(Old) && isExternC(New)))
  2688. Old = nullptr;
  2689. if (!Old) {
  2690. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2691. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2692. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2693. return true;
  2694. }
  2695. return false;
  2696. }
  2697. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2698. const FunctionDecl *B) {
  2699. assert(A->getNumParams() == B->getNumParams());
  2700. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2701. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2702. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2703. if (AttrA == AttrB)
  2704. return true;
  2705. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2706. AttrA->isDynamic() == AttrB->isDynamic();
  2707. };
  2708. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2709. }
  2710. /// If necessary, adjust the semantic declaration context for a qualified
  2711. /// declaration to name the correct inline namespace within the qualifier.
  2712. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2713. DeclaratorDecl *OldD) {
  2714. // The only case where we need to update the DeclContext is when
  2715. // redeclaration lookup for a qualified name finds a declaration
  2716. // in an inline namespace within the context named by the qualifier:
  2717. //
  2718. // inline namespace N { int f(); }
  2719. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2720. //
  2721. // For unqualified declarations, the semantic context *can* change
  2722. // along the redeclaration chain (for local extern declarations,
  2723. // extern "C" declarations, and friend declarations in particular).
  2724. if (!NewD->getQualifier())
  2725. return;
  2726. // NewD is probably already in the right context.
  2727. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2728. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2729. if (NamedDC->Equals(SemaDC))
  2730. return;
  2731. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2732. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2733. "unexpected context for redeclaration");
  2734. auto *LexDC = NewD->getLexicalDeclContext();
  2735. auto FixSemaDC = [=](NamedDecl *D) {
  2736. if (!D)
  2737. return;
  2738. D->setDeclContext(SemaDC);
  2739. D->setLexicalDeclContext(LexDC);
  2740. };
  2741. FixSemaDC(NewD);
  2742. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2743. FixSemaDC(FD->getDescribedFunctionTemplate());
  2744. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2745. FixSemaDC(VD->getDescribedVarTemplate());
  2746. }
  2747. /// MergeFunctionDecl - We just parsed a function 'New' from
  2748. /// declarator D which has the same name and scope as a previous
  2749. /// declaration 'Old'. Figure out how to resolve this situation,
  2750. /// merging decls or emitting diagnostics as appropriate.
  2751. ///
  2752. /// In C++, New and Old must be declarations that are not
  2753. /// overloaded. Use IsOverload to determine whether New and Old are
  2754. /// overloaded, and to select the Old declaration that New should be
  2755. /// merged with.
  2756. ///
  2757. /// Returns true if there was an error, false otherwise.
  2758. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2759. Scope *S, bool MergeTypeWithOld) {
  2760. // Verify the old decl was also a function.
  2761. FunctionDecl *Old = OldD->getAsFunction();
  2762. if (!Old) {
  2763. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2764. if (New->getFriendObjectKind()) {
  2765. Diag(New->getLocation(), diag::err_using_decl_friend);
  2766. Diag(Shadow->getTargetDecl()->getLocation(),
  2767. diag::note_using_decl_target);
  2768. Diag(Shadow->getUsingDecl()->getLocation(),
  2769. diag::note_using_decl) << 0;
  2770. return true;
  2771. }
  2772. // Check whether the two declarations might declare the same function.
  2773. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2774. return true;
  2775. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2776. } else {
  2777. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2778. << New->getDeclName();
  2779. notePreviousDefinition(OldD, New->getLocation());
  2780. return true;
  2781. }
  2782. }
  2783. // If the old declaration is invalid, just give up here.
  2784. if (Old->isInvalidDecl())
  2785. return true;
  2786. // Disallow redeclaration of some builtins.
  2787. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2788. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2789. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2790. << Old << Old->getType();
  2791. return true;
  2792. }
  2793. diag::kind PrevDiag;
  2794. SourceLocation OldLocation;
  2795. std::tie(PrevDiag, OldLocation) =
  2796. getNoteDiagForInvalidRedeclaration(Old, New);
  2797. // Don't complain about this if we're in GNU89 mode and the old function
  2798. // is an extern inline function.
  2799. // Don't complain about specializations. They are not supposed to have
  2800. // storage classes.
  2801. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2802. New->getStorageClass() == SC_Static &&
  2803. Old->hasExternalFormalLinkage() &&
  2804. !New->getTemplateSpecializationInfo() &&
  2805. !canRedefineFunction(Old, getLangOpts())) {
  2806. if (getLangOpts().MicrosoftExt) {
  2807. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2808. Diag(OldLocation, PrevDiag);
  2809. } else {
  2810. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2811. Diag(OldLocation, PrevDiag);
  2812. return true;
  2813. }
  2814. }
  2815. if (New->hasAttr<InternalLinkageAttr>() &&
  2816. !Old->hasAttr<InternalLinkageAttr>()) {
  2817. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2818. << New->getDeclName();
  2819. notePreviousDefinition(Old, New->getLocation());
  2820. New->dropAttr<InternalLinkageAttr>();
  2821. }
  2822. if (CheckRedeclarationModuleOwnership(New, Old))
  2823. return true;
  2824. if (!getLangOpts().CPlusPlus) {
  2825. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2826. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2827. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2828. << New << OldOvl;
  2829. // Try our best to find a decl that actually has the overloadable
  2830. // attribute for the note. In most cases (e.g. programs with only one
  2831. // broken declaration/definition), this won't matter.
  2832. //
  2833. // FIXME: We could do this if we juggled some extra state in
  2834. // OverloadableAttr, rather than just removing it.
  2835. const Decl *DiagOld = Old;
  2836. if (OldOvl) {
  2837. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2838. const auto *A = D->getAttr<OverloadableAttr>();
  2839. return A && !A->isImplicit();
  2840. });
  2841. // If we've implicitly added *all* of the overloadable attrs to this
  2842. // chain, emitting a "previous redecl" note is pointless.
  2843. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2844. }
  2845. if (DiagOld)
  2846. Diag(DiagOld->getLocation(),
  2847. diag::note_attribute_overloadable_prev_overload)
  2848. << OldOvl;
  2849. if (OldOvl)
  2850. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2851. else
  2852. New->dropAttr<OverloadableAttr>();
  2853. }
  2854. }
  2855. // If a function is first declared with a calling convention, but is later
  2856. // declared or defined without one, all following decls assume the calling
  2857. // convention of the first.
  2858. //
  2859. // It's OK if a function is first declared without a calling convention,
  2860. // but is later declared or defined with the default calling convention.
  2861. //
  2862. // To test if either decl has an explicit calling convention, we look for
  2863. // AttributedType sugar nodes on the type as written. If they are missing or
  2864. // were canonicalized away, we assume the calling convention was implicit.
  2865. //
  2866. // Note also that we DO NOT return at this point, because we still have
  2867. // other tests to run.
  2868. QualType OldQType = Context.getCanonicalType(Old->getType());
  2869. QualType NewQType = Context.getCanonicalType(New->getType());
  2870. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2871. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2872. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2873. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2874. bool RequiresAdjustment = false;
  2875. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2876. FunctionDecl *First = Old->getFirstDecl();
  2877. const FunctionType *FT =
  2878. First->getType().getCanonicalType()->castAs<FunctionType>();
  2879. FunctionType::ExtInfo FI = FT->getExtInfo();
  2880. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2881. if (!NewCCExplicit) {
  2882. // Inherit the CC from the previous declaration if it was specified
  2883. // there but not here.
  2884. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2885. RequiresAdjustment = true;
  2886. } else if (New->getBuiltinID()) {
  2887. // Calling Conventions on a Builtin aren't really useful and setting a
  2888. // default calling convention and cdecl'ing some builtin redeclarations is
  2889. // common, so warn and ignore the calling convention on the redeclaration.
  2890. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  2891. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2892. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2893. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2894. RequiresAdjustment = true;
  2895. } else {
  2896. // Calling conventions aren't compatible, so complain.
  2897. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2898. Diag(New->getLocation(), diag::err_cconv_change)
  2899. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2900. << !FirstCCExplicit
  2901. << (!FirstCCExplicit ? "" :
  2902. FunctionType::getNameForCallConv(FI.getCC()));
  2903. // Put the note on the first decl, since it is the one that matters.
  2904. Diag(First->getLocation(), diag::note_previous_declaration);
  2905. return true;
  2906. }
  2907. }
  2908. // FIXME: diagnose the other way around?
  2909. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2910. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2911. RequiresAdjustment = true;
  2912. }
  2913. // Merge regparm attribute.
  2914. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2915. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2916. if (NewTypeInfo.getHasRegParm()) {
  2917. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2918. << NewType->getRegParmType()
  2919. << OldType->getRegParmType();
  2920. Diag(OldLocation, diag::note_previous_declaration);
  2921. return true;
  2922. }
  2923. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2924. RequiresAdjustment = true;
  2925. }
  2926. // Merge ns_returns_retained attribute.
  2927. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2928. if (NewTypeInfo.getProducesResult()) {
  2929. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2930. << "'ns_returns_retained'";
  2931. Diag(OldLocation, diag::note_previous_declaration);
  2932. return true;
  2933. }
  2934. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2935. RequiresAdjustment = true;
  2936. }
  2937. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2938. NewTypeInfo.getNoCallerSavedRegs()) {
  2939. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2940. AnyX86NoCallerSavedRegistersAttr *Attr =
  2941. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2942. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2943. Diag(OldLocation, diag::note_previous_declaration);
  2944. return true;
  2945. }
  2946. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2947. RequiresAdjustment = true;
  2948. }
  2949. if (RequiresAdjustment) {
  2950. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2951. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2952. New->setType(QualType(AdjustedType, 0));
  2953. NewQType = Context.getCanonicalType(New->getType());
  2954. }
  2955. // If this redeclaration makes the function inline, we may need to add it to
  2956. // UndefinedButUsed.
  2957. if (!Old->isInlined() && New->isInlined() &&
  2958. !New->hasAttr<GNUInlineAttr>() &&
  2959. !getLangOpts().GNUInline &&
  2960. Old->isUsed(false) &&
  2961. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2962. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2963. SourceLocation()));
  2964. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2965. // about it.
  2966. if (New->hasAttr<GNUInlineAttr>() &&
  2967. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2968. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2969. }
  2970. // If pass_object_size params don't match up perfectly, this isn't a valid
  2971. // redeclaration.
  2972. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2973. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2974. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2975. << New->getDeclName();
  2976. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2977. return true;
  2978. }
  2979. if (getLangOpts().CPlusPlus) {
  2980. // C++1z [over.load]p2
  2981. // Certain function declarations cannot be overloaded:
  2982. // -- Function declarations that differ only in the return type,
  2983. // the exception specification, or both cannot be overloaded.
  2984. // Check the exception specifications match. This may recompute the type of
  2985. // both Old and New if it resolved exception specifications, so grab the
  2986. // types again after this. Because this updates the type, we do this before
  2987. // any of the other checks below, which may update the "de facto" NewQType
  2988. // but do not necessarily update the type of New.
  2989. if (CheckEquivalentExceptionSpec(Old, New))
  2990. return true;
  2991. OldQType = Context.getCanonicalType(Old->getType());
  2992. NewQType = Context.getCanonicalType(New->getType());
  2993. // Go back to the type source info to compare the declared return types,
  2994. // per C++1y [dcl.type.auto]p13:
  2995. // Redeclarations or specializations of a function or function template
  2996. // with a declared return type that uses a placeholder type shall also
  2997. // use that placeholder, not a deduced type.
  2998. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  2999. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  3000. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  3001. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  3002. OldDeclaredReturnType)) {
  3003. QualType ResQT;
  3004. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  3005. OldDeclaredReturnType->isObjCObjectPointerType())
  3006. // FIXME: This does the wrong thing for a deduced return type.
  3007. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  3008. if (ResQT.isNull()) {
  3009. if (New->isCXXClassMember() && New->isOutOfLine())
  3010. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  3011. << New << New->getReturnTypeSourceRange();
  3012. else
  3013. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  3014. << New->getReturnTypeSourceRange();
  3015. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  3016. << Old->getReturnTypeSourceRange();
  3017. return true;
  3018. }
  3019. else
  3020. NewQType = ResQT;
  3021. }
  3022. QualType OldReturnType = OldType->getReturnType();
  3023. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  3024. if (OldReturnType != NewReturnType) {
  3025. // If this function has a deduced return type and has already been
  3026. // defined, copy the deduced value from the old declaration.
  3027. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  3028. if (OldAT && OldAT->isDeduced()) {
  3029. New->setType(
  3030. SubstAutoType(New->getType(),
  3031. OldAT->isDependentType() ? Context.DependentTy
  3032. : OldAT->getDeducedType()));
  3033. NewQType = Context.getCanonicalType(
  3034. SubstAutoType(NewQType,
  3035. OldAT->isDependentType() ? Context.DependentTy
  3036. : OldAT->getDeducedType()));
  3037. }
  3038. }
  3039. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  3040. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  3041. if (OldMethod && NewMethod) {
  3042. // Preserve triviality.
  3043. NewMethod->setTrivial(OldMethod->isTrivial());
  3044. // MSVC allows explicit template specialization at class scope:
  3045. // 2 CXXMethodDecls referring to the same function will be injected.
  3046. // We don't want a redeclaration error.
  3047. bool IsClassScopeExplicitSpecialization =
  3048. OldMethod->isFunctionTemplateSpecialization() &&
  3049. NewMethod->isFunctionTemplateSpecialization();
  3050. bool isFriend = NewMethod->getFriendObjectKind();
  3051. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  3052. !IsClassScopeExplicitSpecialization) {
  3053. // -- Member function declarations with the same name and the
  3054. // same parameter types cannot be overloaded if any of them
  3055. // is a static member function declaration.
  3056. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  3057. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  3058. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3059. return true;
  3060. }
  3061. // C++ [class.mem]p1:
  3062. // [...] A member shall not be declared twice in the
  3063. // member-specification, except that a nested class or member
  3064. // class template can be declared and then later defined.
  3065. if (!inTemplateInstantiation()) {
  3066. unsigned NewDiag;
  3067. if (isa<CXXConstructorDecl>(OldMethod))
  3068. NewDiag = diag::err_constructor_redeclared;
  3069. else if (isa<CXXDestructorDecl>(NewMethod))
  3070. NewDiag = diag::err_destructor_redeclared;
  3071. else if (isa<CXXConversionDecl>(NewMethod))
  3072. NewDiag = diag::err_conv_function_redeclared;
  3073. else
  3074. NewDiag = diag::err_member_redeclared;
  3075. Diag(New->getLocation(), NewDiag);
  3076. } else {
  3077. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  3078. << New << New->getType();
  3079. }
  3080. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3081. return true;
  3082. // Complain if this is an explicit declaration of a special
  3083. // member that was initially declared implicitly.
  3084. //
  3085. // As an exception, it's okay to befriend such methods in order
  3086. // to permit the implicit constructor/destructor/operator calls.
  3087. } else if (OldMethod->isImplicit()) {
  3088. if (isFriend) {
  3089. NewMethod->setImplicit();
  3090. } else {
  3091. Diag(NewMethod->getLocation(),
  3092. diag::err_definition_of_implicitly_declared_member)
  3093. << New << getSpecialMember(OldMethod);
  3094. return true;
  3095. }
  3096. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3097. Diag(NewMethod->getLocation(),
  3098. diag::err_definition_of_explicitly_defaulted_member)
  3099. << getSpecialMember(OldMethod);
  3100. return true;
  3101. }
  3102. }
  3103. // C++11 [dcl.attr.noreturn]p1:
  3104. // The first declaration of a function shall specify the noreturn
  3105. // attribute if any declaration of that function specifies the noreturn
  3106. // attribute.
  3107. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3108. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3109. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3110. Diag(Old->getFirstDecl()->getLocation(),
  3111. diag::note_noreturn_missing_first_decl);
  3112. }
  3113. // C++11 [dcl.attr.depend]p2:
  3114. // The first declaration of a function shall specify the
  3115. // carries_dependency attribute for its declarator-id if any declaration
  3116. // of the function specifies the carries_dependency attribute.
  3117. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3118. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3119. Diag(CDA->getLocation(),
  3120. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3121. Diag(Old->getFirstDecl()->getLocation(),
  3122. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3123. }
  3124. // (C++98 8.3.5p3):
  3125. // All declarations for a function shall agree exactly in both the
  3126. // return type and the parameter-type-list.
  3127. // We also want to respect all the extended bits except noreturn.
  3128. // noreturn should now match unless the old type info didn't have it.
  3129. QualType OldQTypeForComparison = OldQType;
  3130. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3131. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3132. const FunctionType *OldTypeForComparison
  3133. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3134. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3135. assert(OldQTypeForComparison.isCanonical());
  3136. }
  3137. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3138. // As a special case, retain the language linkage from previous
  3139. // declarations of a friend function as an extension.
  3140. //
  3141. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3142. // and is useful because there's otherwise no way to specify language
  3143. // linkage within class scope.
  3144. //
  3145. // Check cautiously as the friend object kind isn't yet complete.
  3146. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3147. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3148. Diag(OldLocation, PrevDiag);
  3149. } else {
  3150. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3151. Diag(OldLocation, PrevDiag);
  3152. return true;
  3153. }
  3154. }
  3155. // If the function types are compatible, merge the declarations. Ignore the
  3156. // exception specifier because it was already checked above in
  3157. // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
  3158. // about incompatible types under -fms-compatibility.
  3159. if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
  3160. NewQType))
  3161. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3162. // If the types are imprecise (due to dependent constructs in friends or
  3163. // local extern declarations), it's OK if they differ. We'll check again
  3164. // during instantiation.
  3165. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3166. return false;
  3167. // Fall through for conflicting redeclarations and redefinitions.
  3168. }
  3169. // C: Function types need to be compatible, not identical. This handles
  3170. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3171. if (!getLangOpts().CPlusPlus &&
  3172. Context.typesAreCompatible(OldQType, NewQType)) {
  3173. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3174. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3175. const FunctionProtoType *OldProto = nullptr;
  3176. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3177. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3178. // The old declaration provided a function prototype, but the
  3179. // new declaration does not. Merge in the prototype.
  3180. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3181. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3182. NewQType =
  3183. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3184. OldProto->getExtProtoInfo());
  3185. New->setType(NewQType);
  3186. New->setHasInheritedPrototype();
  3187. // Synthesize parameters with the same types.
  3188. SmallVector<ParmVarDecl*, 16> Params;
  3189. for (const auto &ParamType : OldProto->param_types()) {
  3190. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3191. SourceLocation(), nullptr,
  3192. ParamType, /*TInfo=*/nullptr,
  3193. SC_None, nullptr);
  3194. Param->setScopeInfo(0, Params.size());
  3195. Param->setImplicit();
  3196. Params.push_back(Param);
  3197. }
  3198. New->setParams(Params);
  3199. }
  3200. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3201. }
  3202. // GNU C permits a K&R definition to follow a prototype declaration
  3203. // if the declared types of the parameters in the K&R definition
  3204. // match the types in the prototype declaration, even when the
  3205. // promoted types of the parameters from the K&R definition differ
  3206. // from the types in the prototype. GCC then keeps the types from
  3207. // the prototype.
  3208. //
  3209. // If a variadic prototype is followed by a non-variadic K&R definition,
  3210. // the K&R definition becomes variadic. This is sort of an edge case, but
  3211. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3212. // C99 6.9.1p8.
  3213. if (!getLangOpts().CPlusPlus &&
  3214. Old->hasPrototype() && !New->hasPrototype() &&
  3215. New->getType()->getAs<FunctionProtoType>() &&
  3216. Old->getNumParams() == New->getNumParams()) {
  3217. SmallVector<QualType, 16> ArgTypes;
  3218. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3219. const FunctionProtoType *OldProto
  3220. = Old->getType()->getAs<FunctionProtoType>();
  3221. const FunctionProtoType *NewProto
  3222. = New->getType()->getAs<FunctionProtoType>();
  3223. // Determine whether this is the GNU C extension.
  3224. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3225. NewProto->getReturnType());
  3226. bool LooseCompatible = !MergedReturn.isNull();
  3227. for (unsigned Idx = 0, End = Old->getNumParams();
  3228. LooseCompatible && Idx != End; ++Idx) {
  3229. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3230. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3231. if (Context.typesAreCompatible(OldParm->getType(),
  3232. NewProto->getParamType(Idx))) {
  3233. ArgTypes.push_back(NewParm->getType());
  3234. } else if (Context.typesAreCompatible(OldParm->getType(),
  3235. NewParm->getType(),
  3236. /*CompareUnqualified=*/true)) {
  3237. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3238. NewProto->getParamType(Idx) };
  3239. Warnings.push_back(Warn);
  3240. ArgTypes.push_back(NewParm->getType());
  3241. } else
  3242. LooseCompatible = false;
  3243. }
  3244. if (LooseCompatible) {
  3245. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3246. Diag(Warnings[Warn].NewParm->getLocation(),
  3247. diag::ext_param_promoted_not_compatible_with_prototype)
  3248. << Warnings[Warn].PromotedType
  3249. << Warnings[Warn].OldParm->getType();
  3250. if (Warnings[Warn].OldParm->getLocation().isValid())
  3251. Diag(Warnings[Warn].OldParm->getLocation(),
  3252. diag::note_previous_declaration);
  3253. }
  3254. if (MergeTypeWithOld)
  3255. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3256. OldProto->getExtProtoInfo()));
  3257. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3258. }
  3259. // Fall through to diagnose conflicting types.
  3260. }
  3261. // A function that has already been declared has been redeclared or
  3262. // defined with a different type; show an appropriate diagnostic.
  3263. // If the previous declaration was an implicitly-generated builtin
  3264. // declaration, then at the very least we should use a specialized note.
  3265. unsigned BuiltinID;
  3266. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3267. // If it's actually a library-defined builtin function like 'malloc'
  3268. // or 'printf', just warn about the incompatible redeclaration.
  3269. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3270. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3271. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3272. << Old << Old->getType();
  3273. // If this is a global redeclaration, just forget hereafter
  3274. // about the "builtin-ness" of the function.
  3275. //
  3276. // Doing this for local extern declarations is problematic. If
  3277. // the builtin declaration remains visible, a second invalid
  3278. // local declaration will produce a hard error; if it doesn't
  3279. // remain visible, a single bogus local redeclaration (which is
  3280. // actually only a warning) could break all the downstream code.
  3281. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3282. New->getIdentifier()->revertBuiltin();
  3283. return false;
  3284. }
  3285. PrevDiag = diag::note_previous_builtin_declaration;
  3286. }
  3287. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3288. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3289. return true;
  3290. }
  3291. /// Completes the merge of two function declarations that are
  3292. /// known to be compatible.
  3293. ///
  3294. /// This routine handles the merging of attributes and other
  3295. /// properties of function declarations from the old declaration to
  3296. /// the new declaration, once we know that New is in fact a
  3297. /// redeclaration of Old.
  3298. ///
  3299. /// \returns false
  3300. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3301. Scope *S, bool MergeTypeWithOld) {
  3302. // Merge the attributes
  3303. mergeDeclAttributes(New, Old);
  3304. // Merge "pure" flag.
  3305. if (Old->isPure())
  3306. New->setPure();
  3307. // Merge "used" flag.
  3308. if (Old->getMostRecentDecl()->isUsed(false))
  3309. New->setIsUsed();
  3310. // Merge attributes from the parameters. These can mismatch with K&R
  3311. // declarations.
  3312. if (New->getNumParams() == Old->getNumParams())
  3313. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3314. ParmVarDecl *NewParam = New->getParamDecl(i);
  3315. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3316. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3317. mergeParamDeclTypes(NewParam, OldParam, *this);
  3318. }
  3319. if (getLangOpts().CPlusPlus)
  3320. return MergeCXXFunctionDecl(New, Old, S);
  3321. // Merge the function types so the we get the composite types for the return
  3322. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3323. // was visible.
  3324. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3325. if (!Merged.isNull() && MergeTypeWithOld)
  3326. New->setType(Merged);
  3327. return false;
  3328. }
  3329. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3330. ObjCMethodDecl *oldMethod) {
  3331. // Merge the attributes, including deprecated/unavailable
  3332. AvailabilityMergeKind MergeKind =
  3333. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3334. ? AMK_ProtocolImplementation
  3335. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3336. : AMK_Override;
  3337. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3338. // Merge attributes from the parameters.
  3339. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3340. oe = oldMethod->param_end();
  3341. for (ObjCMethodDecl::param_iterator
  3342. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3343. ni != ne && oi != oe; ++ni, ++oi)
  3344. mergeParamDeclAttributes(*ni, *oi, *this);
  3345. CheckObjCMethodOverride(newMethod, oldMethod);
  3346. }
  3347. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3348. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3349. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3350. ? diag::err_redefinition_different_type
  3351. : diag::err_redeclaration_different_type)
  3352. << New->getDeclName() << New->getType() << Old->getType();
  3353. diag::kind PrevDiag;
  3354. SourceLocation OldLocation;
  3355. std::tie(PrevDiag, OldLocation)
  3356. = getNoteDiagForInvalidRedeclaration(Old, New);
  3357. S.Diag(OldLocation, PrevDiag);
  3358. New->setInvalidDecl();
  3359. }
  3360. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3361. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3362. /// emitting diagnostics as appropriate.
  3363. ///
  3364. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3365. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3366. /// is attached.
  3367. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3368. bool MergeTypeWithOld) {
  3369. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3370. return;
  3371. QualType MergedT;
  3372. if (getLangOpts().CPlusPlus) {
  3373. if (New->getType()->isUndeducedType()) {
  3374. // We don't know what the new type is until the initializer is attached.
  3375. return;
  3376. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3377. // These could still be something that needs exception specs checked.
  3378. return MergeVarDeclExceptionSpecs(New, Old);
  3379. }
  3380. // C++ [basic.link]p10:
  3381. // [...] the types specified by all declarations referring to a given
  3382. // object or function shall be identical, except that declarations for an
  3383. // array object can specify array types that differ by the presence or
  3384. // absence of a major array bound (8.3.4).
  3385. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3386. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3387. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3388. // We are merging a variable declaration New into Old. If it has an array
  3389. // bound, and that bound differs from Old's bound, we should diagnose the
  3390. // mismatch.
  3391. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3392. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3393. PrevVD = PrevVD->getPreviousDecl()) {
  3394. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3395. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3396. continue;
  3397. if (!Context.hasSameType(NewArray, PrevVDTy))
  3398. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3399. }
  3400. }
  3401. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3402. if (Context.hasSameType(OldArray->getElementType(),
  3403. NewArray->getElementType()))
  3404. MergedT = New->getType();
  3405. }
  3406. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3407. // has no array bound, it should not inherit one from Old, if Old is not
  3408. // visible.
  3409. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3410. if (Context.hasSameType(OldArray->getElementType(),
  3411. NewArray->getElementType()))
  3412. MergedT = Old->getType();
  3413. }
  3414. }
  3415. else if (New->getType()->isObjCObjectPointerType() &&
  3416. Old->getType()->isObjCObjectPointerType()) {
  3417. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3418. Old->getType());
  3419. }
  3420. } else {
  3421. // C 6.2.7p2:
  3422. // All declarations that refer to the same object or function shall have
  3423. // compatible type.
  3424. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3425. }
  3426. if (MergedT.isNull()) {
  3427. // It's OK if we couldn't merge types if either type is dependent, for a
  3428. // block-scope variable. In other cases (static data members of class
  3429. // templates, variable templates, ...), we require the types to be
  3430. // equivalent.
  3431. // FIXME: The C++ standard doesn't say anything about this.
  3432. if ((New->getType()->isDependentType() ||
  3433. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3434. // If the old type was dependent, we can't merge with it, so the new type
  3435. // becomes dependent for now. We'll reproduce the original type when we
  3436. // instantiate the TypeSourceInfo for the variable.
  3437. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3438. New->setType(Context.DependentTy);
  3439. return;
  3440. }
  3441. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3442. }
  3443. // Don't actually update the type on the new declaration if the old
  3444. // declaration was an extern declaration in a different scope.
  3445. if (MergeTypeWithOld)
  3446. New->setType(MergedT);
  3447. }
  3448. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3449. LookupResult &Previous) {
  3450. // C11 6.2.7p4:
  3451. // For an identifier with internal or external linkage declared
  3452. // in a scope in which a prior declaration of that identifier is
  3453. // visible, if the prior declaration specifies internal or
  3454. // external linkage, the type of the identifier at the later
  3455. // declaration becomes the composite type.
  3456. //
  3457. // If the variable isn't visible, we do not merge with its type.
  3458. if (Previous.isShadowed())
  3459. return false;
  3460. if (S.getLangOpts().CPlusPlus) {
  3461. // C++11 [dcl.array]p3:
  3462. // If there is a preceding declaration of the entity in the same
  3463. // scope in which the bound was specified, an omitted array bound
  3464. // is taken to be the same as in that earlier declaration.
  3465. return NewVD->isPreviousDeclInSameBlockScope() ||
  3466. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3467. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3468. } else {
  3469. // If the old declaration was function-local, don't merge with its
  3470. // type unless we're in the same function.
  3471. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3472. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3473. }
  3474. }
  3475. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3476. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3477. /// situation, merging decls or emitting diagnostics as appropriate.
  3478. ///
  3479. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3480. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3481. /// definitions here, since the initializer hasn't been attached.
  3482. ///
  3483. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3484. // If the new decl is already invalid, don't do any other checking.
  3485. if (New->isInvalidDecl())
  3486. return;
  3487. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3488. return;
  3489. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3490. // Verify the old decl was also a variable or variable template.
  3491. VarDecl *Old = nullptr;
  3492. VarTemplateDecl *OldTemplate = nullptr;
  3493. if (Previous.isSingleResult()) {
  3494. if (NewTemplate) {
  3495. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3496. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3497. if (auto *Shadow =
  3498. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3499. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3500. return New->setInvalidDecl();
  3501. } else {
  3502. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3503. if (auto *Shadow =
  3504. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3505. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3506. return New->setInvalidDecl();
  3507. }
  3508. }
  3509. if (!Old) {
  3510. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3511. << New->getDeclName();
  3512. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3513. New->getLocation());
  3514. return New->setInvalidDecl();
  3515. }
  3516. // Ensure the template parameters are compatible.
  3517. if (NewTemplate &&
  3518. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3519. OldTemplate->getTemplateParameters(),
  3520. /*Complain=*/true, TPL_TemplateMatch))
  3521. return New->setInvalidDecl();
  3522. // C++ [class.mem]p1:
  3523. // A member shall not be declared twice in the member-specification [...]
  3524. //
  3525. // Here, we need only consider static data members.
  3526. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3527. Diag(New->getLocation(), diag::err_duplicate_member)
  3528. << New->getIdentifier();
  3529. Diag(Old->getLocation(), diag::note_previous_declaration);
  3530. New->setInvalidDecl();
  3531. }
  3532. mergeDeclAttributes(New, Old);
  3533. // Warn if an already-declared variable is made a weak_import in a subsequent
  3534. // declaration
  3535. if (New->hasAttr<WeakImportAttr>() &&
  3536. Old->getStorageClass() == SC_None &&
  3537. !Old->hasAttr<WeakImportAttr>()) {
  3538. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3539. notePreviousDefinition(Old, New->getLocation());
  3540. // Remove weak_import attribute on new declaration.
  3541. New->dropAttr<WeakImportAttr>();
  3542. }
  3543. if (New->hasAttr<InternalLinkageAttr>() &&
  3544. !Old->hasAttr<InternalLinkageAttr>()) {
  3545. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3546. << New->getDeclName();
  3547. notePreviousDefinition(Old, New->getLocation());
  3548. New->dropAttr<InternalLinkageAttr>();
  3549. }
  3550. // Merge the types.
  3551. VarDecl *MostRecent = Old->getMostRecentDecl();
  3552. if (MostRecent != Old) {
  3553. MergeVarDeclTypes(New, MostRecent,
  3554. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3555. if (New->isInvalidDecl())
  3556. return;
  3557. }
  3558. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3559. if (New->isInvalidDecl())
  3560. return;
  3561. diag::kind PrevDiag;
  3562. SourceLocation OldLocation;
  3563. std::tie(PrevDiag, OldLocation) =
  3564. getNoteDiagForInvalidRedeclaration(Old, New);
  3565. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3566. if (New->getStorageClass() == SC_Static &&
  3567. !New->isStaticDataMember() &&
  3568. Old->hasExternalFormalLinkage()) {
  3569. if (getLangOpts().MicrosoftExt) {
  3570. Diag(New->getLocation(), diag::ext_static_non_static)
  3571. << New->getDeclName();
  3572. Diag(OldLocation, PrevDiag);
  3573. } else {
  3574. Diag(New->getLocation(), diag::err_static_non_static)
  3575. << New->getDeclName();
  3576. Diag(OldLocation, PrevDiag);
  3577. return New->setInvalidDecl();
  3578. }
  3579. }
  3580. // C99 6.2.2p4:
  3581. // For an identifier declared with the storage-class specifier
  3582. // extern in a scope in which a prior declaration of that
  3583. // identifier is visible,23) if the prior declaration specifies
  3584. // internal or external linkage, the linkage of the identifier at
  3585. // the later declaration is the same as the linkage specified at
  3586. // the prior declaration. If no prior declaration is visible, or
  3587. // if the prior declaration specifies no linkage, then the
  3588. // identifier has external linkage.
  3589. if (New->hasExternalStorage() && Old->hasLinkage())
  3590. /* Okay */;
  3591. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3592. !New->isStaticDataMember() &&
  3593. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3594. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3595. Diag(OldLocation, PrevDiag);
  3596. return New->setInvalidDecl();
  3597. }
  3598. // Check if extern is followed by non-extern and vice-versa.
  3599. if (New->hasExternalStorage() &&
  3600. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3601. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3602. Diag(OldLocation, PrevDiag);
  3603. return New->setInvalidDecl();
  3604. }
  3605. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3606. !New->hasExternalStorage()) {
  3607. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3608. Diag(OldLocation, PrevDiag);
  3609. return New->setInvalidDecl();
  3610. }
  3611. if (CheckRedeclarationModuleOwnership(New, Old))
  3612. return;
  3613. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3614. // FIXME: The test for external storage here seems wrong? We still
  3615. // need to check for mismatches.
  3616. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3617. // Don't complain about out-of-line definitions of static members.
  3618. !(Old->getLexicalDeclContext()->isRecord() &&
  3619. !New->getLexicalDeclContext()->isRecord())) {
  3620. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3621. Diag(OldLocation, PrevDiag);
  3622. return New->setInvalidDecl();
  3623. }
  3624. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3625. if (VarDecl *Def = Old->getDefinition()) {
  3626. // C++1z [dcl.fcn.spec]p4:
  3627. // If the definition of a variable appears in a translation unit before
  3628. // its first declaration as inline, the program is ill-formed.
  3629. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3630. Diag(Def->getLocation(), diag::note_previous_definition);
  3631. }
  3632. }
  3633. // If this redeclaration makes the variable inline, we may need to add it to
  3634. // UndefinedButUsed.
  3635. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3636. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3637. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3638. SourceLocation()));
  3639. if (New->getTLSKind() != Old->getTLSKind()) {
  3640. if (!Old->getTLSKind()) {
  3641. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3642. Diag(OldLocation, PrevDiag);
  3643. } else if (!New->getTLSKind()) {
  3644. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3645. Diag(OldLocation, PrevDiag);
  3646. } else {
  3647. // Do not allow redeclaration to change the variable between requiring
  3648. // static and dynamic initialization.
  3649. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3650. // declaration to determine the kind. Do we need to be compatible here?
  3651. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3652. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3653. Diag(OldLocation, PrevDiag);
  3654. }
  3655. }
  3656. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3657. if (getLangOpts().CPlusPlus &&
  3658. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3659. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3660. Old->getCanonicalDecl()->isConstexpr()) {
  3661. // This definition won't be a definition any more once it's been merged.
  3662. Diag(New->getLocation(),
  3663. diag::warn_deprecated_redundant_constexpr_static_def);
  3664. } else if (VarDecl *Def = Old->getDefinition()) {
  3665. if (checkVarDeclRedefinition(Def, New))
  3666. return;
  3667. }
  3668. }
  3669. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3670. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3671. Diag(OldLocation, PrevDiag);
  3672. New->setInvalidDecl();
  3673. return;
  3674. }
  3675. // Merge "used" flag.
  3676. if (Old->getMostRecentDecl()->isUsed(false))
  3677. New->setIsUsed();
  3678. // Keep a chain of previous declarations.
  3679. New->setPreviousDecl(Old);
  3680. if (NewTemplate)
  3681. NewTemplate->setPreviousDecl(OldTemplate);
  3682. adjustDeclContextForDeclaratorDecl(New, Old);
  3683. // Inherit access appropriately.
  3684. New->setAccess(Old->getAccess());
  3685. if (NewTemplate)
  3686. NewTemplate->setAccess(New->getAccess());
  3687. if (Old->isInline())
  3688. New->setImplicitlyInline();
  3689. }
  3690. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3691. SourceManager &SrcMgr = getSourceManager();
  3692. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3693. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3694. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3695. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3696. auto &HSI = PP.getHeaderSearchInfo();
  3697. StringRef HdrFilename =
  3698. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3699. auto noteFromModuleOrInclude = [&](Module *Mod,
  3700. SourceLocation IncLoc) -> bool {
  3701. // Redefinition errors with modules are common with non modular mapped
  3702. // headers, example: a non-modular header H in module A that also gets
  3703. // included directly in a TU. Pointing twice to the same header/definition
  3704. // is confusing, try to get better diagnostics when modules is on.
  3705. if (IncLoc.isValid()) {
  3706. if (Mod) {
  3707. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3708. << HdrFilename.str() << Mod->getFullModuleName();
  3709. if (!Mod->DefinitionLoc.isInvalid())
  3710. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3711. << Mod->getFullModuleName();
  3712. } else {
  3713. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3714. << HdrFilename.str();
  3715. }
  3716. return true;
  3717. }
  3718. return false;
  3719. };
  3720. // Is it the same file and same offset? Provide more information on why
  3721. // this leads to a redefinition error.
  3722. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3723. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3724. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3725. bool EmittedDiag =
  3726. noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3727. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3728. // If the header has no guards, emit a note suggesting one.
  3729. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3730. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3731. if (EmittedDiag)
  3732. return;
  3733. }
  3734. // Redefinition coming from different files or couldn't do better above.
  3735. if (Old->getLocation().isValid())
  3736. Diag(Old->getLocation(), diag::note_previous_definition);
  3737. }
  3738. /// We've just determined that \p Old and \p New both appear to be definitions
  3739. /// of the same variable. Either diagnose or fix the problem.
  3740. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3741. if (!hasVisibleDefinition(Old) &&
  3742. (New->getFormalLinkage() == InternalLinkage ||
  3743. New->isInline() ||
  3744. New->getDescribedVarTemplate() ||
  3745. New->getNumTemplateParameterLists() ||
  3746. New->getDeclContext()->isDependentContext())) {
  3747. // The previous definition is hidden, and multiple definitions are
  3748. // permitted (in separate TUs). Demote this to a declaration.
  3749. New->demoteThisDefinitionToDeclaration();
  3750. // Make the canonical definition visible.
  3751. if (auto *OldTD = Old->getDescribedVarTemplate())
  3752. makeMergedDefinitionVisible(OldTD);
  3753. makeMergedDefinitionVisible(Old);
  3754. return false;
  3755. } else {
  3756. Diag(New->getLocation(), diag::err_redefinition) << New;
  3757. notePreviousDefinition(Old, New->getLocation());
  3758. New->setInvalidDecl();
  3759. return true;
  3760. }
  3761. }
  3762. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3763. /// no declarator (e.g. "struct foo;") is parsed.
  3764. Decl *
  3765. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3766. RecordDecl *&AnonRecord) {
  3767. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3768. AnonRecord);
  3769. }
  3770. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3771. // disambiguate entities defined in different scopes.
  3772. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3773. // compatibility.
  3774. // We will pick our mangling number depending on which version of MSVC is being
  3775. // targeted.
  3776. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3777. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3778. ? S->getMSCurManglingNumber()
  3779. : S->getMSLastManglingNumber();
  3780. }
  3781. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3782. if (!Context.getLangOpts().CPlusPlus)
  3783. return;
  3784. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3785. // If this tag is the direct child of a class, number it if
  3786. // it is anonymous.
  3787. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3788. return;
  3789. MangleNumberingContext &MCtx =
  3790. Context.getManglingNumberContext(Tag->getParent());
  3791. Context.setManglingNumber(
  3792. Tag, MCtx.getManglingNumber(
  3793. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3794. return;
  3795. }
  3796. // If this tag isn't a direct child of a class, number it if it is local.
  3797. Decl *ManglingContextDecl;
  3798. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3799. Tag->getDeclContext(), ManglingContextDecl)) {
  3800. Context.setManglingNumber(
  3801. Tag, MCtx->getManglingNumber(
  3802. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3803. }
  3804. }
  3805. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3806. TypedefNameDecl *NewTD) {
  3807. if (TagFromDeclSpec->isInvalidDecl())
  3808. return;
  3809. // Do nothing if the tag already has a name for linkage purposes.
  3810. if (TagFromDeclSpec->hasNameForLinkage())
  3811. return;
  3812. // A well-formed anonymous tag must always be a TUK_Definition.
  3813. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3814. // The type must match the tag exactly; no qualifiers allowed.
  3815. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3816. Context.getTagDeclType(TagFromDeclSpec))) {
  3817. if (getLangOpts().CPlusPlus)
  3818. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3819. return;
  3820. }
  3821. // If we've already computed linkage for the anonymous tag, then
  3822. // adding a typedef name for the anonymous decl can change that
  3823. // linkage, which might be a serious problem. Diagnose this as
  3824. // unsupported and ignore the typedef name. TODO: we should
  3825. // pursue this as a language defect and establish a formal rule
  3826. // for how to handle it.
  3827. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3828. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3829. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3830. tagLoc = getLocForEndOfToken(tagLoc);
  3831. llvm::SmallString<40> textToInsert;
  3832. textToInsert += ' ';
  3833. textToInsert += NewTD->getIdentifier()->getName();
  3834. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3835. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3836. return;
  3837. }
  3838. // Otherwise, set this is the anon-decl typedef for the tag.
  3839. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3840. }
  3841. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3842. switch (T) {
  3843. case DeclSpec::TST_class:
  3844. return 0;
  3845. case DeclSpec::TST_struct:
  3846. return 1;
  3847. case DeclSpec::TST_interface:
  3848. return 2;
  3849. case DeclSpec::TST_union:
  3850. return 3;
  3851. case DeclSpec::TST_enum:
  3852. return 4;
  3853. default:
  3854. llvm_unreachable("unexpected type specifier");
  3855. }
  3856. }
  3857. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3858. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3859. /// parameters to cope with template friend declarations.
  3860. Decl *
  3861. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3862. MultiTemplateParamsArg TemplateParams,
  3863. bool IsExplicitInstantiation,
  3864. RecordDecl *&AnonRecord) {
  3865. Decl *TagD = nullptr;
  3866. TagDecl *Tag = nullptr;
  3867. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3868. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3869. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3870. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3871. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3872. TagD = DS.getRepAsDecl();
  3873. if (!TagD) // We probably had an error
  3874. return nullptr;
  3875. // Note that the above type specs guarantee that the
  3876. // type rep is a Decl, whereas in many of the others
  3877. // it's a Type.
  3878. if (isa<TagDecl>(TagD))
  3879. Tag = cast<TagDecl>(TagD);
  3880. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3881. Tag = CTD->getTemplatedDecl();
  3882. }
  3883. if (Tag) {
  3884. handleTagNumbering(Tag, S);
  3885. Tag->setFreeStanding();
  3886. if (Tag->isInvalidDecl())
  3887. return Tag;
  3888. }
  3889. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3890. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3891. // or incomplete types shall not be restrict-qualified."
  3892. if (TypeQuals & DeclSpec::TQ_restrict)
  3893. Diag(DS.getRestrictSpecLoc(),
  3894. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3895. << DS.getSourceRange();
  3896. }
  3897. if (DS.isInlineSpecified())
  3898. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3899. << getLangOpts().CPlusPlus17;
  3900. if (DS.hasConstexprSpecifier()) {
  3901. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3902. // and definitions of functions and variables.
  3903. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  3904. // the declaration of a function or function template
  3905. if (Tag)
  3906. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3907. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
  3908. << DS.getConstexprSpecifier();
  3909. else
  3910. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  3911. << DS.getConstexprSpecifier();
  3912. // Don't emit warnings after this error.
  3913. return TagD;
  3914. }
  3915. DiagnoseFunctionSpecifiers(DS);
  3916. if (DS.isFriendSpecified()) {
  3917. // If we're dealing with a decl but not a TagDecl, assume that
  3918. // whatever routines created it handled the friendship aspect.
  3919. if (TagD && !Tag)
  3920. return nullptr;
  3921. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3922. }
  3923. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3924. bool IsExplicitSpecialization =
  3925. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3926. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3927. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3928. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3929. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3930. // nested-name-specifier unless it is an explicit instantiation
  3931. // or an explicit specialization.
  3932. //
  3933. // FIXME: We allow class template partial specializations here too, per the
  3934. // obvious intent of DR1819.
  3935. //
  3936. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3937. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3938. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3939. return nullptr;
  3940. }
  3941. // Track whether this decl-specifier declares anything.
  3942. bool DeclaresAnything = true;
  3943. // Handle anonymous struct definitions.
  3944. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3945. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3946. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3947. if (getLangOpts().CPlusPlus ||
  3948. Record->getDeclContext()->isRecord()) {
  3949. // If CurContext is a DeclContext that can contain statements,
  3950. // RecursiveASTVisitor won't visit the decls that
  3951. // BuildAnonymousStructOrUnion() will put into CurContext.
  3952. // Also store them here so that they can be part of the
  3953. // DeclStmt that gets created in this case.
  3954. // FIXME: Also return the IndirectFieldDecls created by
  3955. // BuildAnonymousStructOr union, for the same reason?
  3956. if (CurContext->isFunctionOrMethod())
  3957. AnonRecord = Record;
  3958. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3959. Context.getPrintingPolicy());
  3960. }
  3961. DeclaresAnything = false;
  3962. }
  3963. }
  3964. // C11 6.7.2.1p2:
  3965. // A struct-declaration that does not declare an anonymous structure or
  3966. // anonymous union shall contain a struct-declarator-list.
  3967. //
  3968. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3969. // did not permit a struct-declaration without a struct-declarator-list.
  3970. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3971. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3972. // Check for Microsoft C extension: anonymous struct/union member.
  3973. // Handle 2 kinds of anonymous struct/union:
  3974. // struct STRUCT;
  3975. // union UNION;
  3976. // and
  3977. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3978. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3979. if ((Tag && Tag->getDeclName()) ||
  3980. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3981. RecordDecl *Record = nullptr;
  3982. if (Tag)
  3983. Record = dyn_cast<RecordDecl>(Tag);
  3984. else if (const RecordType *RT =
  3985. DS.getRepAsType().get()->getAsStructureType())
  3986. Record = RT->getDecl();
  3987. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3988. Record = UT->getDecl();
  3989. if (Record && getLangOpts().MicrosoftExt) {
  3990. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3991. << Record->isUnion() << DS.getSourceRange();
  3992. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3993. }
  3994. DeclaresAnything = false;
  3995. }
  3996. }
  3997. // Skip all the checks below if we have a type error.
  3998. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3999. (TagD && TagD->isInvalidDecl()))
  4000. return TagD;
  4001. if (getLangOpts().CPlusPlus &&
  4002. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  4003. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  4004. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  4005. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  4006. DeclaresAnything = false;
  4007. if (!DS.isMissingDeclaratorOk()) {
  4008. // Customize diagnostic for a typedef missing a name.
  4009. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  4010. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  4011. << DS.getSourceRange();
  4012. else
  4013. DeclaresAnything = false;
  4014. }
  4015. if (DS.isModulePrivateSpecified() &&
  4016. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  4017. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  4018. << Tag->getTagKind()
  4019. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  4020. ActOnDocumentableDecl(TagD);
  4021. // C 6.7/2:
  4022. // A declaration [...] shall declare at least a declarator [...], a tag,
  4023. // or the members of an enumeration.
  4024. // C++ [dcl.dcl]p3:
  4025. // [If there are no declarators], and except for the declaration of an
  4026. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4027. // names into the program, or shall redeclare a name introduced by a
  4028. // previous declaration.
  4029. if (!DeclaresAnything) {
  4030. // In C, we allow this as a (popular) extension / bug. Don't bother
  4031. // producing further diagnostics for redundant qualifiers after this.
  4032. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4033. return TagD;
  4034. }
  4035. // C++ [dcl.stc]p1:
  4036. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  4037. // init-declarator-list of the declaration shall not be empty.
  4038. // C++ [dcl.fct.spec]p1:
  4039. // If a cv-qualifier appears in a decl-specifier-seq, the
  4040. // init-declarator-list of the declaration shall not be empty.
  4041. //
  4042. // Spurious qualifiers here appear to be valid in C.
  4043. unsigned DiagID = diag::warn_standalone_specifier;
  4044. if (getLangOpts().CPlusPlus)
  4045. DiagID = diag::ext_standalone_specifier;
  4046. // Note that a linkage-specification sets a storage class, but
  4047. // 'extern "C" struct foo;' is actually valid and not theoretically
  4048. // useless.
  4049. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4050. if (SCS == DeclSpec::SCS_mutable)
  4051. // Since mutable is not a viable storage class specifier in C, there is
  4052. // no reason to treat it as an extension. Instead, diagnose as an error.
  4053. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  4054. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  4055. Diag(DS.getStorageClassSpecLoc(), DiagID)
  4056. << DeclSpec::getSpecifierName(SCS);
  4057. }
  4058. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  4059. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  4060. << DeclSpec::getSpecifierName(TSCS);
  4061. if (DS.getTypeQualifiers()) {
  4062. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4063. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  4064. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4065. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  4066. // Restrict is covered above.
  4067. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4068. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  4069. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4070. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  4071. }
  4072. // Warn about ignored type attributes, for example:
  4073. // __attribute__((aligned)) struct A;
  4074. // Attributes should be placed after tag to apply to type declaration.
  4075. if (!DS.getAttributes().empty()) {
  4076. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  4077. if (TypeSpecType == DeclSpec::TST_class ||
  4078. TypeSpecType == DeclSpec::TST_struct ||
  4079. TypeSpecType == DeclSpec::TST_interface ||
  4080. TypeSpecType == DeclSpec::TST_union ||
  4081. TypeSpecType == DeclSpec::TST_enum) {
  4082. for (const ParsedAttr &AL : DS.getAttributes())
  4083. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4084. << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4085. }
  4086. }
  4087. return TagD;
  4088. }
  4089. /// We are trying to inject an anonymous member into the given scope;
  4090. /// check if there's an existing declaration that can't be overloaded.
  4091. ///
  4092. /// \return true if this is a forbidden redeclaration
  4093. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  4094. Scope *S,
  4095. DeclContext *Owner,
  4096. DeclarationName Name,
  4097. SourceLocation NameLoc,
  4098. bool IsUnion) {
  4099. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4100. Sema::ForVisibleRedeclaration);
  4101. if (!SemaRef.LookupName(R, S)) return false;
  4102. // Pick a representative declaration.
  4103. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4104. assert(PrevDecl && "Expected a non-null Decl");
  4105. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4106. return false;
  4107. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4108. << IsUnion << Name;
  4109. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4110. return true;
  4111. }
  4112. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4113. /// anonymous struct or union AnonRecord into the owning context Owner
  4114. /// and scope S. This routine will be invoked just after we realize
  4115. /// that an unnamed union or struct is actually an anonymous union or
  4116. /// struct, e.g.,
  4117. ///
  4118. /// @code
  4119. /// union {
  4120. /// int i;
  4121. /// float f;
  4122. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4123. /// // f into the surrounding scope.x
  4124. /// @endcode
  4125. ///
  4126. /// This routine is recursive, injecting the names of nested anonymous
  4127. /// structs/unions into the owning context and scope as well.
  4128. static bool
  4129. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4130. RecordDecl *AnonRecord, AccessSpecifier AS,
  4131. SmallVectorImpl<NamedDecl *> &Chaining) {
  4132. bool Invalid = false;
  4133. // Look every FieldDecl and IndirectFieldDecl with a name.
  4134. for (auto *D : AnonRecord->decls()) {
  4135. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4136. cast<NamedDecl>(D)->getDeclName()) {
  4137. ValueDecl *VD = cast<ValueDecl>(D);
  4138. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4139. VD->getLocation(),
  4140. AnonRecord->isUnion())) {
  4141. // C++ [class.union]p2:
  4142. // The names of the members of an anonymous union shall be
  4143. // distinct from the names of any other entity in the
  4144. // scope in which the anonymous union is declared.
  4145. Invalid = true;
  4146. } else {
  4147. // C++ [class.union]p2:
  4148. // For the purpose of name lookup, after the anonymous union
  4149. // definition, the members of the anonymous union are
  4150. // considered to have been defined in the scope in which the
  4151. // anonymous union is declared.
  4152. unsigned OldChainingSize = Chaining.size();
  4153. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4154. Chaining.append(IF->chain_begin(), IF->chain_end());
  4155. else
  4156. Chaining.push_back(VD);
  4157. assert(Chaining.size() >= 2);
  4158. NamedDecl **NamedChain =
  4159. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4160. for (unsigned i = 0; i < Chaining.size(); i++)
  4161. NamedChain[i] = Chaining[i];
  4162. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4163. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4164. VD->getType(), {NamedChain, Chaining.size()});
  4165. for (const auto *Attr : VD->attrs())
  4166. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4167. IndirectField->setAccess(AS);
  4168. IndirectField->setImplicit();
  4169. SemaRef.PushOnScopeChains(IndirectField, S);
  4170. // That includes picking up the appropriate access specifier.
  4171. if (AS != AS_none) IndirectField->setAccess(AS);
  4172. Chaining.resize(OldChainingSize);
  4173. }
  4174. }
  4175. }
  4176. return Invalid;
  4177. }
  4178. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4179. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4180. /// illegal input values are mapped to SC_None.
  4181. static StorageClass
  4182. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4183. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4184. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4185. "Parser allowed 'typedef' as storage class VarDecl.");
  4186. switch (StorageClassSpec) {
  4187. case DeclSpec::SCS_unspecified: return SC_None;
  4188. case DeclSpec::SCS_extern:
  4189. if (DS.isExternInLinkageSpec())
  4190. return SC_None;
  4191. return SC_Extern;
  4192. case DeclSpec::SCS_static: return SC_Static;
  4193. case DeclSpec::SCS_auto: return SC_Auto;
  4194. case DeclSpec::SCS_register: return SC_Register;
  4195. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4196. // Illegal SCSs map to None: error reporting is up to the caller.
  4197. case DeclSpec::SCS_mutable: // Fall through.
  4198. case DeclSpec::SCS_typedef: return SC_None;
  4199. }
  4200. llvm_unreachable("unknown storage class specifier");
  4201. }
  4202. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4203. assert(Record->hasInClassInitializer());
  4204. for (const auto *I : Record->decls()) {
  4205. const auto *FD = dyn_cast<FieldDecl>(I);
  4206. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4207. FD = IFD->getAnonField();
  4208. if (FD && FD->hasInClassInitializer())
  4209. return FD->getLocation();
  4210. }
  4211. llvm_unreachable("couldn't find in-class initializer");
  4212. }
  4213. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4214. SourceLocation DefaultInitLoc) {
  4215. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4216. return;
  4217. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4218. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4219. }
  4220. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4221. CXXRecordDecl *AnonUnion) {
  4222. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4223. return;
  4224. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4225. }
  4226. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4227. /// anonymous structure or union. Anonymous unions are a C++ feature
  4228. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4229. /// are a C11 feature and GNU C++ extension.
  4230. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4231. AccessSpecifier AS,
  4232. RecordDecl *Record,
  4233. const PrintingPolicy &Policy) {
  4234. DeclContext *Owner = Record->getDeclContext();
  4235. // Diagnose whether this anonymous struct/union is an extension.
  4236. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4237. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4238. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4239. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4240. else if (!Record->isUnion() && !getLangOpts().C11)
  4241. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4242. // C and C++ require different kinds of checks for anonymous
  4243. // structs/unions.
  4244. bool Invalid = false;
  4245. if (getLangOpts().CPlusPlus) {
  4246. const char *PrevSpec = nullptr;
  4247. if (Record->isUnion()) {
  4248. // C++ [class.union]p6:
  4249. // C++17 [class.union.anon]p2:
  4250. // Anonymous unions declared in a named namespace or in the
  4251. // global namespace shall be declared static.
  4252. unsigned DiagID;
  4253. DeclContext *OwnerScope = Owner->getRedeclContext();
  4254. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4255. (OwnerScope->isTranslationUnit() ||
  4256. (OwnerScope->isNamespace() &&
  4257. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4258. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4259. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4260. // Recover by adding 'static'.
  4261. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4262. PrevSpec, DiagID, Policy);
  4263. }
  4264. // C++ [class.union]p6:
  4265. // A storage class is not allowed in a declaration of an
  4266. // anonymous union in a class scope.
  4267. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4268. isa<RecordDecl>(Owner)) {
  4269. Diag(DS.getStorageClassSpecLoc(),
  4270. diag::err_anonymous_union_with_storage_spec)
  4271. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4272. // Recover by removing the storage specifier.
  4273. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4274. SourceLocation(),
  4275. PrevSpec, DiagID, Context.getPrintingPolicy());
  4276. }
  4277. }
  4278. // Ignore const/volatile/restrict qualifiers.
  4279. if (DS.getTypeQualifiers()) {
  4280. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4281. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4282. << Record->isUnion() << "const"
  4283. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4284. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4285. Diag(DS.getVolatileSpecLoc(),
  4286. diag::ext_anonymous_struct_union_qualified)
  4287. << Record->isUnion() << "volatile"
  4288. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4289. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4290. Diag(DS.getRestrictSpecLoc(),
  4291. diag::ext_anonymous_struct_union_qualified)
  4292. << Record->isUnion() << "restrict"
  4293. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4294. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4295. Diag(DS.getAtomicSpecLoc(),
  4296. diag::ext_anonymous_struct_union_qualified)
  4297. << Record->isUnion() << "_Atomic"
  4298. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4299. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4300. Diag(DS.getUnalignedSpecLoc(),
  4301. diag::ext_anonymous_struct_union_qualified)
  4302. << Record->isUnion() << "__unaligned"
  4303. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4304. DS.ClearTypeQualifiers();
  4305. }
  4306. // C++ [class.union]p2:
  4307. // The member-specification of an anonymous union shall only
  4308. // define non-static data members. [Note: nested types and
  4309. // functions cannot be declared within an anonymous union. ]
  4310. for (auto *Mem : Record->decls()) {
  4311. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4312. // C++ [class.union]p3:
  4313. // An anonymous union shall not have private or protected
  4314. // members (clause 11).
  4315. assert(FD->getAccess() != AS_none);
  4316. if (FD->getAccess() != AS_public) {
  4317. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4318. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4319. Invalid = true;
  4320. }
  4321. // C++ [class.union]p1
  4322. // An object of a class with a non-trivial constructor, a non-trivial
  4323. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4324. // assignment operator cannot be a member of a union, nor can an
  4325. // array of such objects.
  4326. if (CheckNontrivialField(FD))
  4327. Invalid = true;
  4328. } else if (Mem->isImplicit()) {
  4329. // Any implicit members are fine.
  4330. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4331. // This is a type that showed up in an
  4332. // elaborated-type-specifier inside the anonymous struct or
  4333. // union, but which actually declares a type outside of the
  4334. // anonymous struct or union. It's okay.
  4335. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4336. if (!MemRecord->isAnonymousStructOrUnion() &&
  4337. MemRecord->getDeclName()) {
  4338. // Visual C++ allows type definition in anonymous struct or union.
  4339. if (getLangOpts().MicrosoftExt)
  4340. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4341. << Record->isUnion();
  4342. else {
  4343. // This is a nested type declaration.
  4344. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4345. << Record->isUnion();
  4346. Invalid = true;
  4347. }
  4348. } else {
  4349. // This is an anonymous type definition within another anonymous type.
  4350. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4351. // not part of standard C++.
  4352. Diag(MemRecord->getLocation(),
  4353. diag::ext_anonymous_record_with_anonymous_type)
  4354. << Record->isUnion();
  4355. }
  4356. } else if (isa<AccessSpecDecl>(Mem)) {
  4357. // Any access specifier is fine.
  4358. } else if (isa<StaticAssertDecl>(Mem)) {
  4359. // In C++1z, static_assert declarations are also fine.
  4360. } else {
  4361. // We have something that isn't a non-static data
  4362. // member. Complain about it.
  4363. unsigned DK = diag::err_anonymous_record_bad_member;
  4364. if (isa<TypeDecl>(Mem))
  4365. DK = diag::err_anonymous_record_with_type;
  4366. else if (isa<FunctionDecl>(Mem))
  4367. DK = diag::err_anonymous_record_with_function;
  4368. else if (isa<VarDecl>(Mem))
  4369. DK = diag::err_anonymous_record_with_static;
  4370. // Visual C++ allows type definition in anonymous struct or union.
  4371. if (getLangOpts().MicrosoftExt &&
  4372. DK == diag::err_anonymous_record_with_type)
  4373. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4374. << Record->isUnion();
  4375. else {
  4376. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4377. Invalid = true;
  4378. }
  4379. }
  4380. }
  4381. // C++11 [class.union]p8 (DR1460):
  4382. // At most one variant member of a union may have a
  4383. // brace-or-equal-initializer.
  4384. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4385. Owner->isRecord())
  4386. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4387. cast<CXXRecordDecl>(Record));
  4388. }
  4389. if (!Record->isUnion() && !Owner->isRecord()) {
  4390. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4391. << getLangOpts().CPlusPlus;
  4392. Invalid = true;
  4393. }
  4394. // C++ [dcl.dcl]p3:
  4395. // [If there are no declarators], and except for the declaration of an
  4396. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4397. // names into the program
  4398. // C++ [class.mem]p2:
  4399. // each such member-declaration shall either declare at least one member
  4400. // name of the class or declare at least one unnamed bit-field
  4401. //
  4402. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4403. if (getLangOpts().CPlusPlus && Record->field_empty())
  4404. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4405. // Mock up a declarator.
  4406. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4407. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4408. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4409. // Create a declaration for this anonymous struct/union.
  4410. NamedDecl *Anon = nullptr;
  4411. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4412. Anon = FieldDecl::Create(
  4413. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4414. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4415. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4416. /*InitStyle=*/ICIS_NoInit);
  4417. Anon->setAccess(AS);
  4418. if (getLangOpts().CPlusPlus)
  4419. FieldCollector->Add(cast<FieldDecl>(Anon));
  4420. } else {
  4421. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4422. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4423. if (SCSpec == DeclSpec::SCS_mutable) {
  4424. // mutable can only appear on non-static class members, so it's always
  4425. // an error here
  4426. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4427. Invalid = true;
  4428. SC = SC_None;
  4429. }
  4430. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4431. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4432. Context.getTypeDeclType(Record), TInfo, SC);
  4433. // Default-initialize the implicit variable. This initialization will be
  4434. // trivial in almost all cases, except if a union member has an in-class
  4435. // initializer:
  4436. // union { int n = 0; };
  4437. ActOnUninitializedDecl(Anon);
  4438. }
  4439. Anon->setImplicit();
  4440. // Mark this as an anonymous struct/union type.
  4441. Record->setAnonymousStructOrUnion(true);
  4442. // Add the anonymous struct/union object to the current
  4443. // context. We'll be referencing this object when we refer to one of
  4444. // its members.
  4445. Owner->addDecl(Anon);
  4446. // Inject the members of the anonymous struct/union into the owning
  4447. // context and into the identifier resolver chain for name lookup
  4448. // purposes.
  4449. SmallVector<NamedDecl*, 2> Chain;
  4450. Chain.push_back(Anon);
  4451. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4452. Invalid = true;
  4453. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4454. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4455. Decl *ManglingContextDecl;
  4456. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4457. NewVD->getDeclContext(), ManglingContextDecl)) {
  4458. Context.setManglingNumber(
  4459. NewVD, MCtx->getManglingNumber(
  4460. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4461. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4462. }
  4463. }
  4464. }
  4465. if (Invalid)
  4466. Anon->setInvalidDecl();
  4467. return Anon;
  4468. }
  4469. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4470. /// Microsoft C anonymous structure.
  4471. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4472. /// Example:
  4473. ///
  4474. /// struct A { int a; };
  4475. /// struct B { struct A; int b; };
  4476. ///
  4477. /// void foo() {
  4478. /// B var;
  4479. /// var.a = 3;
  4480. /// }
  4481. ///
  4482. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4483. RecordDecl *Record) {
  4484. assert(Record && "expected a record!");
  4485. // Mock up a declarator.
  4486. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4487. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4488. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4489. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4490. QualType RecTy = Context.getTypeDeclType(Record);
  4491. // Create a declaration for this anonymous struct.
  4492. NamedDecl *Anon =
  4493. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4494. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4495. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4496. /*InitStyle=*/ICIS_NoInit);
  4497. Anon->setImplicit();
  4498. // Add the anonymous struct object to the current context.
  4499. CurContext->addDecl(Anon);
  4500. // Inject the members of the anonymous struct into the current
  4501. // context and into the identifier resolver chain for name lookup
  4502. // purposes.
  4503. SmallVector<NamedDecl*, 2> Chain;
  4504. Chain.push_back(Anon);
  4505. RecordDecl *RecordDef = Record->getDefinition();
  4506. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4507. diag::err_field_incomplete) ||
  4508. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4509. AS_none, Chain)) {
  4510. Anon->setInvalidDecl();
  4511. ParentDecl->setInvalidDecl();
  4512. }
  4513. return Anon;
  4514. }
  4515. /// GetNameForDeclarator - Determine the full declaration name for the
  4516. /// given Declarator.
  4517. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4518. return GetNameFromUnqualifiedId(D.getName());
  4519. }
  4520. /// Retrieves the declaration name from a parsed unqualified-id.
  4521. DeclarationNameInfo
  4522. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4523. DeclarationNameInfo NameInfo;
  4524. NameInfo.setLoc(Name.StartLocation);
  4525. switch (Name.getKind()) {
  4526. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4527. case UnqualifiedIdKind::IK_Identifier:
  4528. NameInfo.setName(Name.Identifier);
  4529. return NameInfo;
  4530. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4531. // C++ [temp.deduct.guide]p3:
  4532. // The simple-template-id shall name a class template specialization.
  4533. // The template-name shall be the same identifier as the template-name
  4534. // of the simple-template-id.
  4535. // These together intend to imply that the template-name shall name a
  4536. // class template.
  4537. // FIXME: template<typename T> struct X {};
  4538. // template<typename T> using Y = X<T>;
  4539. // Y(int) -> Y<int>;
  4540. // satisfies these rules but does not name a class template.
  4541. TemplateName TN = Name.TemplateName.get().get();
  4542. auto *Template = TN.getAsTemplateDecl();
  4543. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4544. Diag(Name.StartLocation,
  4545. diag::err_deduction_guide_name_not_class_template)
  4546. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4547. if (Template)
  4548. Diag(Template->getLocation(), diag::note_template_decl_here);
  4549. return DeclarationNameInfo();
  4550. }
  4551. NameInfo.setName(
  4552. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4553. return NameInfo;
  4554. }
  4555. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4556. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4557. Name.OperatorFunctionId.Operator));
  4558. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4559. = Name.OperatorFunctionId.SymbolLocations[0];
  4560. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4561. = Name.EndLocation.getRawEncoding();
  4562. return NameInfo;
  4563. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4564. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4565. Name.Identifier));
  4566. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4567. return NameInfo;
  4568. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4569. TypeSourceInfo *TInfo;
  4570. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4571. if (Ty.isNull())
  4572. return DeclarationNameInfo();
  4573. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4574. Context.getCanonicalType(Ty)));
  4575. NameInfo.setNamedTypeInfo(TInfo);
  4576. return NameInfo;
  4577. }
  4578. case UnqualifiedIdKind::IK_ConstructorName: {
  4579. TypeSourceInfo *TInfo;
  4580. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4581. if (Ty.isNull())
  4582. return DeclarationNameInfo();
  4583. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4584. Context.getCanonicalType(Ty)));
  4585. NameInfo.setNamedTypeInfo(TInfo);
  4586. return NameInfo;
  4587. }
  4588. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4589. // In well-formed code, we can only have a constructor
  4590. // template-id that refers to the current context, so go there
  4591. // to find the actual type being constructed.
  4592. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4593. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4594. return DeclarationNameInfo();
  4595. // Determine the type of the class being constructed.
  4596. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4597. // FIXME: Check two things: that the template-id names the same type as
  4598. // CurClassType, and that the template-id does not occur when the name
  4599. // was qualified.
  4600. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4601. Context.getCanonicalType(CurClassType)));
  4602. // FIXME: should we retrieve TypeSourceInfo?
  4603. NameInfo.setNamedTypeInfo(nullptr);
  4604. return NameInfo;
  4605. }
  4606. case UnqualifiedIdKind::IK_DestructorName: {
  4607. TypeSourceInfo *TInfo;
  4608. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4609. if (Ty.isNull())
  4610. return DeclarationNameInfo();
  4611. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4612. Context.getCanonicalType(Ty)));
  4613. NameInfo.setNamedTypeInfo(TInfo);
  4614. return NameInfo;
  4615. }
  4616. case UnqualifiedIdKind::IK_TemplateId: {
  4617. TemplateName TName = Name.TemplateId->Template.get();
  4618. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4619. return Context.getNameForTemplate(TName, TNameLoc);
  4620. }
  4621. } // switch (Name.getKind())
  4622. llvm_unreachable("Unknown name kind");
  4623. }
  4624. static QualType getCoreType(QualType Ty) {
  4625. do {
  4626. if (Ty->isPointerType() || Ty->isReferenceType())
  4627. Ty = Ty->getPointeeType();
  4628. else if (Ty->isArrayType())
  4629. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4630. else
  4631. return Ty.withoutLocalFastQualifiers();
  4632. } while (true);
  4633. }
  4634. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4635. /// and Definition have "nearly" matching parameters. This heuristic is
  4636. /// used to improve diagnostics in the case where an out-of-line function
  4637. /// definition doesn't match any declaration within the class or namespace.
  4638. /// Also sets Params to the list of indices to the parameters that differ
  4639. /// between the declaration and the definition. If hasSimilarParameters
  4640. /// returns true and Params is empty, then all of the parameters match.
  4641. static bool hasSimilarParameters(ASTContext &Context,
  4642. FunctionDecl *Declaration,
  4643. FunctionDecl *Definition,
  4644. SmallVectorImpl<unsigned> &Params) {
  4645. Params.clear();
  4646. if (Declaration->param_size() != Definition->param_size())
  4647. return false;
  4648. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4649. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4650. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4651. // The parameter types are identical
  4652. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4653. continue;
  4654. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4655. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4656. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4657. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4658. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4659. (DeclTyName && DeclTyName == DefTyName))
  4660. Params.push_back(Idx);
  4661. else // The two parameters aren't even close
  4662. return false;
  4663. }
  4664. return true;
  4665. }
  4666. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4667. /// declarator needs to be rebuilt in the current instantiation.
  4668. /// Any bits of declarator which appear before the name are valid for
  4669. /// consideration here. That's specifically the type in the decl spec
  4670. /// and the base type in any member-pointer chunks.
  4671. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4672. DeclarationName Name) {
  4673. // The types we specifically need to rebuild are:
  4674. // - typenames, typeofs, and decltypes
  4675. // - types which will become injected class names
  4676. // Of course, we also need to rebuild any type referencing such a
  4677. // type. It's safest to just say "dependent", but we call out a
  4678. // few cases here.
  4679. DeclSpec &DS = D.getMutableDeclSpec();
  4680. switch (DS.getTypeSpecType()) {
  4681. case DeclSpec::TST_typename:
  4682. case DeclSpec::TST_typeofType:
  4683. case DeclSpec::TST_underlyingType:
  4684. case DeclSpec::TST_atomic: {
  4685. // Grab the type from the parser.
  4686. TypeSourceInfo *TSI = nullptr;
  4687. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4688. if (T.isNull() || !T->isDependentType()) break;
  4689. // Make sure there's a type source info. This isn't really much
  4690. // of a waste; most dependent types should have type source info
  4691. // attached already.
  4692. if (!TSI)
  4693. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4694. // Rebuild the type in the current instantiation.
  4695. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4696. if (!TSI) return true;
  4697. // Store the new type back in the decl spec.
  4698. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4699. DS.UpdateTypeRep(LocType);
  4700. break;
  4701. }
  4702. case DeclSpec::TST_decltype:
  4703. case DeclSpec::TST_typeofExpr: {
  4704. Expr *E = DS.getRepAsExpr();
  4705. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4706. if (Result.isInvalid()) return true;
  4707. DS.UpdateExprRep(Result.get());
  4708. break;
  4709. }
  4710. default:
  4711. // Nothing to do for these decl specs.
  4712. break;
  4713. }
  4714. // It doesn't matter what order we do this in.
  4715. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4716. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4717. // The only type information in the declarator which can come
  4718. // before the declaration name is the base type of a member
  4719. // pointer.
  4720. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4721. continue;
  4722. // Rebuild the scope specifier in-place.
  4723. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4724. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4725. return true;
  4726. }
  4727. return false;
  4728. }
  4729. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4730. D.setFunctionDefinitionKind(FDK_Declaration);
  4731. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4732. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4733. Dcl && Dcl->getDeclContext()->isFileContext())
  4734. Dcl->setTopLevelDeclInObjCContainer();
  4735. if (getLangOpts().OpenCL)
  4736. setCurrentOpenCLExtensionForDecl(Dcl);
  4737. return Dcl;
  4738. }
  4739. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4740. /// If T is the name of a class, then each of the following shall have a
  4741. /// name different from T:
  4742. /// - every static data member of class T;
  4743. /// - every member function of class T
  4744. /// - every member of class T that is itself a type;
  4745. /// \returns true if the declaration name violates these rules.
  4746. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4747. DeclarationNameInfo NameInfo) {
  4748. DeclarationName Name = NameInfo.getName();
  4749. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4750. while (Record && Record->isAnonymousStructOrUnion())
  4751. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4752. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4753. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4754. return true;
  4755. }
  4756. return false;
  4757. }
  4758. /// Diagnose a declaration whose declarator-id has the given
  4759. /// nested-name-specifier.
  4760. ///
  4761. /// \param SS The nested-name-specifier of the declarator-id.
  4762. ///
  4763. /// \param DC The declaration context to which the nested-name-specifier
  4764. /// resolves.
  4765. ///
  4766. /// \param Name The name of the entity being declared.
  4767. ///
  4768. /// \param Loc The location of the name of the entity being declared.
  4769. ///
  4770. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4771. /// we're declaring an explicit / partial specialization / instantiation.
  4772. ///
  4773. /// \returns true if we cannot safely recover from this error, false otherwise.
  4774. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4775. DeclarationName Name,
  4776. SourceLocation Loc, bool IsTemplateId) {
  4777. DeclContext *Cur = CurContext;
  4778. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4779. Cur = Cur->getParent();
  4780. // If the user provided a superfluous scope specifier that refers back to the
  4781. // class in which the entity is already declared, diagnose and ignore it.
  4782. //
  4783. // class X {
  4784. // void X::f();
  4785. // };
  4786. //
  4787. // Note, it was once ill-formed to give redundant qualification in all
  4788. // contexts, but that rule was removed by DR482.
  4789. if (Cur->Equals(DC)) {
  4790. if (Cur->isRecord()) {
  4791. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4792. : diag::err_member_extra_qualification)
  4793. << Name << FixItHint::CreateRemoval(SS.getRange());
  4794. SS.clear();
  4795. } else {
  4796. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4797. }
  4798. return false;
  4799. }
  4800. // Check whether the qualifying scope encloses the scope of the original
  4801. // declaration. For a template-id, we perform the checks in
  4802. // CheckTemplateSpecializationScope.
  4803. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4804. if (Cur->isRecord())
  4805. Diag(Loc, diag::err_member_qualification)
  4806. << Name << SS.getRange();
  4807. else if (isa<TranslationUnitDecl>(DC))
  4808. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4809. << Name << SS.getRange();
  4810. else if (isa<FunctionDecl>(Cur))
  4811. Diag(Loc, diag::err_invalid_declarator_in_function)
  4812. << Name << SS.getRange();
  4813. else if (isa<BlockDecl>(Cur))
  4814. Diag(Loc, diag::err_invalid_declarator_in_block)
  4815. << Name << SS.getRange();
  4816. else
  4817. Diag(Loc, diag::err_invalid_declarator_scope)
  4818. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4819. return true;
  4820. }
  4821. if (Cur->isRecord()) {
  4822. // Cannot qualify members within a class.
  4823. Diag(Loc, diag::err_member_qualification)
  4824. << Name << SS.getRange();
  4825. SS.clear();
  4826. // C++ constructors and destructors with incorrect scopes can break
  4827. // our AST invariants by having the wrong underlying types. If
  4828. // that's the case, then drop this declaration entirely.
  4829. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4830. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4831. !Context.hasSameType(Name.getCXXNameType(),
  4832. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4833. return true;
  4834. return false;
  4835. }
  4836. // C++11 [dcl.meaning]p1:
  4837. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4838. // not begin with a decltype-specifer"
  4839. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4840. while (SpecLoc.getPrefix())
  4841. SpecLoc = SpecLoc.getPrefix();
  4842. if (dyn_cast_or_null<DecltypeType>(
  4843. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4844. Diag(Loc, diag::err_decltype_in_declarator)
  4845. << SpecLoc.getTypeLoc().getSourceRange();
  4846. return false;
  4847. }
  4848. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4849. MultiTemplateParamsArg TemplateParamLists) {
  4850. // TODO: consider using NameInfo for diagnostic.
  4851. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4852. DeclarationName Name = NameInfo.getName();
  4853. // All of these full declarators require an identifier. If it doesn't have
  4854. // one, the ParsedFreeStandingDeclSpec action should be used.
  4855. if (D.isDecompositionDeclarator()) {
  4856. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4857. } else if (!Name) {
  4858. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4859. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4860. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4861. return nullptr;
  4862. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4863. return nullptr;
  4864. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4865. // we find one that is.
  4866. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4867. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4868. S = S->getParent();
  4869. DeclContext *DC = CurContext;
  4870. if (D.getCXXScopeSpec().isInvalid())
  4871. D.setInvalidType();
  4872. else if (D.getCXXScopeSpec().isSet()) {
  4873. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4874. UPPC_DeclarationQualifier))
  4875. return nullptr;
  4876. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4877. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4878. if (!DC || isa<EnumDecl>(DC)) {
  4879. // If we could not compute the declaration context, it's because the
  4880. // declaration context is dependent but does not refer to a class,
  4881. // class template, or class template partial specialization. Complain
  4882. // and return early, to avoid the coming semantic disaster.
  4883. Diag(D.getIdentifierLoc(),
  4884. diag::err_template_qualified_declarator_no_match)
  4885. << D.getCXXScopeSpec().getScopeRep()
  4886. << D.getCXXScopeSpec().getRange();
  4887. return nullptr;
  4888. }
  4889. bool IsDependentContext = DC->isDependentContext();
  4890. if (!IsDependentContext &&
  4891. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4892. return nullptr;
  4893. // If a class is incomplete, do not parse entities inside it.
  4894. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4895. Diag(D.getIdentifierLoc(),
  4896. diag::err_member_def_undefined_record)
  4897. << Name << DC << D.getCXXScopeSpec().getRange();
  4898. return nullptr;
  4899. }
  4900. if (!D.getDeclSpec().isFriendSpecified()) {
  4901. if (diagnoseQualifiedDeclaration(
  4902. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4903. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4904. if (DC->isRecord())
  4905. return nullptr;
  4906. D.setInvalidType();
  4907. }
  4908. }
  4909. // Check whether we need to rebuild the type of the given
  4910. // declaration in the current instantiation.
  4911. if (EnteringContext && IsDependentContext &&
  4912. TemplateParamLists.size() != 0) {
  4913. ContextRAII SavedContext(*this, DC);
  4914. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4915. D.setInvalidType();
  4916. }
  4917. }
  4918. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4919. QualType R = TInfo->getType();
  4920. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4921. UPPC_DeclarationType))
  4922. D.setInvalidType();
  4923. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4924. forRedeclarationInCurContext());
  4925. // See if this is a redefinition of a variable in the same scope.
  4926. if (!D.getCXXScopeSpec().isSet()) {
  4927. bool IsLinkageLookup = false;
  4928. bool CreateBuiltins = false;
  4929. // If the declaration we're planning to build will be a function
  4930. // or object with linkage, then look for another declaration with
  4931. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4932. //
  4933. // If the declaration we're planning to build will be declared with
  4934. // external linkage in the translation unit, create any builtin with
  4935. // the same name.
  4936. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4937. /* Do nothing*/;
  4938. else if (CurContext->isFunctionOrMethod() &&
  4939. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4940. R->isFunctionType())) {
  4941. IsLinkageLookup = true;
  4942. CreateBuiltins =
  4943. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4944. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4945. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4946. CreateBuiltins = true;
  4947. if (IsLinkageLookup) {
  4948. Previous.clear(LookupRedeclarationWithLinkage);
  4949. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4950. }
  4951. LookupName(Previous, S, CreateBuiltins);
  4952. } else { // Something like "int foo::x;"
  4953. LookupQualifiedName(Previous, DC);
  4954. // C++ [dcl.meaning]p1:
  4955. // When the declarator-id is qualified, the declaration shall refer to a
  4956. // previously declared member of the class or namespace to which the
  4957. // qualifier refers (or, in the case of a namespace, of an element of the
  4958. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4959. // thereof; [...]
  4960. //
  4961. // Note that we already checked the context above, and that we do not have
  4962. // enough information to make sure that Previous contains the declaration
  4963. // we want to match. For example, given:
  4964. //
  4965. // class X {
  4966. // void f();
  4967. // void f(float);
  4968. // };
  4969. //
  4970. // void X::f(int) { } // ill-formed
  4971. //
  4972. // In this case, Previous will point to the overload set
  4973. // containing the two f's declared in X, but neither of them
  4974. // matches.
  4975. // C++ [dcl.meaning]p1:
  4976. // [...] the member shall not merely have been introduced by a
  4977. // using-declaration in the scope of the class or namespace nominated by
  4978. // the nested-name-specifier of the declarator-id.
  4979. RemoveUsingDecls(Previous);
  4980. }
  4981. if (Previous.isSingleResult() &&
  4982. Previous.getFoundDecl()->isTemplateParameter()) {
  4983. // Maybe we will complain about the shadowed template parameter.
  4984. if (!D.isInvalidType())
  4985. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4986. Previous.getFoundDecl());
  4987. // Just pretend that we didn't see the previous declaration.
  4988. Previous.clear();
  4989. }
  4990. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4991. // Forget that the previous declaration is the injected-class-name.
  4992. Previous.clear();
  4993. // In C++, the previous declaration we find might be a tag type
  4994. // (class or enum). In this case, the new declaration will hide the
  4995. // tag type. Note that this applies to functions, function templates, and
  4996. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4997. if (Previous.isSingleTagDecl() &&
  4998. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4999. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  5000. Previous.clear();
  5001. // Check that there are no default arguments other than in the parameters
  5002. // of a function declaration (C++ only).
  5003. if (getLangOpts().CPlusPlus)
  5004. CheckExtraCXXDefaultArguments(D);
  5005. NamedDecl *New;
  5006. bool AddToScope = true;
  5007. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  5008. if (TemplateParamLists.size()) {
  5009. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  5010. return nullptr;
  5011. }
  5012. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  5013. } else if (R->isFunctionType()) {
  5014. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  5015. TemplateParamLists,
  5016. AddToScope);
  5017. } else {
  5018. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  5019. AddToScope);
  5020. }
  5021. if (!New)
  5022. return nullptr;
  5023. // If this has an identifier and is not a function template specialization,
  5024. // add it to the scope stack.
  5025. if (New->getDeclName() && AddToScope)
  5026. PushOnScopeChains(New, S);
  5027. if (isInOpenMPDeclareTargetContext())
  5028. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  5029. return New;
  5030. }
  5031. /// Helper method to turn variable array types into constant array
  5032. /// types in certain situations which would otherwise be errors (for
  5033. /// GCC compatibility).
  5034. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  5035. ASTContext &Context,
  5036. bool &SizeIsNegative,
  5037. llvm::APSInt &Oversized) {
  5038. // This method tries to turn a variable array into a constant
  5039. // array even when the size isn't an ICE. This is necessary
  5040. // for compatibility with code that depends on gcc's buggy
  5041. // constant expression folding, like struct {char x[(int)(char*)2];}
  5042. SizeIsNegative = false;
  5043. Oversized = 0;
  5044. if (T->isDependentType())
  5045. return QualType();
  5046. QualifierCollector Qs;
  5047. const Type *Ty = Qs.strip(T);
  5048. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  5049. QualType Pointee = PTy->getPointeeType();
  5050. QualType FixedType =
  5051. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  5052. Oversized);
  5053. if (FixedType.isNull()) return FixedType;
  5054. FixedType = Context.getPointerType(FixedType);
  5055. return Qs.apply(Context, FixedType);
  5056. }
  5057. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  5058. QualType Inner = PTy->getInnerType();
  5059. QualType FixedType =
  5060. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  5061. Oversized);
  5062. if (FixedType.isNull()) return FixedType;
  5063. FixedType = Context.getParenType(FixedType);
  5064. return Qs.apply(Context, FixedType);
  5065. }
  5066. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  5067. if (!VLATy)
  5068. return QualType();
  5069. // FIXME: We should probably handle this case
  5070. if (VLATy->getElementType()->isVariablyModifiedType())
  5071. return QualType();
  5072. Expr::EvalResult Result;
  5073. if (!VLATy->getSizeExpr() ||
  5074. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  5075. return QualType();
  5076. llvm::APSInt Res = Result.Val.getInt();
  5077. // Check whether the array size is negative.
  5078. if (Res.isSigned() && Res.isNegative()) {
  5079. SizeIsNegative = true;
  5080. return QualType();
  5081. }
  5082. // Check whether the array is too large to be addressed.
  5083. unsigned ActiveSizeBits
  5084. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  5085. Res);
  5086. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  5087. Oversized = Res;
  5088. return QualType();
  5089. }
  5090. return Context.getConstantArrayType(
  5091. VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
  5092. }
  5093. static void
  5094. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  5095. SrcTL = SrcTL.getUnqualifiedLoc();
  5096. DstTL = DstTL.getUnqualifiedLoc();
  5097. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  5098. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  5099. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5100. DstPTL.getPointeeLoc());
  5101. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5102. return;
  5103. }
  5104. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5105. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5106. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5107. DstPTL.getInnerLoc());
  5108. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5109. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5110. return;
  5111. }
  5112. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5113. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5114. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5115. TypeLoc DstElemTL = DstATL.getElementLoc();
  5116. DstElemTL.initializeFullCopy(SrcElemTL);
  5117. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5118. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5119. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5120. }
  5121. /// Helper method to turn variable array types into constant array
  5122. /// types in certain situations which would otherwise be errors (for
  5123. /// GCC compatibility).
  5124. static TypeSourceInfo*
  5125. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5126. ASTContext &Context,
  5127. bool &SizeIsNegative,
  5128. llvm::APSInt &Oversized) {
  5129. QualType FixedTy
  5130. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5131. SizeIsNegative, Oversized);
  5132. if (FixedTy.isNull())
  5133. return nullptr;
  5134. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5135. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5136. FixedTInfo->getTypeLoc());
  5137. return FixedTInfo;
  5138. }
  5139. /// Register the given locally-scoped extern "C" declaration so
  5140. /// that it can be found later for redeclarations. We include any extern "C"
  5141. /// declaration that is not visible in the translation unit here, not just
  5142. /// function-scope declarations.
  5143. void
  5144. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5145. if (!getLangOpts().CPlusPlus &&
  5146. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5147. // Don't need to track declarations in the TU in C.
  5148. return;
  5149. // Note that we have a locally-scoped external with this name.
  5150. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5151. }
  5152. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5153. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5154. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5155. return Result.empty() ? nullptr : *Result.begin();
  5156. }
  5157. /// Diagnose function specifiers on a declaration of an identifier that
  5158. /// does not identify a function.
  5159. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5160. // FIXME: We should probably indicate the identifier in question to avoid
  5161. // confusion for constructs like "virtual int a(), b;"
  5162. if (DS.isVirtualSpecified())
  5163. Diag(DS.getVirtualSpecLoc(),
  5164. diag::err_virtual_non_function);
  5165. if (DS.hasExplicitSpecifier())
  5166. Diag(DS.getExplicitSpecLoc(),
  5167. diag::err_explicit_non_function);
  5168. if (DS.isNoreturnSpecified())
  5169. Diag(DS.getNoreturnSpecLoc(),
  5170. diag::err_noreturn_non_function);
  5171. }
  5172. NamedDecl*
  5173. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5174. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5175. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5176. if (D.getCXXScopeSpec().isSet()) {
  5177. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5178. << D.getCXXScopeSpec().getRange();
  5179. D.setInvalidType();
  5180. // Pretend we didn't see the scope specifier.
  5181. DC = CurContext;
  5182. Previous.clear();
  5183. }
  5184. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5185. if (D.getDeclSpec().isInlineSpecified())
  5186. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5187. << getLangOpts().CPlusPlus17;
  5188. if (D.getDeclSpec().hasConstexprSpecifier())
  5189. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5190. << 1 << D.getDeclSpec().getConstexprSpecifier();
  5191. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5192. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5193. Diag(D.getName().StartLocation,
  5194. diag::err_deduction_guide_invalid_specifier)
  5195. << "typedef";
  5196. else
  5197. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5198. << D.getName().getSourceRange();
  5199. return nullptr;
  5200. }
  5201. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5202. if (!NewTD) return nullptr;
  5203. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5204. ProcessDeclAttributes(S, NewTD, D);
  5205. CheckTypedefForVariablyModifiedType(S, NewTD);
  5206. bool Redeclaration = D.isRedeclaration();
  5207. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5208. D.setRedeclaration(Redeclaration);
  5209. return ND;
  5210. }
  5211. void
  5212. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5213. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5214. // then it shall have block scope.
  5215. // Note that variably modified types must be fixed before merging the decl so
  5216. // that redeclarations will match.
  5217. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5218. QualType T = TInfo->getType();
  5219. if (T->isVariablyModifiedType()) {
  5220. setFunctionHasBranchProtectedScope();
  5221. if (S->getFnParent() == nullptr) {
  5222. bool SizeIsNegative;
  5223. llvm::APSInt Oversized;
  5224. TypeSourceInfo *FixedTInfo =
  5225. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5226. SizeIsNegative,
  5227. Oversized);
  5228. if (FixedTInfo) {
  5229. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5230. NewTD->setTypeSourceInfo(FixedTInfo);
  5231. } else {
  5232. if (SizeIsNegative)
  5233. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5234. else if (T->isVariableArrayType())
  5235. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5236. else if (Oversized.getBoolValue())
  5237. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5238. << Oversized.toString(10);
  5239. else
  5240. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5241. NewTD->setInvalidDecl();
  5242. }
  5243. }
  5244. }
  5245. }
  5246. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5247. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5248. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5249. NamedDecl*
  5250. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5251. LookupResult &Previous, bool &Redeclaration) {
  5252. // Find the shadowed declaration before filtering for scope.
  5253. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5254. // Merge the decl with the existing one if appropriate. If the decl is
  5255. // in an outer scope, it isn't the same thing.
  5256. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5257. /*AllowInlineNamespace*/false);
  5258. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5259. if (!Previous.empty()) {
  5260. Redeclaration = true;
  5261. MergeTypedefNameDecl(S, NewTD, Previous);
  5262. } else {
  5263. inferGslPointerAttribute(NewTD);
  5264. }
  5265. if (ShadowedDecl && !Redeclaration)
  5266. CheckShadow(NewTD, ShadowedDecl, Previous);
  5267. // If this is the C FILE type, notify the AST context.
  5268. if (IdentifierInfo *II = NewTD->getIdentifier())
  5269. if (!NewTD->isInvalidDecl() &&
  5270. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5271. if (II->isStr("FILE"))
  5272. Context.setFILEDecl(NewTD);
  5273. else if (II->isStr("jmp_buf"))
  5274. Context.setjmp_bufDecl(NewTD);
  5275. else if (II->isStr("sigjmp_buf"))
  5276. Context.setsigjmp_bufDecl(NewTD);
  5277. else if (II->isStr("ucontext_t"))
  5278. Context.setucontext_tDecl(NewTD);
  5279. }
  5280. return NewTD;
  5281. }
  5282. /// Determines whether the given declaration is an out-of-scope
  5283. /// previous declaration.
  5284. ///
  5285. /// This routine should be invoked when name lookup has found a
  5286. /// previous declaration (PrevDecl) that is not in the scope where a
  5287. /// new declaration by the same name is being introduced. If the new
  5288. /// declaration occurs in a local scope, previous declarations with
  5289. /// linkage may still be considered previous declarations (C99
  5290. /// 6.2.2p4-5, C++ [basic.link]p6).
  5291. ///
  5292. /// \param PrevDecl the previous declaration found by name
  5293. /// lookup
  5294. ///
  5295. /// \param DC the context in which the new declaration is being
  5296. /// declared.
  5297. ///
  5298. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5299. /// for a new delcaration with the same name.
  5300. static bool
  5301. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5302. ASTContext &Context) {
  5303. if (!PrevDecl)
  5304. return false;
  5305. if (!PrevDecl->hasLinkage())
  5306. return false;
  5307. if (Context.getLangOpts().CPlusPlus) {
  5308. // C++ [basic.link]p6:
  5309. // If there is a visible declaration of an entity with linkage
  5310. // having the same name and type, ignoring entities declared
  5311. // outside the innermost enclosing namespace scope, the block
  5312. // scope declaration declares that same entity and receives the
  5313. // linkage of the previous declaration.
  5314. DeclContext *OuterContext = DC->getRedeclContext();
  5315. if (!OuterContext->isFunctionOrMethod())
  5316. // This rule only applies to block-scope declarations.
  5317. return false;
  5318. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5319. if (PrevOuterContext->isRecord())
  5320. // We found a member function: ignore it.
  5321. return false;
  5322. // Find the innermost enclosing namespace for the new and
  5323. // previous declarations.
  5324. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5325. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5326. // The previous declaration is in a different namespace, so it
  5327. // isn't the same function.
  5328. if (!OuterContext->Equals(PrevOuterContext))
  5329. return false;
  5330. }
  5331. return true;
  5332. }
  5333. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5334. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5335. if (!SS.isSet()) return;
  5336. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5337. }
  5338. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5339. QualType type = decl->getType();
  5340. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5341. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5342. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5343. unsigned kind = -1U;
  5344. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5345. if (var->hasAttr<BlocksAttr>())
  5346. kind = 0; // __block
  5347. else if (!var->hasLocalStorage())
  5348. kind = 1; // global
  5349. } else if (isa<ObjCIvarDecl>(decl)) {
  5350. kind = 3; // ivar
  5351. } else if (isa<FieldDecl>(decl)) {
  5352. kind = 2; // field
  5353. }
  5354. if (kind != -1U) {
  5355. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5356. << kind;
  5357. }
  5358. } else if (lifetime == Qualifiers::OCL_None) {
  5359. // Try to infer lifetime.
  5360. if (!type->isObjCLifetimeType())
  5361. return false;
  5362. lifetime = type->getObjCARCImplicitLifetime();
  5363. type = Context.getLifetimeQualifiedType(type, lifetime);
  5364. decl->setType(type);
  5365. }
  5366. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5367. // Thread-local variables cannot have lifetime.
  5368. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5369. var->getTLSKind()) {
  5370. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5371. << var->getType();
  5372. return true;
  5373. }
  5374. }
  5375. return false;
  5376. }
  5377. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5378. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5379. // the wrong linkage.
  5380. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5381. // 'weak' only applies to declarations with external linkage.
  5382. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5383. if (!ND.isExternallyVisible()) {
  5384. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5385. ND.dropAttr<WeakAttr>();
  5386. }
  5387. }
  5388. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5389. if (ND.isExternallyVisible()) {
  5390. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5391. ND.dropAttr<WeakRefAttr>();
  5392. ND.dropAttr<AliasAttr>();
  5393. }
  5394. }
  5395. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5396. if (VD->hasInit()) {
  5397. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5398. assert(VD->isThisDeclarationADefinition() &&
  5399. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5400. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5401. VD->dropAttr<AliasAttr>();
  5402. }
  5403. }
  5404. }
  5405. // 'selectany' only applies to externally visible variable declarations.
  5406. // It does not apply to functions.
  5407. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5408. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5409. S.Diag(Attr->getLocation(),
  5410. diag::err_attribute_selectany_non_extern_data);
  5411. ND.dropAttr<SelectAnyAttr>();
  5412. }
  5413. }
  5414. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5415. auto *VD = dyn_cast<VarDecl>(&ND);
  5416. bool IsAnonymousNS = false;
  5417. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5418. if (VD) {
  5419. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5420. while (NS && !IsAnonymousNS) {
  5421. IsAnonymousNS = NS->isAnonymousNamespace();
  5422. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5423. }
  5424. }
  5425. // dll attributes require external linkage. Static locals may have external
  5426. // linkage but still cannot be explicitly imported or exported.
  5427. // In Microsoft mode, a variable defined in anonymous namespace must have
  5428. // external linkage in order to be exported.
  5429. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5430. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5431. (!AnonNSInMicrosoftMode &&
  5432. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5433. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5434. << &ND << Attr;
  5435. ND.setInvalidDecl();
  5436. }
  5437. }
  5438. // Virtual functions cannot be marked as 'notail'.
  5439. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5440. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5441. if (MD->isVirtual()) {
  5442. S.Diag(ND.getLocation(),
  5443. diag::err_invalid_attribute_on_virtual_function)
  5444. << Attr;
  5445. ND.dropAttr<NotTailCalledAttr>();
  5446. }
  5447. // Check the attributes on the function type, if any.
  5448. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5449. // Don't declare this variable in the second operand of the for-statement;
  5450. // GCC miscompiles that by ending its lifetime before evaluating the
  5451. // third operand. See gcc.gnu.org/PR86769.
  5452. AttributedTypeLoc ATL;
  5453. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5454. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5455. TL = ATL.getModifiedLoc()) {
  5456. // The [[lifetimebound]] attribute can be applied to the implicit object
  5457. // parameter of a non-static member function (other than a ctor or dtor)
  5458. // by applying it to the function type.
  5459. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5460. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5461. if (!MD || MD->isStatic()) {
  5462. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5463. << !MD << A->getRange();
  5464. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5465. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5466. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5467. }
  5468. }
  5469. }
  5470. }
  5471. }
  5472. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5473. NamedDecl *NewDecl,
  5474. bool IsSpecialization,
  5475. bool IsDefinition) {
  5476. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5477. return;
  5478. bool IsTemplate = false;
  5479. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5480. OldDecl = OldTD->getTemplatedDecl();
  5481. IsTemplate = true;
  5482. if (!IsSpecialization)
  5483. IsDefinition = false;
  5484. }
  5485. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5486. NewDecl = NewTD->getTemplatedDecl();
  5487. IsTemplate = true;
  5488. }
  5489. if (!OldDecl || !NewDecl)
  5490. return;
  5491. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5492. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5493. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5494. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5495. // dllimport and dllexport are inheritable attributes so we have to exclude
  5496. // inherited attribute instances.
  5497. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5498. (NewExportAttr && !NewExportAttr->isInherited());
  5499. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5500. // the only exception being explicit specializations.
  5501. // Implicitly generated declarations are also excluded for now because there
  5502. // is no other way to switch these to use dllimport or dllexport.
  5503. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5504. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5505. // Allow with a warning for free functions and global variables.
  5506. bool JustWarn = false;
  5507. if (!OldDecl->isCXXClassMember()) {
  5508. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5509. if (VD && !VD->getDescribedVarTemplate())
  5510. JustWarn = true;
  5511. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5512. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5513. JustWarn = true;
  5514. }
  5515. // We cannot change a declaration that's been used because IR has already
  5516. // been emitted. Dllimported functions will still work though (modulo
  5517. // address equality) as they can use the thunk.
  5518. if (OldDecl->isUsed())
  5519. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5520. JustWarn = false;
  5521. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5522. : diag::err_attribute_dll_redeclaration;
  5523. S.Diag(NewDecl->getLocation(), DiagID)
  5524. << NewDecl
  5525. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5526. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5527. if (!JustWarn) {
  5528. NewDecl->setInvalidDecl();
  5529. return;
  5530. }
  5531. }
  5532. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5533. // exceptions being inline function definitions (except for function
  5534. // templates), local extern declarations, qualified friend declarations or
  5535. // special MSVC extension: in the last case, the declaration is treated as if
  5536. // it were marked dllexport.
  5537. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5538. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5539. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5540. // Ignore static data because out-of-line definitions are diagnosed
  5541. // separately.
  5542. IsStaticDataMember = VD->isStaticDataMember();
  5543. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5544. VarDecl::DeclarationOnly;
  5545. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5546. IsInline = FD->isInlined();
  5547. IsQualifiedFriend = FD->getQualifier() &&
  5548. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5549. }
  5550. if (OldImportAttr && !HasNewAttr &&
  5551. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5552. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5553. if (IsMicrosoft && IsDefinition) {
  5554. S.Diag(NewDecl->getLocation(),
  5555. diag::warn_redeclaration_without_import_attribute)
  5556. << NewDecl;
  5557. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5558. NewDecl->dropAttr<DLLImportAttr>();
  5559. NewDecl->addAttr(
  5560. DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
  5561. } else {
  5562. S.Diag(NewDecl->getLocation(),
  5563. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5564. << NewDecl << OldImportAttr;
  5565. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5566. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5567. OldDecl->dropAttr<DLLImportAttr>();
  5568. NewDecl->dropAttr<DLLImportAttr>();
  5569. }
  5570. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5571. // In MinGW, seeing a function declared inline drops the dllimport
  5572. // attribute.
  5573. OldDecl->dropAttr<DLLImportAttr>();
  5574. NewDecl->dropAttr<DLLImportAttr>();
  5575. S.Diag(NewDecl->getLocation(),
  5576. diag::warn_dllimport_dropped_from_inline_function)
  5577. << NewDecl << OldImportAttr;
  5578. }
  5579. // A specialization of a class template member function is processed here
  5580. // since it's a redeclaration. If the parent class is dllexport, the
  5581. // specialization inherits that attribute. This doesn't happen automatically
  5582. // since the parent class isn't instantiated until later.
  5583. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5584. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5585. !NewImportAttr && !NewExportAttr) {
  5586. if (const DLLExportAttr *ParentExportAttr =
  5587. MD->getParent()->getAttr<DLLExportAttr>()) {
  5588. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5589. NewAttr->setInherited(true);
  5590. NewDecl->addAttr(NewAttr);
  5591. }
  5592. }
  5593. }
  5594. }
  5595. /// Given that we are within the definition of the given function,
  5596. /// will that definition behave like C99's 'inline', where the
  5597. /// definition is discarded except for optimization purposes?
  5598. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5599. // Try to avoid calling GetGVALinkageForFunction.
  5600. // All cases of this require the 'inline' keyword.
  5601. if (!FD->isInlined()) return false;
  5602. // This is only possible in C++ with the gnu_inline attribute.
  5603. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5604. return false;
  5605. // Okay, go ahead and call the relatively-more-expensive function.
  5606. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5607. }
  5608. /// Determine whether a variable is extern "C" prior to attaching
  5609. /// an initializer. We can't just call isExternC() here, because that
  5610. /// will also compute and cache whether the declaration is externally
  5611. /// visible, which might change when we attach the initializer.
  5612. ///
  5613. /// This can only be used if the declaration is known to not be a
  5614. /// redeclaration of an internal linkage declaration.
  5615. ///
  5616. /// For instance:
  5617. ///
  5618. /// auto x = []{};
  5619. ///
  5620. /// Attaching the initializer here makes this declaration not externally
  5621. /// visible, because its type has internal linkage.
  5622. ///
  5623. /// FIXME: This is a hack.
  5624. template<typename T>
  5625. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5626. if (S.getLangOpts().CPlusPlus) {
  5627. // In C++, the overloadable attribute negates the effects of extern "C".
  5628. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5629. return false;
  5630. // So do CUDA's host/device attributes.
  5631. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5632. D->template hasAttr<CUDAHostAttr>()))
  5633. return false;
  5634. }
  5635. return D->isExternC();
  5636. }
  5637. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5638. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5639. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5640. isa<OMPDeclareMapperDecl>(DC))
  5641. return VD->hasExternalStorage();
  5642. if (DC->isFileContext())
  5643. return true;
  5644. if (DC->isRecord())
  5645. return false;
  5646. llvm_unreachable("Unexpected context");
  5647. }
  5648. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5649. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5650. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5651. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5652. return true;
  5653. if (DC->isRecord())
  5654. return false;
  5655. llvm_unreachable("Unexpected context");
  5656. }
  5657. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5658. ParsedAttr::Kind Kind) {
  5659. // Check decl attributes on the DeclSpec.
  5660. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5661. return true;
  5662. // Walk the declarator structure, checking decl attributes that were in a type
  5663. // position to the decl itself.
  5664. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5665. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5666. return true;
  5667. }
  5668. // Finally, check attributes on the decl itself.
  5669. return PD.getAttributes().hasAttribute(Kind);
  5670. }
  5671. /// Adjust the \c DeclContext for a function or variable that might be a
  5672. /// function-local external declaration.
  5673. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5674. if (!DC->isFunctionOrMethod())
  5675. return false;
  5676. // If this is a local extern function or variable declared within a function
  5677. // template, don't add it into the enclosing namespace scope until it is
  5678. // instantiated; it might have a dependent type right now.
  5679. if (DC->isDependentContext())
  5680. return true;
  5681. // C++11 [basic.link]p7:
  5682. // When a block scope declaration of an entity with linkage is not found to
  5683. // refer to some other declaration, then that entity is a member of the
  5684. // innermost enclosing namespace.
  5685. //
  5686. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5687. // semantically-enclosing namespace, not a lexically-enclosing one.
  5688. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5689. DC = DC->getParent();
  5690. return true;
  5691. }
  5692. /// Returns true if given declaration has external C language linkage.
  5693. static bool isDeclExternC(const Decl *D) {
  5694. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5695. return FD->isExternC();
  5696. if (const auto *VD = dyn_cast<VarDecl>(D))
  5697. return VD->isExternC();
  5698. llvm_unreachable("Unknown type of decl!");
  5699. }
  5700. NamedDecl *Sema::ActOnVariableDeclarator(
  5701. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5702. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5703. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5704. QualType R = TInfo->getType();
  5705. DeclarationName Name = GetNameForDeclarator(D).getName();
  5706. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5707. if (D.isDecompositionDeclarator()) {
  5708. // Take the name of the first declarator as our name for diagnostic
  5709. // purposes.
  5710. auto &Decomp = D.getDecompositionDeclarator();
  5711. if (!Decomp.bindings().empty()) {
  5712. II = Decomp.bindings()[0].Name;
  5713. Name = II;
  5714. }
  5715. } else if (!II) {
  5716. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5717. return nullptr;
  5718. }
  5719. if (getLangOpts().OpenCL) {
  5720. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5721. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5722. // argument.
  5723. if (R->isImageType() || R->isPipeType()) {
  5724. Diag(D.getIdentifierLoc(),
  5725. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5726. << R;
  5727. D.setInvalidType();
  5728. return nullptr;
  5729. }
  5730. // OpenCL v1.2 s6.9.r:
  5731. // The event type cannot be used to declare a program scope variable.
  5732. // OpenCL v2.0 s6.9.q:
  5733. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5734. if (NULL == S->getParent()) {
  5735. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5736. Diag(D.getIdentifierLoc(),
  5737. diag::err_invalid_type_for_program_scope_var) << R;
  5738. D.setInvalidType();
  5739. return nullptr;
  5740. }
  5741. }
  5742. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5743. QualType NR = R;
  5744. while (NR->isPointerType()) {
  5745. if (NR->isFunctionPointerType()) {
  5746. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5747. D.setInvalidType();
  5748. break;
  5749. }
  5750. NR = NR->getPointeeType();
  5751. }
  5752. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5753. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5754. // half array type (unless the cl_khr_fp16 extension is enabled).
  5755. if (Context.getBaseElementType(R)->isHalfType()) {
  5756. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5757. D.setInvalidType();
  5758. }
  5759. }
  5760. if (R->isSamplerT()) {
  5761. // OpenCL v1.2 s6.9.b p4:
  5762. // The sampler type cannot be used with the __local and __global address
  5763. // space qualifiers.
  5764. if (R.getAddressSpace() == LangAS::opencl_local ||
  5765. R.getAddressSpace() == LangAS::opencl_global) {
  5766. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5767. }
  5768. // OpenCL v1.2 s6.12.14.1:
  5769. // A global sampler must be declared with either the constant address
  5770. // space qualifier or with the const qualifier.
  5771. if (DC->isTranslationUnit() &&
  5772. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5773. R.isConstQualified())) {
  5774. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5775. D.setInvalidType();
  5776. }
  5777. }
  5778. // OpenCL v1.2 s6.9.r:
  5779. // The event type cannot be used with the __local, __constant and __global
  5780. // address space qualifiers.
  5781. if (R->isEventT()) {
  5782. if (R.getAddressSpace() != LangAS::opencl_private) {
  5783. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5784. D.setInvalidType();
  5785. }
  5786. }
  5787. // C++ for OpenCL does not allow the thread_local storage qualifier.
  5788. // OpenCL C does not support thread_local either, and
  5789. // also reject all other thread storage class specifiers.
  5790. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5791. if (TSC != TSCS_unspecified) {
  5792. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5793. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5794. diag::err_opencl_unknown_type_specifier)
  5795. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5796. << DeclSpec::getSpecifierName(TSC) << 1;
  5797. D.setInvalidType();
  5798. return nullptr;
  5799. }
  5800. }
  5801. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5802. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5803. // dllimport globals without explicit storage class are treated as extern. We
  5804. // have to change the storage class this early to get the right DeclContext.
  5805. if (SC == SC_None && !DC->isRecord() &&
  5806. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5807. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5808. SC = SC_Extern;
  5809. DeclContext *OriginalDC = DC;
  5810. bool IsLocalExternDecl = SC == SC_Extern &&
  5811. adjustContextForLocalExternDecl(DC);
  5812. if (SCSpec == DeclSpec::SCS_mutable) {
  5813. // mutable can only appear on non-static class members, so it's always
  5814. // an error here
  5815. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5816. D.setInvalidType();
  5817. SC = SC_None;
  5818. }
  5819. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5820. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5821. D.getDeclSpec().getStorageClassSpecLoc())) {
  5822. // In C++11, the 'register' storage class specifier is deprecated.
  5823. // Suppress the warning in system macros, it's used in macros in some
  5824. // popular C system headers, such as in glibc's htonl() macro.
  5825. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5826. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5827. : diag::warn_deprecated_register)
  5828. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5829. }
  5830. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5831. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5832. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5833. // appear in the declaration specifiers in an external declaration.
  5834. // Global Register+Asm is a GNU extension we support.
  5835. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5836. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5837. D.setInvalidType();
  5838. }
  5839. }
  5840. bool IsMemberSpecialization = false;
  5841. bool IsVariableTemplateSpecialization = false;
  5842. bool IsPartialSpecialization = false;
  5843. bool IsVariableTemplate = false;
  5844. VarDecl *NewVD = nullptr;
  5845. VarTemplateDecl *NewTemplate = nullptr;
  5846. TemplateParameterList *TemplateParams = nullptr;
  5847. if (!getLangOpts().CPlusPlus) {
  5848. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5849. II, R, TInfo, SC);
  5850. if (R->getContainedDeducedType())
  5851. ParsingInitForAutoVars.insert(NewVD);
  5852. if (D.isInvalidType())
  5853. NewVD->setInvalidDecl();
  5854. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  5855. NewVD->hasLocalStorage())
  5856. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  5857. NTCUC_AutoVar, NTCUK_Destruct);
  5858. } else {
  5859. bool Invalid = false;
  5860. if (DC->isRecord() && !CurContext->isRecord()) {
  5861. // This is an out-of-line definition of a static data member.
  5862. switch (SC) {
  5863. case SC_None:
  5864. break;
  5865. case SC_Static:
  5866. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5867. diag::err_static_out_of_line)
  5868. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5869. break;
  5870. case SC_Auto:
  5871. case SC_Register:
  5872. case SC_Extern:
  5873. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5874. // to names of variables declared in a block or to function parameters.
  5875. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5876. // of class members
  5877. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5878. diag::err_storage_class_for_static_member)
  5879. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5880. break;
  5881. case SC_PrivateExtern:
  5882. llvm_unreachable("C storage class in c++!");
  5883. }
  5884. }
  5885. if (SC == SC_Static && CurContext->isRecord()) {
  5886. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5887. if (RD->isLocalClass())
  5888. Diag(D.getIdentifierLoc(),
  5889. diag::err_static_data_member_not_allowed_in_local_class)
  5890. << Name << RD->getDeclName();
  5891. // C++98 [class.union]p1: If a union contains a static data member,
  5892. // the program is ill-formed. C++11 drops this restriction.
  5893. if (RD->isUnion())
  5894. Diag(D.getIdentifierLoc(),
  5895. getLangOpts().CPlusPlus11
  5896. ? diag::warn_cxx98_compat_static_data_member_in_union
  5897. : diag::ext_static_data_member_in_union) << Name;
  5898. // We conservatively disallow static data members in anonymous structs.
  5899. else if (!RD->getDeclName())
  5900. Diag(D.getIdentifierLoc(),
  5901. diag::err_static_data_member_not_allowed_in_anon_struct)
  5902. << Name << RD->isUnion();
  5903. }
  5904. }
  5905. // Match up the template parameter lists with the scope specifier, then
  5906. // determine whether we have a template or a template specialization.
  5907. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5908. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5909. D.getCXXScopeSpec(),
  5910. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5911. ? D.getName().TemplateId
  5912. : nullptr,
  5913. TemplateParamLists,
  5914. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5915. if (TemplateParams) {
  5916. if (!TemplateParams->size() &&
  5917. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5918. // There is an extraneous 'template<>' for this variable. Complain
  5919. // about it, but allow the declaration of the variable.
  5920. Diag(TemplateParams->getTemplateLoc(),
  5921. diag::err_template_variable_noparams)
  5922. << II
  5923. << SourceRange(TemplateParams->getTemplateLoc(),
  5924. TemplateParams->getRAngleLoc());
  5925. TemplateParams = nullptr;
  5926. } else {
  5927. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5928. // This is an explicit specialization or a partial specialization.
  5929. // FIXME: Check that we can declare a specialization here.
  5930. IsVariableTemplateSpecialization = true;
  5931. IsPartialSpecialization = TemplateParams->size() > 0;
  5932. } else { // if (TemplateParams->size() > 0)
  5933. // This is a template declaration.
  5934. IsVariableTemplate = true;
  5935. // Check that we can declare a template here.
  5936. if (CheckTemplateDeclScope(S, TemplateParams))
  5937. return nullptr;
  5938. // Only C++1y supports variable templates (N3651).
  5939. Diag(D.getIdentifierLoc(),
  5940. getLangOpts().CPlusPlus14
  5941. ? diag::warn_cxx11_compat_variable_template
  5942. : diag::ext_variable_template);
  5943. }
  5944. }
  5945. } else {
  5946. assert((Invalid ||
  5947. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5948. "should have a 'template<>' for this decl");
  5949. }
  5950. if (IsVariableTemplateSpecialization) {
  5951. SourceLocation TemplateKWLoc =
  5952. TemplateParamLists.size() > 0
  5953. ? TemplateParamLists[0]->getTemplateLoc()
  5954. : SourceLocation();
  5955. DeclResult Res = ActOnVarTemplateSpecialization(
  5956. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5957. IsPartialSpecialization);
  5958. if (Res.isInvalid())
  5959. return nullptr;
  5960. NewVD = cast<VarDecl>(Res.get());
  5961. AddToScope = false;
  5962. } else if (D.isDecompositionDeclarator()) {
  5963. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5964. D.getIdentifierLoc(), R, TInfo, SC,
  5965. Bindings);
  5966. } else
  5967. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5968. D.getIdentifierLoc(), II, R, TInfo, SC);
  5969. // If this is supposed to be a variable template, create it as such.
  5970. if (IsVariableTemplate) {
  5971. NewTemplate =
  5972. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5973. TemplateParams, NewVD);
  5974. NewVD->setDescribedVarTemplate(NewTemplate);
  5975. }
  5976. // If this decl has an auto type in need of deduction, make a note of the
  5977. // Decl so we can diagnose uses of it in its own initializer.
  5978. if (R->getContainedDeducedType())
  5979. ParsingInitForAutoVars.insert(NewVD);
  5980. if (D.isInvalidType() || Invalid) {
  5981. NewVD->setInvalidDecl();
  5982. if (NewTemplate)
  5983. NewTemplate->setInvalidDecl();
  5984. }
  5985. SetNestedNameSpecifier(*this, NewVD, D);
  5986. // If we have any template parameter lists that don't directly belong to
  5987. // the variable (matching the scope specifier), store them.
  5988. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5989. if (TemplateParamLists.size() > VDTemplateParamLists)
  5990. NewVD->setTemplateParameterListsInfo(
  5991. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5992. }
  5993. if (D.getDeclSpec().isInlineSpecified()) {
  5994. if (!getLangOpts().CPlusPlus) {
  5995. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5996. << 0;
  5997. } else if (CurContext->isFunctionOrMethod()) {
  5998. // 'inline' is not allowed on block scope variable declaration.
  5999. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6000. diag::err_inline_declaration_block_scope) << Name
  6001. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6002. } else {
  6003. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6004. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  6005. : diag::ext_inline_variable);
  6006. NewVD->setInlineSpecified();
  6007. }
  6008. }
  6009. // Set the lexical context. If the declarator has a C++ scope specifier, the
  6010. // lexical context will be different from the semantic context.
  6011. NewVD->setLexicalDeclContext(CurContext);
  6012. if (NewTemplate)
  6013. NewTemplate->setLexicalDeclContext(CurContext);
  6014. if (IsLocalExternDecl) {
  6015. if (D.isDecompositionDeclarator())
  6016. for (auto *B : Bindings)
  6017. B->setLocalExternDecl();
  6018. else
  6019. NewVD->setLocalExternDecl();
  6020. }
  6021. bool EmitTLSUnsupportedError = false;
  6022. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  6023. // C++11 [dcl.stc]p4:
  6024. // When thread_local is applied to a variable of block scope the
  6025. // storage-class-specifier static is implied if it does not appear
  6026. // explicitly.
  6027. // Core issue: 'static' is not implied if the variable is declared
  6028. // 'extern'.
  6029. if (NewVD->hasLocalStorage() &&
  6030. (SCSpec != DeclSpec::SCS_unspecified ||
  6031. TSCS != DeclSpec::TSCS_thread_local ||
  6032. !DC->isFunctionOrMethod()))
  6033. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6034. diag::err_thread_non_global)
  6035. << DeclSpec::getSpecifierName(TSCS);
  6036. else if (!Context.getTargetInfo().isTLSSupported()) {
  6037. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6038. // Postpone error emission until we've collected attributes required to
  6039. // figure out whether it's a host or device variable and whether the
  6040. // error should be ignored.
  6041. EmitTLSUnsupportedError = true;
  6042. // We still need to mark the variable as TLS so it shows up in AST with
  6043. // proper storage class for other tools to use even if we're not going
  6044. // to emit any code for it.
  6045. NewVD->setTSCSpec(TSCS);
  6046. } else
  6047. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6048. diag::err_thread_unsupported);
  6049. } else
  6050. NewVD->setTSCSpec(TSCS);
  6051. }
  6052. switch (D.getDeclSpec().getConstexprSpecifier()) {
  6053. case CSK_unspecified:
  6054. break;
  6055. case CSK_consteval:
  6056. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6057. diag::err_constexpr_wrong_decl_kind)
  6058. << D.getDeclSpec().getConstexprSpecifier();
  6059. LLVM_FALLTHROUGH;
  6060. case CSK_constexpr:
  6061. NewVD->setConstexpr(true);
  6062. // C++1z [dcl.spec.constexpr]p1:
  6063. // A static data member declared with the constexpr specifier is
  6064. // implicitly an inline variable.
  6065. if (NewVD->isStaticDataMember() &&
  6066. (getLangOpts().CPlusPlus17 ||
  6067. Context.getTargetInfo().getCXXABI().isMicrosoft()))
  6068. NewVD->setImplicitlyInline();
  6069. break;
  6070. case CSK_constinit:
  6071. if (!NewVD->hasGlobalStorage())
  6072. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6073. diag::err_constinit_local_variable);
  6074. else
  6075. NewVD->addAttr(ConstInitAttr::Create(
  6076. Context, D.getDeclSpec().getConstexprSpecLoc(),
  6077. AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
  6078. break;
  6079. }
  6080. // C99 6.7.4p3
  6081. // An inline definition of a function with external linkage shall
  6082. // not contain a definition of a modifiable object with static or
  6083. // thread storage duration...
  6084. // We only apply this when the function is required to be defined
  6085. // elsewhere, i.e. when the function is not 'extern inline'. Note
  6086. // that a local variable with thread storage duration still has to
  6087. // be marked 'static'. Also note that it's possible to get these
  6088. // semantics in C++ using __attribute__((gnu_inline)).
  6089. if (SC == SC_Static && S->getFnParent() != nullptr &&
  6090. !NewVD->getType().isConstQualified()) {
  6091. FunctionDecl *CurFD = getCurFunctionDecl();
  6092. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  6093. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6094. diag::warn_static_local_in_extern_inline);
  6095. MaybeSuggestAddingStaticToDecl(CurFD);
  6096. }
  6097. }
  6098. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6099. if (IsVariableTemplateSpecialization)
  6100. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6101. << (IsPartialSpecialization ? 1 : 0)
  6102. << FixItHint::CreateRemoval(
  6103. D.getDeclSpec().getModulePrivateSpecLoc());
  6104. else if (IsMemberSpecialization)
  6105. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6106. << 2
  6107. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6108. else if (NewVD->hasLocalStorage())
  6109. Diag(NewVD->getLocation(), diag::err_module_private_local)
  6110. << 0 << NewVD->getDeclName()
  6111. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6112. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6113. else {
  6114. NewVD->setModulePrivate();
  6115. if (NewTemplate)
  6116. NewTemplate->setModulePrivate();
  6117. for (auto *B : Bindings)
  6118. B->setModulePrivate();
  6119. }
  6120. }
  6121. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6122. ProcessDeclAttributes(S, NewVD, D);
  6123. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6124. if (EmitTLSUnsupportedError &&
  6125. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6126. (getLangOpts().OpenMPIsDevice &&
  6127. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
  6128. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6129. diag::err_thread_unsupported);
  6130. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6131. // storage [duration]."
  6132. if (SC == SC_None && S->getFnParent() != nullptr &&
  6133. (NewVD->hasAttr<CUDASharedAttr>() ||
  6134. NewVD->hasAttr<CUDAConstantAttr>())) {
  6135. NewVD->setStorageClass(SC_Static);
  6136. }
  6137. }
  6138. // Ensure that dllimport globals without explicit storage class are treated as
  6139. // extern. The storage class is set above using parsed attributes. Now we can
  6140. // check the VarDecl itself.
  6141. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6142. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6143. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6144. // In auto-retain/release, infer strong retension for variables of
  6145. // retainable type.
  6146. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6147. NewVD->setInvalidDecl();
  6148. // Handle GNU asm-label extension (encoded as an attribute).
  6149. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6150. // The parser guarantees this is a string.
  6151. StringLiteral *SE = cast<StringLiteral>(E);
  6152. StringRef Label = SE->getString();
  6153. if (S->getFnParent() != nullptr) {
  6154. switch (SC) {
  6155. case SC_None:
  6156. case SC_Auto:
  6157. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6158. break;
  6159. case SC_Register:
  6160. // Local Named register
  6161. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6162. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6163. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6164. break;
  6165. case SC_Static:
  6166. case SC_Extern:
  6167. case SC_PrivateExtern:
  6168. break;
  6169. }
  6170. } else if (SC == SC_Register) {
  6171. // Global Named register
  6172. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6173. const auto &TI = Context.getTargetInfo();
  6174. bool HasSizeMismatch;
  6175. if (!TI.isValidGCCRegisterName(Label))
  6176. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6177. else if (!TI.validateGlobalRegisterVariable(Label,
  6178. Context.getTypeSize(R),
  6179. HasSizeMismatch))
  6180. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6181. else if (HasSizeMismatch)
  6182. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6183. }
  6184. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6185. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6186. NewVD->setInvalidDecl(true);
  6187. }
  6188. }
  6189. NewVD->addAttr(::new (Context) AsmLabelAttr(
  6190. Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
  6191. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6192. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6193. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6194. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6195. if (isDeclExternC(NewVD)) {
  6196. NewVD->addAttr(I->second);
  6197. ExtnameUndeclaredIdentifiers.erase(I);
  6198. } else
  6199. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6200. << /*Variable*/1 << NewVD;
  6201. }
  6202. }
  6203. // Find the shadowed declaration before filtering for scope.
  6204. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6205. ? getShadowedDeclaration(NewVD, Previous)
  6206. : nullptr;
  6207. // Don't consider existing declarations that are in a different
  6208. // scope and are out-of-semantic-context declarations (if the new
  6209. // declaration has linkage).
  6210. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6211. D.getCXXScopeSpec().isNotEmpty() ||
  6212. IsMemberSpecialization ||
  6213. IsVariableTemplateSpecialization);
  6214. // Check whether the previous declaration is in the same block scope. This
  6215. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6216. if (getLangOpts().CPlusPlus &&
  6217. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6218. NewVD->setPreviousDeclInSameBlockScope(
  6219. Previous.isSingleResult() && !Previous.isShadowed() &&
  6220. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6221. if (!getLangOpts().CPlusPlus) {
  6222. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6223. } else {
  6224. // If this is an explicit specialization of a static data member, check it.
  6225. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6226. CheckMemberSpecialization(NewVD, Previous))
  6227. NewVD->setInvalidDecl();
  6228. // Merge the decl with the existing one if appropriate.
  6229. if (!Previous.empty()) {
  6230. if (Previous.isSingleResult() &&
  6231. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6232. D.getCXXScopeSpec().isSet()) {
  6233. // The user tried to define a non-static data member
  6234. // out-of-line (C++ [dcl.meaning]p1).
  6235. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6236. << D.getCXXScopeSpec().getRange();
  6237. Previous.clear();
  6238. NewVD->setInvalidDecl();
  6239. }
  6240. } else if (D.getCXXScopeSpec().isSet()) {
  6241. // No previous declaration in the qualifying scope.
  6242. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6243. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6244. << D.getCXXScopeSpec().getRange();
  6245. NewVD->setInvalidDecl();
  6246. }
  6247. if (!IsVariableTemplateSpecialization)
  6248. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6249. if (NewTemplate) {
  6250. VarTemplateDecl *PrevVarTemplate =
  6251. NewVD->getPreviousDecl()
  6252. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6253. : nullptr;
  6254. // Check the template parameter list of this declaration, possibly
  6255. // merging in the template parameter list from the previous variable
  6256. // template declaration.
  6257. if (CheckTemplateParameterList(
  6258. TemplateParams,
  6259. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6260. : nullptr,
  6261. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6262. DC->isDependentContext())
  6263. ? TPC_ClassTemplateMember
  6264. : TPC_VarTemplate))
  6265. NewVD->setInvalidDecl();
  6266. // If we are providing an explicit specialization of a static variable
  6267. // template, make a note of that.
  6268. if (PrevVarTemplate &&
  6269. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6270. PrevVarTemplate->setMemberSpecialization();
  6271. }
  6272. }
  6273. // Diagnose shadowed variables iff this isn't a redeclaration.
  6274. if (ShadowedDecl && !D.isRedeclaration())
  6275. CheckShadow(NewVD, ShadowedDecl, Previous);
  6276. ProcessPragmaWeak(S, NewVD);
  6277. // If this is the first declaration of an extern C variable, update
  6278. // the map of such variables.
  6279. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6280. isIncompleteDeclExternC(*this, NewVD))
  6281. RegisterLocallyScopedExternCDecl(NewVD, S);
  6282. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6283. Decl *ManglingContextDecl;
  6284. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6285. NewVD->getDeclContext(), ManglingContextDecl)) {
  6286. Context.setManglingNumber(
  6287. NewVD, MCtx->getManglingNumber(
  6288. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6289. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6290. }
  6291. }
  6292. // Special handling of variable named 'main'.
  6293. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6294. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6295. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6296. // C++ [basic.start.main]p3
  6297. // A program that declares a variable main at global scope is ill-formed.
  6298. if (getLangOpts().CPlusPlus)
  6299. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6300. // In C, and external-linkage variable named main results in undefined
  6301. // behavior.
  6302. else if (NewVD->hasExternalFormalLinkage())
  6303. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6304. }
  6305. if (D.isRedeclaration() && !Previous.empty()) {
  6306. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6307. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6308. D.isFunctionDefinition());
  6309. }
  6310. if (NewTemplate) {
  6311. if (NewVD->isInvalidDecl())
  6312. NewTemplate->setInvalidDecl();
  6313. ActOnDocumentableDecl(NewTemplate);
  6314. return NewTemplate;
  6315. }
  6316. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6317. CompleteMemberSpecialization(NewVD, Previous);
  6318. return NewVD;
  6319. }
  6320. /// Enum describing the %select options in diag::warn_decl_shadow.
  6321. enum ShadowedDeclKind {
  6322. SDK_Local,
  6323. SDK_Global,
  6324. SDK_StaticMember,
  6325. SDK_Field,
  6326. SDK_Typedef,
  6327. SDK_Using
  6328. };
  6329. /// Determine what kind of declaration we're shadowing.
  6330. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6331. const DeclContext *OldDC) {
  6332. if (isa<TypeAliasDecl>(ShadowedDecl))
  6333. return SDK_Using;
  6334. else if (isa<TypedefDecl>(ShadowedDecl))
  6335. return SDK_Typedef;
  6336. else if (isa<RecordDecl>(OldDC))
  6337. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6338. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6339. }
  6340. /// Return the location of the capture if the given lambda captures the given
  6341. /// variable \p VD, or an invalid source location otherwise.
  6342. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6343. const VarDecl *VD) {
  6344. for (const Capture &Capture : LSI->Captures) {
  6345. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6346. return Capture.getLocation();
  6347. }
  6348. return SourceLocation();
  6349. }
  6350. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6351. const LookupResult &R) {
  6352. // Only diagnose if we're shadowing an unambiguous field or variable.
  6353. if (R.getResultKind() != LookupResult::Found)
  6354. return false;
  6355. // Return false if warning is ignored.
  6356. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6357. }
  6358. /// Return the declaration shadowed by the given variable \p D, or null
  6359. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6360. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6361. const LookupResult &R) {
  6362. if (!shouldWarnIfShadowedDecl(Diags, R))
  6363. return nullptr;
  6364. // Don't diagnose declarations at file scope.
  6365. if (D->hasGlobalStorage())
  6366. return nullptr;
  6367. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6368. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6369. ? ShadowedDecl
  6370. : nullptr;
  6371. }
  6372. /// Return the declaration shadowed by the given typedef \p D, or null
  6373. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6374. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6375. const LookupResult &R) {
  6376. // Don't warn if typedef declaration is part of a class
  6377. if (D->getDeclContext()->isRecord())
  6378. return nullptr;
  6379. if (!shouldWarnIfShadowedDecl(Diags, R))
  6380. return nullptr;
  6381. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6382. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6383. }
  6384. /// Diagnose variable or built-in function shadowing. Implements
  6385. /// -Wshadow.
  6386. ///
  6387. /// This method is called whenever a VarDecl is added to a "useful"
  6388. /// scope.
  6389. ///
  6390. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6391. /// \param R the lookup of the name
  6392. ///
  6393. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6394. const LookupResult &R) {
  6395. DeclContext *NewDC = D->getDeclContext();
  6396. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6397. // Fields are not shadowed by variables in C++ static methods.
  6398. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6399. if (MD->isStatic())
  6400. return;
  6401. // Fields shadowed by constructor parameters are a special case. Usually
  6402. // the constructor initializes the field with the parameter.
  6403. if (isa<CXXConstructorDecl>(NewDC))
  6404. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6405. // Remember that this was shadowed so we can either warn about its
  6406. // modification or its existence depending on warning settings.
  6407. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6408. return;
  6409. }
  6410. }
  6411. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6412. if (shadowedVar->isExternC()) {
  6413. // For shadowing external vars, make sure that we point to the global
  6414. // declaration, not a locally scoped extern declaration.
  6415. for (auto I : shadowedVar->redecls())
  6416. if (I->isFileVarDecl()) {
  6417. ShadowedDecl = I;
  6418. break;
  6419. }
  6420. }
  6421. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6422. unsigned WarningDiag = diag::warn_decl_shadow;
  6423. SourceLocation CaptureLoc;
  6424. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6425. isa<CXXMethodDecl>(NewDC)) {
  6426. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6427. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6428. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6429. // Try to avoid warnings for lambdas with an explicit capture list.
  6430. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6431. // Warn only when the lambda captures the shadowed decl explicitly.
  6432. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6433. if (CaptureLoc.isInvalid())
  6434. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6435. } else {
  6436. // Remember that this was shadowed so we can avoid the warning if the
  6437. // shadowed decl isn't captured and the warning settings allow it.
  6438. cast<LambdaScopeInfo>(getCurFunction())
  6439. ->ShadowingDecls.push_back(
  6440. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6441. return;
  6442. }
  6443. }
  6444. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6445. // A variable can't shadow a local variable in an enclosing scope, if
  6446. // they are separated by a non-capturing declaration context.
  6447. for (DeclContext *ParentDC = NewDC;
  6448. ParentDC && !ParentDC->Equals(OldDC);
  6449. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6450. // Only block literals, captured statements, and lambda expressions
  6451. // can capture; other scopes don't.
  6452. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6453. !isLambdaCallOperator(ParentDC)) {
  6454. return;
  6455. }
  6456. }
  6457. }
  6458. }
  6459. }
  6460. // Only warn about certain kinds of shadowing for class members.
  6461. if (NewDC && NewDC->isRecord()) {
  6462. // In particular, don't warn about shadowing non-class members.
  6463. if (!OldDC->isRecord())
  6464. return;
  6465. // TODO: should we warn about static data members shadowing
  6466. // static data members from base classes?
  6467. // TODO: don't diagnose for inaccessible shadowed members.
  6468. // This is hard to do perfectly because we might friend the
  6469. // shadowing context, but that's just a false negative.
  6470. }
  6471. DeclarationName Name = R.getLookupName();
  6472. // Emit warning and note.
  6473. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6474. return;
  6475. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6476. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6477. if (!CaptureLoc.isInvalid())
  6478. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6479. << Name << /*explicitly*/ 1;
  6480. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6481. }
  6482. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6483. /// when these variables are captured by the lambda.
  6484. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6485. for (const auto &Shadow : LSI->ShadowingDecls) {
  6486. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6487. // Try to avoid the warning when the shadowed decl isn't captured.
  6488. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6489. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6490. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6491. ? diag::warn_decl_shadow_uncaptured_local
  6492. : diag::warn_decl_shadow)
  6493. << Shadow.VD->getDeclName()
  6494. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6495. if (!CaptureLoc.isInvalid())
  6496. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6497. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6498. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6499. }
  6500. }
  6501. /// Check -Wshadow without the advantage of a previous lookup.
  6502. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6503. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6504. return;
  6505. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6506. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6507. LookupName(R, S);
  6508. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6509. CheckShadow(D, ShadowedDecl, R);
  6510. }
  6511. /// Check if 'E', which is an expression that is about to be modified, refers
  6512. /// to a constructor parameter that shadows a field.
  6513. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6514. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6515. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6516. return;
  6517. E = E->IgnoreParenImpCasts();
  6518. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6519. if (!DRE)
  6520. return;
  6521. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6522. auto I = ShadowingDecls.find(D);
  6523. if (I == ShadowingDecls.end())
  6524. return;
  6525. const NamedDecl *ShadowedDecl = I->second;
  6526. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6527. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6528. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6529. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6530. // Avoid issuing multiple warnings about the same decl.
  6531. ShadowingDecls.erase(I);
  6532. }
  6533. /// Check for conflict between this global or extern "C" declaration and
  6534. /// previous global or extern "C" declarations. This is only used in C++.
  6535. template<typename T>
  6536. static bool checkGlobalOrExternCConflict(
  6537. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6538. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6539. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6540. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6541. // The common case: this global doesn't conflict with any extern "C"
  6542. // declaration.
  6543. return false;
  6544. }
  6545. if (Prev) {
  6546. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6547. // Both the old and new declarations have C language linkage. This is a
  6548. // redeclaration.
  6549. Previous.clear();
  6550. Previous.addDecl(Prev);
  6551. return true;
  6552. }
  6553. // This is a global, non-extern "C" declaration, and there is a previous
  6554. // non-global extern "C" declaration. Diagnose if this is a variable
  6555. // declaration.
  6556. if (!isa<VarDecl>(ND))
  6557. return false;
  6558. } else {
  6559. // The declaration is extern "C". Check for any declaration in the
  6560. // translation unit which might conflict.
  6561. if (IsGlobal) {
  6562. // We have already performed the lookup into the translation unit.
  6563. IsGlobal = false;
  6564. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6565. I != E; ++I) {
  6566. if (isa<VarDecl>(*I)) {
  6567. Prev = *I;
  6568. break;
  6569. }
  6570. }
  6571. } else {
  6572. DeclContext::lookup_result R =
  6573. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6574. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6575. I != E; ++I) {
  6576. if (isa<VarDecl>(*I)) {
  6577. Prev = *I;
  6578. break;
  6579. }
  6580. // FIXME: If we have any other entity with this name in global scope,
  6581. // the declaration is ill-formed, but that is a defect: it breaks the
  6582. // 'stat' hack, for instance. Only variables can have mangled name
  6583. // clashes with extern "C" declarations, so only they deserve a
  6584. // diagnostic.
  6585. }
  6586. }
  6587. if (!Prev)
  6588. return false;
  6589. }
  6590. // Use the first declaration's location to ensure we point at something which
  6591. // is lexically inside an extern "C" linkage-spec.
  6592. assert(Prev && "should have found a previous declaration to diagnose");
  6593. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6594. Prev = FD->getFirstDecl();
  6595. else
  6596. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6597. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6598. << IsGlobal << ND;
  6599. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6600. << IsGlobal;
  6601. return false;
  6602. }
  6603. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6604. /// if we have found that this is a redeclaration of some prior entity.
  6605. ///
  6606. /// Per C++ [dcl.link]p6:
  6607. /// Two declarations [for a function or variable] with C language linkage
  6608. /// with the same name that appear in different scopes refer to the same
  6609. /// [entity]. An entity with C language linkage shall not be declared with
  6610. /// the same name as an entity in global scope.
  6611. template<typename T>
  6612. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6613. LookupResult &Previous) {
  6614. if (!S.getLangOpts().CPlusPlus) {
  6615. // In C, when declaring a global variable, look for a corresponding 'extern'
  6616. // variable declared in function scope. We don't need this in C++, because
  6617. // we find local extern decls in the surrounding file-scope DeclContext.
  6618. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6619. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6620. Previous.clear();
  6621. Previous.addDecl(Prev);
  6622. return true;
  6623. }
  6624. }
  6625. return false;
  6626. }
  6627. // A declaration in the translation unit can conflict with an extern "C"
  6628. // declaration.
  6629. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6630. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6631. // An extern "C" declaration can conflict with a declaration in the
  6632. // translation unit or can be a redeclaration of an extern "C" declaration
  6633. // in another scope.
  6634. if (isIncompleteDeclExternC(S,ND))
  6635. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6636. // Neither global nor extern "C": nothing to do.
  6637. return false;
  6638. }
  6639. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6640. // If the decl is already known invalid, don't check it.
  6641. if (NewVD->isInvalidDecl())
  6642. return;
  6643. QualType T = NewVD->getType();
  6644. // Defer checking an 'auto' type until its initializer is attached.
  6645. if (T->isUndeducedType())
  6646. return;
  6647. if (NewVD->hasAttrs())
  6648. CheckAlignasUnderalignment(NewVD);
  6649. if (T->isObjCObjectType()) {
  6650. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6651. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6652. T = Context.getObjCObjectPointerType(T);
  6653. NewVD->setType(T);
  6654. }
  6655. // Emit an error if an address space was applied to decl with local storage.
  6656. // This includes arrays of objects with address space qualifiers, but not
  6657. // automatic variables that point to other address spaces.
  6658. // ISO/IEC TR 18037 S5.1.2
  6659. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6660. T.getAddressSpace() != LangAS::Default) {
  6661. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6662. NewVD->setInvalidDecl();
  6663. return;
  6664. }
  6665. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6666. // scope.
  6667. if (getLangOpts().OpenCLVersion == 120 &&
  6668. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6669. NewVD->isStaticLocal()) {
  6670. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6671. NewVD->setInvalidDecl();
  6672. return;
  6673. }
  6674. if (getLangOpts().OpenCL) {
  6675. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6676. if (NewVD->hasAttr<BlocksAttr>()) {
  6677. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6678. return;
  6679. }
  6680. if (T->isBlockPointerType()) {
  6681. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6682. // can't use 'extern' storage class.
  6683. if (!T.isConstQualified()) {
  6684. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6685. << 0 /*const*/;
  6686. NewVD->setInvalidDecl();
  6687. return;
  6688. }
  6689. if (NewVD->hasExternalStorage()) {
  6690. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6691. NewVD->setInvalidDecl();
  6692. return;
  6693. }
  6694. }
  6695. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6696. // __constant address space.
  6697. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6698. // variables inside a function can also be declared in the global
  6699. // address space.
  6700. // C++ for OpenCL inherits rule from OpenCL C v2.0.
  6701. // FIXME: Adding local AS in C++ for OpenCL might make sense.
  6702. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6703. NewVD->hasExternalStorage()) {
  6704. if (!T->isSamplerT() &&
  6705. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6706. (T.getAddressSpace() == LangAS::opencl_global &&
  6707. (getLangOpts().OpenCLVersion == 200 ||
  6708. getLangOpts().OpenCLCPlusPlus)))) {
  6709. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6710. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6711. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6712. << Scope << "global or constant";
  6713. else
  6714. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6715. << Scope << "constant";
  6716. NewVD->setInvalidDecl();
  6717. return;
  6718. }
  6719. } else {
  6720. if (T.getAddressSpace() == LangAS::opencl_global) {
  6721. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6722. << 1 /*is any function*/ << "global";
  6723. NewVD->setInvalidDecl();
  6724. return;
  6725. }
  6726. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6727. T.getAddressSpace() == LangAS::opencl_local) {
  6728. FunctionDecl *FD = getCurFunctionDecl();
  6729. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6730. // in functions.
  6731. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6732. if (T.getAddressSpace() == LangAS::opencl_constant)
  6733. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6734. << 0 /*non-kernel only*/ << "constant";
  6735. else
  6736. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6737. << 0 /*non-kernel only*/ << "local";
  6738. NewVD->setInvalidDecl();
  6739. return;
  6740. }
  6741. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6742. // in the outermost scope of a kernel function.
  6743. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6744. if (!getCurScope()->isFunctionScope()) {
  6745. if (T.getAddressSpace() == LangAS::opencl_constant)
  6746. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6747. << "constant";
  6748. else
  6749. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6750. << "local";
  6751. NewVD->setInvalidDecl();
  6752. return;
  6753. }
  6754. }
  6755. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  6756. // If we are parsing a template we didn't deduce an addr
  6757. // space yet.
  6758. T.getAddressSpace() != LangAS::Default) {
  6759. // Do not allow other address spaces on automatic variable.
  6760. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6761. NewVD->setInvalidDecl();
  6762. return;
  6763. }
  6764. }
  6765. }
  6766. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6767. && !NewVD->hasAttr<BlocksAttr>()) {
  6768. if (getLangOpts().getGC() != LangOptions::NonGC)
  6769. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6770. else {
  6771. assert(!getLangOpts().ObjCAutoRefCount);
  6772. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6773. }
  6774. }
  6775. bool isVM = T->isVariablyModifiedType();
  6776. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6777. NewVD->hasAttr<BlocksAttr>())
  6778. setFunctionHasBranchProtectedScope();
  6779. if ((isVM && NewVD->hasLinkage()) ||
  6780. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6781. bool SizeIsNegative;
  6782. llvm::APSInt Oversized;
  6783. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6784. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6785. QualType FixedT;
  6786. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6787. FixedT = FixedTInfo->getType();
  6788. else if (FixedTInfo) {
  6789. // Type and type-as-written are canonically different. We need to fix up
  6790. // both types separately.
  6791. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6792. Oversized);
  6793. }
  6794. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6795. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6796. // FIXME: This won't give the correct result for
  6797. // int a[10][n];
  6798. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6799. if (NewVD->isFileVarDecl())
  6800. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6801. << SizeRange;
  6802. else if (NewVD->isStaticLocal())
  6803. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6804. << SizeRange;
  6805. else
  6806. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6807. << SizeRange;
  6808. NewVD->setInvalidDecl();
  6809. return;
  6810. }
  6811. if (!FixedTInfo) {
  6812. if (NewVD->isFileVarDecl())
  6813. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6814. else
  6815. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6816. NewVD->setInvalidDecl();
  6817. return;
  6818. }
  6819. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6820. NewVD->setType(FixedT);
  6821. NewVD->setTypeSourceInfo(FixedTInfo);
  6822. }
  6823. if (T->isVoidType()) {
  6824. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6825. // of objects and functions.
  6826. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6827. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6828. << T;
  6829. NewVD->setInvalidDecl();
  6830. return;
  6831. }
  6832. }
  6833. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6834. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6835. NewVD->setInvalidDecl();
  6836. return;
  6837. }
  6838. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6839. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6840. NewVD->setInvalidDecl();
  6841. return;
  6842. }
  6843. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6844. RequireLiteralType(NewVD->getLocation(), T,
  6845. diag::err_constexpr_var_non_literal)) {
  6846. NewVD->setInvalidDecl();
  6847. return;
  6848. }
  6849. }
  6850. /// Perform semantic checking on a newly-created variable
  6851. /// declaration.
  6852. ///
  6853. /// This routine performs all of the type-checking required for a
  6854. /// variable declaration once it has been built. It is used both to
  6855. /// check variables after they have been parsed and their declarators
  6856. /// have been translated into a declaration, and to check variables
  6857. /// that have been instantiated from a template.
  6858. ///
  6859. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6860. ///
  6861. /// Returns true if the variable declaration is a redeclaration.
  6862. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6863. CheckVariableDeclarationType(NewVD);
  6864. // If the decl is already known invalid, don't check it.
  6865. if (NewVD->isInvalidDecl())
  6866. return false;
  6867. // If we did not find anything by this name, look for a non-visible
  6868. // extern "C" declaration with the same name.
  6869. if (Previous.empty() &&
  6870. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6871. Previous.setShadowed();
  6872. if (!Previous.empty()) {
  6873. MergeVarDecl(NewVD, Previous);
  6874. return true;
  6875. }
  6876. return false;
  6877. }
  6878. namespace {
  6879. struct FindOverriddenMethod {
  6880. Sema *S;
  6881. CXXMethodDecl *Method;
  6882. /// Member lookup function that determines whether a given C++
  6883. /// method overrides a method in a base class, to be used with
  6884. /// CXXRecordDecl::lookupInBases().
  6885. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6886. RecordDecl *BaseRecord =
  6887. Specifier->getType()->castAs<RecordType>()->getDecl();
  6888. DeclarationName Name = Method->getDeclName();
  6889. // FIXME: Do we care about other names here too?
  6890. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6891. // We really want to find the base class destructor here.
  6892. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6893. CanQualType CT = S->Context.getCanonicalType(T);
  6894. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6895. }
  6896. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6897. Path.Decls = Path.Decls.slice(1)) {
  6898. NamedDecl *D = Path.Decls.front();
  6899. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6900. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6901. return true;
  6902. }
  6903. }
  6904. return false;
  6905. }
  6906. };
  6907. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6908. } // end anonymous namespace
  6909. /// Report an error regarding overriding, along with any relevant
  6910. /// overridden methods.
  6911. ///
  6912. /// \param DiagID the primary error to report.
  6913. /// \param MD the overriding method.
  6914. /// \param OEK which overrides to include as notes.
  6915. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6916. OverrideErrorKind OEK = OEK_All) {
  6917. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6918. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6919. // This check (& the OEK parameter) could be replaced by a predicate, but
  6920. // without lambdas that would be overkill. This is still nicer than writing
  6921. // out the diag loop 3 times.
  6922. if ((OEK == OEK_All) ||
  6923. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6924. (OEK == OEK_Deleted && O->isDeleted()))
  6925. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6926. }
  6927. }
  6928. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6929. /// and if so, check that it's a valid override and remember it.
  6930. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6931. // Look for methods in base classes that this method might override.
  6932. CXXBasePaths Paths;
  6933. FindOverriddenMethod FOM;
  6934. FOM.Method = MD;
  6935. FOM.S = this;
  6936. bool hasDeletedOverridenMethods = false;
  6937. bool hasNonDeletedOverridenMethods = false;
  6938. bool AddedAny = false;
  6939. if (DC->lookupInBases(FOM, Paths)) {
  6940. for (auto *I : Paths.found_decls()) {
  6941. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6942. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6943. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6944. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6945. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6946. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6947. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6948. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6949. AddedAny = true;
  6950. }
  6951. }
  6952. }
  6953. }
  6954. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6955. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6956. }
  6957. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6958. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6959. }
  6960. return AddedAny;
  6961. }
  6962. namespace {
  6963. // Struct for holding all of the extra arguments needed by
  6964. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6965. struct ActOnFDArgs {
  6966. Scope *S;
  6967. Declarator &D;
  6968. MultiTemplateParamsArg TemplateParamLists;
  6969. bool AddToScope;
  6970. };
  6971. } // end anonymous namespace
  6972. namespace {
  6973. // Callback to only accept typo corrections that have a non-zero edit distance.
  6974. // Also only accept corrections that have the same parent decl.
  6975. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  6976. public:
  6977. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6978. CXXRecordDecl *Parent)
  6979. : Context(Context), OriginalFD(TypoFD),
  6980. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6981. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6982. if (candidate.getEditDistance() == 0)
  6983. return false;
  6984. SmallVector<unsigned, 1> MismatchedParams;
  6985. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6986. CDeclEnd = candidate.end();
  6987. CDecl != CDeclEnd; ++CDecl) {
  6988. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6989. if (FD && !FD->hasBody() &&
  6990. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6991. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6992. CXXRecordDecl *Parent = MD->getParent();
  6993. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6994. return true;
  6995. } else if (!ExpectedParent) {
  6996. return true;
  6997. }
  6998. }
  6999. }
  7000. return false;
  7001. }
  7002. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  7003. return std::make_unique<DifferentNameValidatorCCC>(*this);
  7004. }
  7005. private:
  7006. ASTContext &Context;
  7007. FunctionDecl *OriginalFD;
  7008. CXXRecordDecl *ExpectedParent;
  7009. };
  7010. } // end anonymous namespace
  7011. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  7012. TypoCorrectedFunctionDefinitions.insert(F);
  7013. }
  7014. /// Generate diagnostics for an invalid function redeclaration.
  7015. ///
  7016. /// This routine handles generating the diagnostic messages for an invalid
  7017. /// function redeclaration, including finding possible similar declarations
  7018. /// or performing typo correction if there are no previous declarations with
  7019. /// the same name.
  7020. ///
  7021. /// Returns a NamedDecl iff typo correction was performed and substituting in
  7022. /// the new declaration name does not cause new errors.
  7023. static NamedDecl *DiagnoseInvalidRedeclaration(
  7024. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  7025. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  7026. DeclarationName Name = NewFD->getDeclName();
  7027. DeclContext *NewDC = NewFD->getDeclContext();
  7028. SmallVector<unsigned, 1> MismatchedParams;
  7029. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  7030. TypoCorrection Correction;
  7031. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  7032. unsigned DiagMsg =
  7033. IsLocalFriend ? diag::err_no_matching_local_friend :
  7034. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  7035. diag::err_member_decl_does_not_match;
  7036. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  7037. IsLocalFriend ? Sema::LookupLocalFriendName
  7038. : Sema::LookupOrdinaryName,
  7039. Sema::ForVisibleRedeclaration);
  7040. NewFD->setInvalidDecl();
  7041. if (IsLocalFriend)
  7042. SemaRef.LookupName(Prev, S);
  7043. else
  7044. SemaRef.LookupQualifiedName(Prev, NewDC);
  7045. assert(!Prev.isAmbiguous() &&
  7046. "Cannot have an ambiguity in previous-declaration lookup");
  7047. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7048. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  7049. MD ? MD->getParent() : nullptr);
  7050. if (!Prev.empty()) {
  7051. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  7052. Func != FuncEnd; ++Func) {
  7053. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  7054. if (FD &&
  7055. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7056. // Add 1 to the index so that 0 can mean the mismatch didn't
  7057. // involve a parameter
  7058. unsigned ParamNum =
  7059. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  7060. NearMatches.push_back(std::make_pair(FD, ParamNum));
  7061. }
  7062. }
  7063. // If the qualified name lookup yielded nothing, try typo correction
  7064. } else if ((Correction = SemaRef.CorrectTypo(
  7065. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  7066. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  7067. IsLocalFriend ? nullptr : NewDC))) {
  7068. // Set up everything for the call to ActOnFunctionDeclarator
  7069. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  7070. ExtraArgs.D.getIdentifierLoc());
  7071. Previous.clear();
  7072. Previous.setLookupName(Correction.getCorrection());
  7073. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  7074. CDeclEnd = Correction.end();
  7075. CDecl != CDeclEnd; ++CDecl) {
  7076. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7077. if (FD && !FD->hasBody() &&
  7078. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7079. Previous.addDecl(FD);
  7080. }
  7081. }
  7082. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  7083. NamedDecl *Result;
  7084. // Retry building the function declaration with the new previous
  7085. // declarations, and with errors suppressed.
  7086. {
  7087. // Trap errors.
  7088. Sema::SFINAETrap Trap(SemaRef);
  7089. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  7090. // pieces need to verify the typo-corrected C++ declaration and hopefully
  7091. // eliminate the need for the parameter pack ExtraArgs.
  7092. Result = SemaRef.ActOnFunctionDeclarator(
  7093. ExtraArgs.S, ExtraArgs.D,
  7094. Correction.getCorrectionDecl()->getDeclContext(),
  7095. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  7096. ExtraArgs.AddToScope);
  7097. if (Trap.hasErrorOccurred())
  7098. Result = nullptr;
  7099. }
  7100. if (Result) {
  7101. // Determine which correction we picked.
  7102. Decl *Canonical = Result->getCanonicalDecl();
  7103. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7104. I != E; ++I)
  7105. if ((*I)->getCanonicalDecl() == Canonical)
  7106. Correction.setCorrectionDecl(*I);
  7107. // Let Sema know about the correction.
  7108. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  7109. SemaRef.diagnoseTypo(
  7110. Correction,
  7111. SemaRef.PDiag(IsLocalFriend
  7112. ? diag::err_no_matching_local_friend_suggest
  7113. : diag::err_member_decl_does_not_match_suggest)
  7114. << Name << NewDC << IsDefinition);
  7115. return Result;
  7116. }
  7117. // Pretend the typo correction never occurred
  7118. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7119. ExtraArgs.D.getIdentifierLoc());
  7120. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7121. Previous.clear();
  7122. Previous.setLookupName(Name);
  7123. }
  7124. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7125. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7126. bool NewFDisConst = false;
  7127. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7128. NewFDisConst = NewMD->isConst();
  7129. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7130. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7131. NearMatch != NearMatchEnd; ++NearMatch) {
  7132. FunctionDecl *FD = NearMatch->first;
  7133. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7134. bool FDisConst = MD && MD->isConst();
  7135. bool IsMember = MD || !IsLocalFriend;
  7136. // FIXME: These notes are poorly worded for the local friend case.
  7137. if (unsigned Idx = NearMatch->second) {
  7138. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7139. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7140. if (Loc.isInvalid()) Loc = FD->getLocation();
  7141. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7142. : diag::note_local_decl_close_param_match)
  7143. << Idx << FDParam->getType()
  7144. << NewFD->getParamDecl(Idx - 1)->getType();
  7145. } else if (FDisConst != NewFDisConst) {
  7146. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7147. << NewFDisConst << FD->getSourceRange().getEnd();
  7148. } else
  7149. SemaRef.Diag(FD->getLocation(),
  7150. IsMember ? diag::note_member_def_close_match
  7151. : diag::note_local_decl_close_match);
  7152. }
  7153. return nullptr;
  7154. }
  7155. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7156. switch (D.getDeclSpec().getStorageClassSpec()) {
  7157. default: llvm_unreachable("Unknown storage class!");
  7158. case DeclSpec::SCS_auto:
  7159. case DeclSpec::SCS_register:
  7160. case DeclSpec::SCS_mutable:
  7161. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7162. diag::err_typecheck_sclass_func);
  7163. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7164. D.setInvalidType();
  7165. break;
  7166. case DeclSpec::SCS_unspecified: break;
  7167. case DeclSpec::SCS_extern:
  7168. if (D.getDeclSpec().isExternInLinkageSpec())
  7169. return SC_None;
  7170. return SC_Extern;
  7171. case DeclSpec::SCS_static: {
  7172. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7173. // C99 6.7.1p5:
  7174. // The declaration of an identifier for a function that has
  7175. // block scope shall have no explicit storage-class specifier
  7176. // other than extern
  7177. // See also (C++ [dcl.stc]p4).
  7178. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7179. diag::err_static_block_func);
  7180. break;
  7181. } else
  7182. return SC_Static;
  7183. }
  7184. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7185. }
  7186. // No explicit storage class has already been returned
  7187. return SC_None;
  7188. }
  7189. static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7190. DeclContext *DC, QualType &R,
  7191. TypeSourceInfo *TInfo,
  7192. StorageClass SC,
  7193. bool &IsVirtualOkay) {
  7194. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7195. DeclarationName Name = NameInfo.getName();
  7196. FunctionDecl *NewFD = nullptr;
  7197. bool isInline = D.getDeclSpec().isInlineSpecified();
  7198. if (!SemaRef.getLangOpts().CPlusPlus) {
  7199. // Determine whether the function was written with a
  7200. // prototype. This true when:
  7201. // - there is a prototype in the declarator, or
  7202. // - the type R of the function is some kind of typedef or other non-
  7203. // attributed reference to a type name (which eventually refers to a
  7204. // function type).
  7205. bool HasPrototype =
  7206. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7207. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7208. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7209. R, TInfo, SC, isInline, HasPrototype,
  7210. CSK_unspecified);
  7211. if (D.isInvalidType())
  7212. NewFD->setInvalidDecl();
  7213. return NewFD;
  7214. }
  7215. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7216. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7217. if (ConstexprKind == CSK_constinit) {
  7218. SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7219. diag::err_constexpr_wrong_decl_kind)
  7220. << ConstexprKind;
  7221. ConstexprKind = CSK_unspecified;
  7222. D.getMutableDeclSpec().ClearConstexprSpec();
  7223. }
  7224. // Check that the return type is not an abstract class type.
  7225. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7226. // the class has been completely parsed.
  7227. if (!DC->isRecord() &&
  7228. SemaRef.RequireNonAbstractType(
  7229. D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
  7230. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7231. D.setInvalidType();
  7232. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7233. // This is a C++ constructor declaration.
  7234. assert(DC->isRecord() &&
  7235. "Constructors can only be declared in a member context");
  7236. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7237. return CXXConstructorDecl::Create(
  7238. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7239. TInfo, ExplicitSpecifier, isInline,
  7240. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7241. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7242. // This is a C++ destructor declaration.
  7243. if (DC->isRecord()) {
  7244. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7245. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7246. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7247. SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
  7248. isInline,
  7249. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7250. // If the destructor needs an implicit exception specification, set it
  7251. // now. FIXME: It'd be nice to be able to create the right type to start
  7252. // with, but the type needs to reference the destructor declaration.
  7253. if (SemaRef.getLangOpts().CPlusPlus11)
  7254. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7255. IsVirtualOkay = true;
  7256. return NewDD;
  7257. } else {
  7258. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7259. D.setInvalidType();
  7260. // Create a FunctionDecl to satisfy the function definition parsing
  7261. // code path.
  7262. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7263. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7264. isInline,
  7265. /*hasPrototype=*/true, ConstexprKind);
  7266. }
  7267. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7268. if (!DC->isRecord()) {
  7269. SemaRef.Diag(D.getIdentifierLoc(),
  7270. diag::err_conv_function_not_member);
  7271. return nullptr;
  7272. }
  7273. SemaRef.CheckConversionDeclarator(D, R, SC);
  7274. if (D.isInvalidType())
  7275. return nullptr;
  7276. IsVirtualOkay = true;
  7277. return CXXConversionDecl::Create(
  7278. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7279. TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
  7280. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7281. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7282. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7283. ExplicitSpecifier, NameInfo, R, TInfo,
  7284. D.getEndLoc());
  7285. } else if (DC->isRecord()) {
  7286. // If the name of the function is the same as the name of the record,
  7287. // then this must be an invalid constructor that has a return type.
  7288. // (The parser checks for a return type and makes the declarator a
  7289. // constructor if it has no return type).
  7290. if (Name.getAsIdentifierInfo() &&
  7291. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7292. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7293. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7294. << SourceRange(D.getIdentifierLoc());
  7295. return nullptr;
  7296. }
  7297. // This is a C++ method declaration.
  7298. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7299. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7300. TInfo, SC, isInline, ConstexprKind, SourceLocation());
  7301. IsVirtualOkay = !Ret->isStatic();
  7302. return Ret;
  7303. } else {
  7304. bool isFriend =
  7305. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7306. if (!isFriend && SemaRef.CurContext->isRecord())
  7307. return nullptr;
  7308. // Determine whether the function was written with a
  7309. // prototype. This true when:
  7310. // - we're in C++ (where every function has a prototype),
  7311. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7312. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7313. ConstexprKind);
  7314. }
  7315. }
  7316. enum OpenCLParamType {
  7317. ValidKernelParam,
  7318. PtrPtrKernelParam,
  7319. PtrKernelParam,
  7320. InvalidAddrSpacePtrKernelParam,
  7321. InvalidKernelParam,
  7322. RecordKernelParam
  7323. };
  7324. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7325. // Size dependent types are just typedefs to normal integer types
  7326. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7327. // integers other than by their names.
  7328. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7329. // Remove typedefs one by one until we reach a typedef
  7330. // for a size dependent type.
  7331. QualType DesugaredTy = Ty;
  7332. do {
  7333. ArrayRef<StringRef> Names(SizeTypeNames);
  7334. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7335. if (Names.end() != Match)
  7336. return true;
  7337. Ty = DesugaredTy;
  7338. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7339. } while (DesugaredTy != Ty);
  7340. return false;
  7341. }
  7342. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7343. if (PT->isPointerType()) {
  7344. QualType PointeeType = PT->getPointeeType();
  7345. if (PointeeType->isPointerType())
  7346. return PtrPtrKernelParam;
  7347. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7348. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7349. PointeeType.getAddressSpace() == LangAS::Default)
  7350. return InvalidAddrSpacePtrKernelParam;
  7351. return PtrKernelParam;
  7352. }
  7353. // OpenCL v1.2 s6.9.k:
  7354. // Arguments to kernel functions in a program cannot be declared with the
  7355. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7356. // uintptr_t or a struct and/or union that contain fields declared to be one
  7357. // of these built-in scalar types.
  7358. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7359. return InvalidKernelParam;
  7360. if (PT->isImageType())
  7361. return PtrKernelParam;
  7362. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7363. return InvalidKernelParam;
  7364. // OpenCL extension spec v1.2 s9.5:
  7365. // This extension adds support for half scalar and vector types as built-in
  7366. // types that can be used for arithmetic operations, conversions etc.
  7367. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7368. return InvalidKernelParam;
  7369. if (PT->isRecordType())
  7370. return RecordKernelParam;
  7371. // Look into an array argument to check if it has a forbidden type.
  7372. if (PT->isArrayType()) {
  7373. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7374. // Call ourself to check an underlying type of an array. Since the
  7375. // getPointeeOrArrayElementType returns an innermost type which is not an
  7376. // array, this recursive call only happens once.
  7377. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7378. }
  7379. return ValidKernelParam;
  7380. }
  7381. static void checkIsValidOpenCLKernelParameter(
  7382. Sema &S,
  7383. Declarator &D,
  7384. ParmVarDecl *Param,
  7385. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7386. QualType PT = Param->getType();
  7387. // Cache the valid types we encounter to avoid rechecking structs that are
  7388. // used again
  7389. if (ValidTypes.count(PT.getTypePtr()))
  7390. return;
  7391. switch (getOpenCLKernelParameterType(S, PT)) {
  7392. case PtrPtrKernelParam:
  7393. // OpenCL v1.2 s6.9.a:
  7394. // A kernel function argument cannot be declared as a
  7395. // pointer to a pointer type.
  7396. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7397. D.setInvalidType();
  7398. return;
  7399. case InvalidAddrSpacePtrKernelParam:
  7400. // OpenCL v1.0 s6.5:
  7401. // __kernel function arguments declared to be a pointer of a type can point
  7402. // to one of the following address spaces only : __global, __local or
  7403. // __constant.
  7404. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7405. D.setInvalidType();
  7406. return;
  7407. // OpenCL v1.2 s6.9.k:
  7408. // Arguments to kernel functions in a program cannot be declared with the
  7409. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7410. // uintptr_t or a struct and/or union that contain fields declared to be
  7411. // one of these built-in scalar types.
  7412. case InvalidKernelParam:
  7413. // OpenCL v1.2 s6.8 n:
  7414. // A kernel function argument cannot be declared
  7415. // of event_t type.
  7416. // Do not diagnose half type since it is diagnosed as invalid argument
  7417. // type for any function elsewhere.
  7418. if (!PT->isHalfType()) {
  7419. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7420. // Explain what typedefs are involved.
  7421. const TypedefType *Typedef = nullptr;
  7422. while ((Typedef = PT->getAs<TypedefType>())) {
  7423. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7424. // SourceLocation may be invalid for a built-in type.
  7425. if (Loc.isValid())
  7426. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7427. PT = Typedef->desugar();
  7428. }
  7429. }
  7430. D.setInvalidType();
  7431. return;
  7432. case PtrKernelParam:
  7433. case ValidKernelParam:
  7434. ValidTypes.insert(PT.getTypePtr());
  7435. return;
  7436. case RecordKernelParam:
  7437. break;
  7438. }
  7439. // Track nested structs we will inspect
  7440. SmallVector<const Decl *, 4> VisitStack;
  7441. // Track where we are in the nested structs. Items will migrate from
  7442. // VisitStack to HistoryStack as we do the DFS for bad field.
  7443. SmallVector<const FieldDecl *, 4> HistoryStack;
  7444. HistoryStack.push_back(nullptr);
  7445. // At this point we already handled everything except of a RecordType or
  7446. // an ArrayType of a RecordType.
  7447. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7448. const RecordType *RecTy =
  7449. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7450. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7451. VisitStack.push_back(RecTy->getDecl());
  7452. assert(VisitStack.back() && "First decl null?");
  7453. do {
  7454. const Decl *Next = VisitStack.pop_back_val();
  7455. if (!Next) {
  7456. assert(!HistoryStack.empty());
  7457. // Found a marker, we have gone up a level
  7458. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7459. ValidTypes.insert(Hist->getType().getTypePtr());
  7460. continue;
  7461. }
  7462. // Adds everything except the original parameter declaration (which is not a
  7463. // field itself) to the history stack.
  7464. const RecordDecl *RD;
  7465. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7466. HistoryStack.push_back(Field);
  7467. QualType FieldTy = Field->getType();
  7468. // Other field types (known to be valid or invalid) are handled while we
  7469. // walk around RecordDecl::fields().
  7470. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7471. "Unexpected type.");
  7472. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7473. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7474. } else {
  7475. RD = cast<RecordDecl>(Next);
  7476. }
  7477. // Add a null marker so we know when we've gone back up a level
  7478. VisitStack.push_back(nullptr);
  7479. for (const auto *FD : RD->fields()) {
  7480. QualType QT = FD->getType();
  7481. if (ValidTypes.count(QT.getTypePtr()))
  7482. continue;
  7483. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7484. if (ParamType == ValidKernelParam)
  7485. continue;
  7486. if (ParamType == RecordKernelParam) {
  7487. VisitStack.push_back(FD);
  7488. continue;
  7489. }
  7490. // OpenCL v1.2 s6.9.p:
  7491. // Arguments to kernel functions that are declared to be a struct or union
  7492. // do not allow OpenCL objects to be passed as elements of the struct or
  7493. // union.
  7494. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7495. ParamType == InvalidAddrSpacePtrKernelParam) {
  7496. S.Diag(Param->getLocation(),
  7497. diag::err_record_with_pointers_kernel_param)
  7498. << PT->isUnionType()
  7499. << PT;
  7500. } else {
  7501. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7502. }
  7503. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7504. << OrigRecDecl->getDeclName();
  7505. // We have an error, now let's go back up through history and show where
  7506. // the offending field came from
  7507. for (ArrayRef<const FieldDecl *>::const_iterator
  7508. I = HistoryStack.begin() + 1,
  7509. E = HistoryStack.end();
  7510. I != E; ++I) {
  7511. const FieldDecl *OuterField = *I;
  7512. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7513. << OuterField->getType();
  7514. }
  7515. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7516. << QT->isPointerType()
  7517. << QT;
  7518. D.setInvalidType();
  7519. return;
  7520. }
  7521. } while (!VisitStack.empty());
  7522. }
  7523. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7524. /// elaborated type specifier in the specified context, and lookup finds
  7525. /// nothing.
  7526. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7527. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7528. DC = DC->getParent();
  7529. return DC;
  7530. }
  7531. /// Find the Scope in which a tag is implicitly declared if we see an
  7532. /// elaborated type specifier in the specified context, and lookup finds
  7533. /// nothing.
  7534. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7535. while (S->isClassScope() ||
  7536. (LangOpts.CPlusPlus &&
  7537. S->isFunctionPrototypeScope()) ||
  7538. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7539. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7540. S = S->getParent();
  7541. return S;
  7542. }
  7543. NamedDecl*
  7544. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7545. TypeSourceInfo *TInfo, LookupResult &Previous,
  7546. MultiTemplateParamsArg TemplateParamLists,
  7547. bool &AddToScope) {
  7548. QualType R = TInfo->getType();
  7549. assert(R->isFunctionType());
  7550. // TODO: consider using NameInfo for diagnostic.
  7551. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7552. DeclarationName Name = NameInfo.getName();
  7553. StorageClass SC = getFunctionStorageClass(*this, D);
  7554. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7555. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7556. diag::err_invalid_thread)
  7557. << DeclSpec::getSpecifierName(TSCS);
  7558. if (D.isFirstDeclarationOfMember())
  7559. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7560. D.getIdentifierLoc());
  7561. bool isFriend = false;
  7562. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7563. bool isMemberSpecialization = false;
  7564. bool isFunctionTemplateSpecialization = false;
  7565. bool isDependentClassScopeExplicitSpecialization = false;
  7566. bool HasExplicitTemplateArgs = false;
  7567. TemplateArgumentListInfo TemplateArgs;
  7568. bool isVirtualOkay = false;
  7569. DeclContext *OriginalDC = DC;
  7570. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7571. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7572. isVirtualOkay);
  7573. if (!NewFD) return nullptr;
  7574. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7575. NewFD->setTopLevelDeclInObjCContainer();
  7576. // Set the lexical context. If this is a function-scope declaration, or has a
  7577. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7578. // context will be different from the semantic context.
  7579. NewFD->setLexicalDeclContext(CurContext);
  7580. if (IsLocalExternDecl)
  7581. NewFD->setLocalExternDecl();
  7582. if (getLangOpts().CPlusPlus) {
  7583. bool isInline = D.getDeclSpec().isInlineSpecified();
  7584. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7585. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7586. isFriend = D.getDeclSpec().isFriendSpecified();
  7587. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7588. // C++ [class.friend]p5
  7589. // A function can be defined in a friend declaration of a
  7590. // class . . . . Such a function is implicitly inline.
  7591. NewFD->setImplicitlyInline();
  7592. }
  7593. // If this is a method defined in an __interface, and is not a constructor
  7594. // or an overloaded operator, then set the pure flag (isVirtual will already
  7595. // return true).
  7596. if (const CXXRecordDecl *Parent =
  7597. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7598. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7599. NewFD->setPure(true);
  7600. // C++ [class.union]p2
  7601. // A union can have member functions, but not virtual functions.
  7602. if (isVirtual && Parent->isUnion())
  7603. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7604. }
  7605. SetNestedNameSpecifier(*this, NewFD, D);
  7606. isMemberSpecialization = false;
  7607. isFunctionTemplateSpecialization = false;
  7608. if (D.isInvalidType())
  7609. NewFD->setInvalidDecl();
  7610. // Match up the template parameter lists with the scope specifier, then
  7611. // determine whether we have a template or a template specialization.
  7612. bool Invalid = false;
  7613. if (TemplateParameterList *TemplateParams =
  7614. MatchTemplateParametersToScopeSpecifier(
  7615. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7616. D.getCXXScopeSpec(),
  7617. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7618. ? D.getName().TemplateId
  7619. : nullptr,
  7620. TemplateParamLists, isFriend, isMemberSpecialization,
  7621. Invalid)) {
  7622. if (TemplateParams->size() > 0) {
  7623. // This is a function template
  7624. // Check that we can declare a template here.
  7625. if (CheckTemplateDeclScope(S, TemplateParams))
  7626. NewFD->setInvalidDecl();
  7627. // A destructor cannot be a template.
  7628. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7629. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7630. NewFD->setInvalidDecl();
  7631. }
  7632. // If we're adding a template to a dependent context, we may need to
  7633. // rebuilding some of the types used within the template parameter list,
  7634. // now that we know what the current instantiation is.
  7635. if (DC->isDependentContext()) {
  7636. ContextRAII SavedContext(*this, DC);
  7637. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7638. Invalid = true;
  7639. }
  7640. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7641. NewFD->getLocation(),
  7642. Name, TemplateParams,
  7643. NewFD);
  7644. FunctionTemplate->setLexicalDeclContext(CurContext);
  7645. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7646. // For source fidelity, store the other template param lists.
  7647. if (TemplateParamLists.size() > 1) {
  7648. NewFD->setTemplateParameterListsInfo(Context,
  7649. TemplateParamLists.drop_back(1));
  7650. }
  7651. } else {
  7652. // This is a function template specialization.
  7653. isFunctionTemplateSpecialization = true;
  7654. // For source fidelity, store all the template param lists.
  7655. if (TemplateParamLists.size() > 0)
  7656. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7657. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7658. if (isFriend) {
  7659. // We want to remove the "template<>", found here.
  7660. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7661. // If we remove the template<> and the name is not a
  7662. // template-id, we're actually silently creating a problem:
  7663. // the friend declaration will refer to an untemplated decl,
  7664. // and clearly the user wants a template specialization. So
  7665. // we need to insert '<>' after the name.
  7666. SourceLocation InsertLoc;
  7667. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7668. InsertLoc = D.getName().getSourceRange().getEnd();
  7669. InsertLoc = getLocForEndOfToken(InsertLoc);
  7670. }
  7671. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7672. << Name << RemoveRange
  7673. << FixItHint::CreateRemoval(RemoveRange)
  7674. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7675. }
  7676. }
  7677. } else {
  7678. // All template param lists were matched against the scope specifier:
  7679. // this is NOT (an explicit specialization of) a template.
  7680. if (TemplateParamLists.size() > 0)
  7681. // For source fidelity, store all the template param lists.
  7682. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7683. }
  7684. if (Invalid) {
  7685. NewFD->setInvalidDecl();
  7686. if (FunctionTemplate)
  7687. FunctionTemplate->setInvalidDecl();
  7688. }
  7689. // C++ [dcl.fct.spec]p5:
  7690. // The virtual specifier shall only be used in declarations of
  7691. // nonstatic class member functions that appear within a
  7692. // member-specification of a class declaration; see 10.3.
  7693. //
  7694. if (isVirtual && !NewFD->isInvalidDecl()) {
  7695. if (!isVirtualOkay) {
  7696. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7697. diag::err_virtual_non_function);
  7698. } else if (!CurContext->isRecord()) {
  7699. // 'virtual' was specified outside of the class.
  7700. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7701. diag::err_virtual_out_of_class)
  7702. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7703. } else if (NewFD->getDescribedFunctionTemplate()) {
  7704. // C++ [temp.mem]p3:
  7705. // A member function template shall not be virtual.
  7706. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7707. diag::err_virtual_member_function_template)
  7708. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7709. } else {
  7710. // Okay: Add virtual to the method.
  7711. NewFD->setVirtualAsWritten(true);
  7712. }
  7713. if (getLangOpts().CPlusPlus14 &&
  7714. NewFD->getReturnType()->isUndeducedType())
  7715. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7716. }
  7717. if (getLangOpts().CPlusPlus14 &&
  7718. (NewFD->isDependentContext() ||
  7719. (isFriend && CurContext->isDependentContext())) &&
  7720. NewFD->getReturnType()->isUndeducedType()) {
  7721. // If the function template is referenced directly (for instance, as a
  7722. // member of the current instantiation), pretend it has a dependent type.
  7723. // This is not really justified by the standard, but is the only sane
  7724. // thing to do.
  7725. // FIXME: For a friend function, we have not marked the function as being
  7726. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7727. const FunctionProtoType *FPT =
  7728. NewFD->getType()->castAs<FunctionProtoType>();
  7729. QualType Result =
  7730. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7731. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7732. FPT->getExtProtoInfo()));
  7733. }
  7734. // C++ [dcl.fct.spec]p3:
  7735. // The inline specifier shall not appear on a block scope function
  7736. // declaration.
  7737. if (isInline && !NewFD->isInvalidDecl()) {
  7738. if (CurContext->isFunctionOrMethod()) {
  7739. // 'inline' is not allowed on block scope function declaration.
  7740. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7741. diag::err_inline_declaration_block_scope) << Name
  7742. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7743. }
  7744. }
  7745. // C++ [dcl.fct.spec]p6:
  7746. // The explicit specifier shall be used only in the declaration of a
  7747. // constructor or conversion function within its class definition;
  7748. // see 12.3.1 and 12.3.2.
  7749. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7750. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7751. if (!CurContext->isRecord()) {
  7752. // 'explicit' was specified outside of the class.
  7753. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7754. diag::err_explicit_out_of_class)
  7755. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7756. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7757. !isa<CXXConversionDecl>(NewFD)) {
  7758. // 'explicit' was specified on a function that wasn't a constructor
  7759. // or conversion function.
  7760. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7761. diag::err_explicit_non_ctor_or_conv_function)
  7762. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7763. }
  7764. }
  7765. if (ConstexprSpecKind ConstexprKind =
  7766. D.getDeclSpec().getConstexprSpecifier()) {
  7767. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7768. // are implicitly inline.
  7769. NewFD->setImplicitlyInline();
  7770. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7771. // be either constructors or to return a literal type. Therefore,
  7772. // destructors cannot be declared constexpr.
  7773. if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
  7774. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  7775. << ConstexprKind;
  7776. }
  7777. }
  7778. // If __module_private__ was specified, mark the function accordingly.
  7779. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7780. if (isFunctionTemplateSpecialization) {
  7781. SourceLocation ModulePrivateLoc
  7782. = D.getDeclSpec().getModulePrivateSpecLoc();
  7783. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7784. << 0
  7785. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7786. } else {
  7787. NewFD->setModulePrivate();
  7788. if (FunctionTemplate)
  7789. FunctionTemplate->setModulePrivate();
  7790. }
  7791. }
  7792. if (isFriend) {
  7793. if (FunctionTemplate) {
  7794. FunctionTemplate->setObjectOfFriendDecl();
  7795. FunctionTemplate->setAccess(AS_public);
  7796. }
  7797. NewFD->setObjectOfFriendDecl();
  7798. NewFD->setAccess(AS_public);
  7799. }
  7800. // If a function is defined as defaulted or deleted, mark it as such now.
  7801. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7802. // definition kind to FDK_Definition.
  7803. switch (D.getFunctionDefinitionKind()) {
  7804. case FDK_Declaration:
  7805. case FDK_Definition:
  7806. break;
  7807. case FDK_Defaulted:
  7808. NewFD->setDefaulted();
  7809. break;
  7810. case FDK_Deleted:
  7811. NewFD->setDeletedAsWritten();
  7812. break;
  7813. }
  7814. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7815. D.isFunctionDefinition()) {
  7816. // C++ [class.mfct]p2:
  7817. // A member function may be defined (8.4) in its class definition, in
  7818. // which case it is an inline member function (7.1.2)
  7819. NewFD->setImplicitlyInline();
  7820. }
  7821. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7822. !CurContext->isRecord()) {
  7823. // C++ [class.static]p1:
  7824. // A data or function member of a class may be declared static
  7825. // in a class definition, in which case it is a static member of
  7826. // the class.
  7827. // Complain about the 'static' specifier if it's on an out-of-line
  7828. // member function definition.
  7829. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7830. // member function template declaration and class member template
  7831. // declaration (MSVC versions before 2015), warn about this.
  7832. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7833. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7834. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7835. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7836. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7837. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7838. }
  7839. // C++11 [except.spec]p15:
  7840. // A deallocation function with no exception-specification is treated
  7841. // as if it were specified with noexcept(true).
  7842. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7843. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7844. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7845. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7846. NewFD->setType(Context.getFunctionType(
  7847. FPT->getReturnType(), FPT->getParamTypes(),
  7848. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7849. }
  7850. // Filter out previous declarations that don't match the scope.
  7851. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7852. D.getCXXScopeSpec().isNotEmpty() ||
  7853. isMemberSpecialization ||
  7854. isFunctionTemplateSpecialization);
  7855. // Handle GNU asm-label extension (encoded as an attribute).
  7856. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7857. // The parser guarantees this is a string.
  7858. StringLiteral *SE = cast<StringLiteral>(E);
  7859. NewFD->addAttr(::new (Context)
  7860. AsmLabelAttr(Context, SE->getStrTokenLoc(0),
  7861. SE->getString(), /*IsLiteralLabel=*/true));
  7862. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7863. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7864. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7865. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7866. if (isDeclExternC(NewFD)) {
  7867. NewFD->addAttr(I->second);
  7868. ExtnameUndeclaredIdentifiers.erase(I);
  7869. } else
  7870. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7871. << /*Variable*/0 << NewFD;
  7872. }
  7873. }
  7874. // Copy the parameter declarations from the declarator D to the function
  7875. // declaration NewFD, if they are available. First scavenge them into Params.
  7876. SmallVector<ParmVarDecl*, 16> Params;
  7877. unsigned FTIIdx;
  7878. if (D.isFunctionDeclarator(FTIIdx)) {
  7879. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7880. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7881. // function that takes no arguments, not a function that takes a
  7882. // single void argument.
  7883. // We let through "const void" here because Sema::GetTypeForDeclarator
  7884. // already checks for that case.
  7885. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7886. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7887. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7888. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7889. Param->setDeclContext(NewFD);
  7890. Params.push_back(Param);
  7891. if (Param->isInvalidDecl())
  7892. NewFD->setInvalidDecl();
  7893. }
  7894. }
  7895. if (!getLangOpts().CPlusPlus) {
  7896. // In C, find all the tag declarations from the prototype and move them
  7897. // into the function DeclContext. Remove them from the surrounding tag
  7898. // injection context of the function, which is typically but not always
  7899. // the TU.
  7900. DeclContext *PrototypeTagContext =
  7901. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7902. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7903. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7904. // We don't want to reparent enumerators. Look at their parent enum
  7905. // instead.
  7906. if (!TD) {
  7907. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7908. TD = cast<EnumDecl>(ECD->getDeclContext());
  7909. }
  7910. if (!TD)
  7911. continue;
  7912. DeclContext *TagDC = TD->getLexicalDeclContext();
  7913. if (!TagDC->containsDecl(TD))
  7914. continue;
  7915. TagDC->removeDecl(TD);
  7916. TD->setDeclContext(NewFD);
  7917. NewFD->addDecl(TD);
  7918. // Preserve the lexical DeclContext if it is not the surrounding tag
  7919. // injection context of the FD. In this example, the semantic context of
  7920. // E will be f and the lexical context will be S, while both the
  7921. // semantic and lexical contexts of S will be f:
  7922. // void f(struct S { enum E { a } f; } s);
  7923. if (TagDC != PrototypeTagContext)
  7924. TD->setLexicalDeclContext(TagDC);
  7925. }
  7926. }
  7927. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7928. // When we're declaring a function with a typedef, typeof, etc as in the
  7929. // following example, we'll need to synthesize (unnamed)
  7930. // parameters for use in the declaration.
  7931. //
  7932. // @code
  7933. // typedef void fn(int);
  7934. // fn f;
  7935. // @endcode
  7936. // Synthesize a parameter for each argument type.
  7937. for (const auto &AI : FT->param_types()) {
  7938. ParmVarDecl *Param =
  7939. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7940. Param->setScopeInfo(0, Params.size());
  7941. Params.push_back(Param);
  7942. }
  7943. } else {
  7944. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7945. "Should not need args for typedef of non-prototype fn");
  7946. }
  7947. // Finally, we know we have the right number of parameters, install them.
  7948. NewFD->setParams(Params);
  7949. if (D.getDeclSpec().isNoreturnSpecified())
  7950. NewFD->addAttr(C11NoReturnAttr::Create(Context,
  7951. D.getDeclSpec().getNoreturnSpecLoc(),
  7952. AttributeCommonInfo::AS_Keyword));
  7953. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7954. // because all functions have linkage.
  7955. if (!NewFD->isInvalidDecl() &&
  7956. NewFD->getReturnType()->isVariablyModifiedType()) {
  7957. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7958. NewFD->setInvalidDecl();
  7959. }
  7960. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7961. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7962. !NewFD->hasAttr<SectionAttr>())
  7963. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
  7964. Context, PragmaClangTextSection.SectionName,
  7965. PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
  7966. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7967. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7968. !NewFD->hasAttr<SectionAttr>()) {
  7969. NewFD->addAttr(SectionAttr::CreateImplicit(
  7970. Context, CodeSegStack.CurrentValue->getString(),
  7971. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  7972. SectionAttr::Declspec_allocate));
  7973. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7974. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7975. ASTContext::PSF_Read,
  7976. NewFD))
  7977. NewFD->dropAttr<SectionAttr>();
  7978. }
  7979. // Apply an implicit CodeSegAttr from class declspec or
  7980. // apply an implicit SectionAttr from #pragma code_seg if active.
  7981. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7982. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7983. D.isFunctionDefinition())) {
  7984. NewFD->addAttr(SAttr);
  7985. }
  7986. }
  7987. // Handle attributes.
  7988. ProcessDeclAttributes(S, NewFD, D);
  7989. if (getLangOpts().OpenCL) {
  7990. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7991. // type declaration will generate a compilation error.
  7992. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7993. if (AddressSpace != LangAS::Default) {
  7994. Diag(NewFD->getLocation(),
  7995. diag::err_opencl_return_value_with_address_space);
  7996. NewFD->setInvalidDecl();
  7997. }
  7998. }
  7999. if (!getLangOpts().CPlusPlus) {
  8000. // Perform semantic checking on the function declaration.
  8001. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8002. CheckMain(NewFD, D.getDeclSpec());
  8003. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8004. CheckMSVCRTEntryPoint(NewFD);
  8005. if (!NewFD->isInvalidDecl())
  8006. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8007. isMemberSpecialization));
  8008. else if (!Previous.empty())
  8009. // Recover gracefully from an invalid redeclaration.
  8010. D.setRedeclaration(true);
  8011. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8012. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8013. "previous declaration set still overloaded");
  8014. // Diagnose no-prototype function declarations with calling conventions that
  8015. // don't support variadic calls. Only do this in C and do it after merging
  8016. // possibly prototyped redeclarations.
  8017. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  8018. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  8019. CallingConv CC = FT->getExtInfo().getCC();
  8020. if (!supportsVariadicCall(CC)) {
  8021. // Windows system headers sometimes accidentally use stdcall without
  8022. // (void) parameters, so we relax this to a warning.
  8023. int DiagID =
  8024. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  8025. Diag(NewFD->getLocation(), DiagID)
  8026. << FunctionType::getNameForCallConv(CC);
  8027. }
  8028. }
  8029. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  8030. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  8031. checkNonTrivialCUnion(NewFD->getReturnType(),
  8032. NewFD->getReturnTypeSourceRange().getBegin(),
  8033. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  8034. } else {
  8035. // C++11 [replacement.functions]p3:
  8036. // The program's definitions shall not be specified as inline.
  8037. //
  8038. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  8039. //
  8040. // Suppress the diagnostic if the function is __attribute__((used)), since
  8041. // that forces an external definition to be emitted.
  8042. if (D.getDeclSpec().isInlineSpecified() &&
  8043. NewFD->isReplaceableGlobalAllocationFunction() &&
  8044. !NewFD->hasAttr<UsedAttr>())
  8045. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8046. diag::ext_operator_new_delete_declared_inline)
  8047. << NewFD->getDeclName();
  8048. // If the declarator is a template-id, translate the parser's template
  8049. // argument list into our AST format.
  8050. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8051. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  8052. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  8053. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  8054. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  8055. TemplateId->NumArgs);
  8056. translateTemplateArguments(TemplateArgsPtr,
  8057. TemplateArgs);
  8058. HasExplicitTemplateArgs = true;
  8059. if (NewFD->isInvalidDecl()) {
  8060. HasExplicitTemplateArgs = false;
  8061. } else if (FunctionTemplate) {
  8062. // Function template with explicit template arguments.
  8063. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  8064. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  8065. HasExplicitTemplateArgs = false;
  8066. } else {
  8067. assert((isFunctionTemplateSpecialization ||
  8068. D.getDeclSpec().isFriendSpecified()) &&
  8069. "should have a 'template<>' for this decl");
  8070. // "friend void foo<>(int);" is an implicit specialization decl.
  8071. isFunctionTemplateSpecialization = true;
  8072. }
  8073. } else if (isFriend && isFunctionTemplateSpecialization) {
  8074. // This combination is only possible in a recovery case; the user
  8075. // wrote something like:
  8076. // template <> friend void foo(int);
  8077. // which we're recovering from as if the user had written:
  8078. // friend void foo<>(int);
  8079. // Go ahead and fake up a template id.
  8080. HasExplicitTemplateArgs = true;
  8081. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  8082. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  8083. }
  8084. // We do not add HD attributes to specializations here because
  8085. // they may have different constexpr-ness compared to their
  8086. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  8087. // may end up with different effective targets. Instead, a
  8088. // specialization inherits its target attributes from its template
  8089. // in the CheckFunctionTemplateSpecialization() call below.
  8090. if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
  8091. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  8092. // If it's a friend (and only if it's a friend), it's possible
  8093. // that either the specialized function type or the specialized
  8094. // template is dependent, and therefore matching will fail. In
  8095. // this case, don't check the specialization yet.
  8096. bool InstantiationDependent = false;
  8097. if (isFunctionTemplateSpecialization && isFriend &&
  8098. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  8099. TemplateSpecializationType::anyDependentTemplateArguments(
  8100. TemplateArgs,
  8101. InstantiationDependent))) {
  8102. assert(HasExplicitTemplateArgs &&
  8103. "friend function specialization without template args");
  8104. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  8105. Previous))
  8106. NewFD->setInvalidDecl();
  8107. } else if (isFunctionTemplateSpecialization) {
  8108. if (CurContext->isDependentContext() && CurContext->isRecord()
  8109. && !isFriend) {
  8110. isDependentClassScopeExplicitSpecialization = true;
  8111. } else if (!NewFD->isInvalidDecl() &&
  8112. CheckFunctionTemplateSpecialization(
  8113. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  8114. Previous))
  8115. NewFD->setInvalidDecl();
  8116. // C++ [dcl.stc]p1:
  8117. // A storage-class-specifier shall not be specified in an explicit
  8118. // specialization (14.7.3)
  8119. FunctionTemplateSpecializationInfo *Info =
  8120. NewFD->getTemplateSpecializationInfo();
  8121. if (Info && SC != SC_None) {
  8122. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  8123. Diag(NewFD->getLocation(),
  8124. diag::err_explicit_specialization_inconsistent_storage_class)
  8125. << SC
  8126. << FixItHint::CreateRemoval(
  8127. D.getDeclSpec().getStorageClassSpecLoc());
  8128. else
  8129. Diag(NewFD->getLocation(),
  8130. diag::ext_explicit_specialization_storage_class)
  8131. << FixItHint::CreateRemoval(
  8132. D.getDeclSpec().getStorageClassSpecLoc());
  8133. }
  8134. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8135. if (CheckMemberSpecialization(NewFD, Previous))
  8136. NewFD->setInvalidDecl();
  8137. }
  8138. // Perform semantic checking on the function declaration.
  8139. if (!isDependentClassScopeExplicitSpecialization) {
  8140. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8141. CheckMain(NewFD, D.getDeclSpec());
  8142. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8143. CheckMSVCRTEntryPoint(NewFD);
  8144. if (!NewFD->isInvalidDecl())
  8145. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8146. isMemberSpecialization));
  8147. else if (!Previous.empty())
  8148. // Recover gracefully from an invalid redeclaration.
  8149. D.setRedeclaration(true);
  8150. }
  8151. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8152. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8153. "previous declaration set still overloaded");
  8154. NamedDecl *PrincipalDecl = (FunctionTemplate
  8155. ? cast<NamedDecl>(FunctionTemplate)
  8156. : NewFD);
  8157. if (isFriend && NewFD->getPreviousDecl()) {
  8158. AccessSpecifier Access = AS_public;
  8159. if (!NewFD->isInvalidDecl())
  8160. Access = NewFD->getPreviousDecl()->getAccess();
  8161. NewFD->setAccess(Access);
  8162. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8163. }
  8164. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8165. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8166. PrincipalDecl->setNonMemberOperator();
  8167. // If we have a function template, check the template parameter
  8168. // list. This will check and merge default template arguments.
  8169. if (FunctionTemplate) {
  8170. FunctionTemplateDecl *PrevTemplate =
  8171. FunctionTemplate->getPreviousDecl();
  8172. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8173. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8174. : nullptr,
  8175. D.getDeclSpec().isFriendSpecified()
  8176. ? (D.isFunctionDefinition()
  8177. ? TPC_FriendFunctionTemplateDefinition
  8178. : TPC_FriendFunctionTemplate)
  8179. : (D.getCXXScopeSpec().isSet() &&
  8180. DC && DC->isRecord() &&
  8181. DC->isDependentContext())
  8182. ? TPC_ClassTemplateMember
  8183. : TPC_FunctionTemplate);
  8184. }
  8185. if (NewFD->isInvalidDecl()) {
  8186. // Ignore all the rest of this.
  8187. } else if (!D.isRedeclaration()) {
  8188. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8189. AddToScope };
  8190. // Fake up an access specifier if it's supposed to be a class member.
  8191. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8192. NewFD->setAccess(AS_public);
  8193. // Qualified decls generally require a previous declaration.
  8194. if (D.getCXXScopeSpec().isSet()) {
  8195. // ...with the major exception of templated-scope or
  8196. // dependent-scope friend declarations.
  8197. // TODO: we currently also suppress this check in dependent
  8198. // contexts because (1) the parameter depth will be off when
  8199. // matching friend templates and (2) we might actually be
  8200. // selecting a friend based on a dependent factor. But there
  8201. // are situations where these conditions don't apply and we
  8202. // can actually do this check immediately.
  8203. //
  8204. // Unless the scope is dependent, it's always an error if qualified
  8205. // redeclaration lookup found nothing at all. Diagnose that now;
  8206. // nothing will diagnose that error later.
  8207. if (isFriend &&
  8208. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8209. (!Previous.empty() && CurContext->isDependentContext()))) {
  8210. // ignore these
  8211. } else {
  8212. // The user tried to provide an out-of-line definition for a
  8213. // function that is a member of a class or namespace, but there
  8214. // was no such member function declared (C++ [class.mfct]p2,
  8215. // C++ [namespace.memdef]p2). For example:
  8216. //
  8217. // class X {
  8218. // void f() const;
  8219. // };
  8220. //
  8221. // void X::f() { } // ill-formed
  8222. //
  8223. // Complain about this problem, and attempt to suggest close
  8224. // matches (e.g., those that differ only in cv-qualifiers and
  8225. // whether the parameter types are references).
  8226. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8227. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8228. AddToScope = ExtraArgs.AddToScope;
  8229. return Result;
  8230. }
  8231. }
  8232. // Unqualified local friend declarations are required to resolve
  8233. // to something.
  8234. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8235. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8236. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8237. AddToScope = ExtraArgs.AddToScope;
  8238. return Result;
  8239. }
  8240. }
  8241. } else if (!D.isFunctionDefinition() &&
  8242. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8243. !isFriend && !isFunctionTemplateSpecialization &&
  8244. !isMemberSpecialization) {
  8245. // An out-of-line member function declaration must also be a
  8246. // definition (C++ [class.mfct]p2).
  8247. // Note that this is not the case for explicit specializations of
  8248. // function templates or member functions of class templates, per
  8249. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8250. // extension for compatibility with old SWIG code which likes to
  8251. // generate them.
  8252. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8253. << D.getCXXScopeSpec().getRange();
  8254. }
  8255. }
  8256. ProcessPragmaWeak(S, NewFD);
  8257. checkAttributesAfterMerging(*this, *NewFD);
  8258. AddKnownFunctionAttributes(NewFD);
  8259. if (NewFD->hasAttr<OverloadableAttr>() &&
  8260. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8261. Diag(NewFD->getLocation(),
  8262. diag::err_attribute_overloadable_no_prototype)
  8263. << NewFD;
  8264. // Turn this into a variadic function with no parameters.
  8265. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8266. FunctionProtoType::ExtProtoInfo EPI(
  8267. Context.getDefaultCallingConvention(true, false));
  8268. EPI.Variadic = true;
  8269. EPI.ExtInfo = FT->getExtInfo();
  8270. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8271. NewFD->setType(R);
  8272. }
  8273. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8274. // member, set the visibility of this function.
  8275. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8276. AddPushedVisibilityAttribute(NewFD);
  8277. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8278. // marking the function.
  8279. AddCFAuditedAttribute(NewFD);
  8280. // If this is a function definition, check if we have to apply optnone due to
  8281. // a pragma.
  8282. if(D.isFunctionDefinition())
  8283. AddRangeBasedOptnone(NewFD);
  8284. // If this is the first declaration of an extern C variable, update
  8285. // the map of such variables.
  8286. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8287. isIncompleteDeclExternC(*this, NewFD))
  8288. RegisterLocallyScopedExternCDecl(NewFD, S);
  8289. // Set this FunctionDecl's range up to the right paren.
  8290. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8291. if (D.isRedeclaration() && !Previous.empty()) {
  8292. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8293. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8294. isMemberSpecialization ||
  8295. isFunctionTemplateSpecialization,
  8296. D.isFunctionDefinition());
  8297. }
  8298. if (getLangOpts().CUDA) {
  8299. IdentifierInfo *II = NewFD->getIdentifier();
  8300. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8301. !NewFD->isInvalidDecl() &&
  8302. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8303. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8304. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8305. << getCudaConfigureFuncName();
  8306. Context.setcudaConfigureCallDecl(NewFD);
  8307. }
  8308. // Variadic functions, other than a *declaration* of printf, are not allowed
  8309. // in device-side CUDA code, unless someone passed
  8310. // -fcuda-allow-variadic-functions.
  8311. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8312. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8313. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8314. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8315. !D.isFunctionDefinition())) {
  8316. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8317. }
  8318. }
  8319. MarkUnusedFileScopedDecl(NewFD);
  8320. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8321. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8322. if ((getLangOpts().OpenCLVersion >= 120)
  8323. && (SC == SC_Static)) {
  8324. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8325. D.setInvalidType();
  8326. }
  8327. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8328. if (!NewFD->getReturnType()->isVoidType()) {
  8329. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8330. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8331. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8332. : FixItHint());
  8333. D.setInvalidType();
  8334. }
  8335. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8336. for (auto Param : NewFD->parameters())
  8337. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8338. if (getLangOpts().OpenCLCPlusPlus) {
  8339. if (DC->isRecord()) {
  8340. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8341. D.setInvalidType();
  8342. }
  8343. if (FunctionTemplate) {
  8344. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8345. D.setInvalidType();
  8346. }
  8347. }
  8348. }
  8349. if (getLangOpts().CPlusPlus) {
  8350. if (FunctionTemplate) {
  8351. if (NewFD->isInvalidDecl())
  8352. FunctionTemplate->setInvalidDecl();
  8353. return FunctionTemplate;
  8354. }
  8355. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8356. CompleteMemberSpecialization(NewFD, Previous);
  8357. }
  8358. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8359. QualType PT = Param->getType();
  8360. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8361. // types.
  8362. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8363. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8364. QualType ElemTy = PipeTy->getElementType();
  8365. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8366. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8367. D.setInvalidType();
  8368. }
  8369. }
  8370. }
  8371. }
  8372. // Here we have an function template explicit specialization at class scope.
  8373. // The actual specialization will be postponed to template instatiation
  8374. // time via the ClassScopeFunctionSpecializationDecl node.
  8375. if (isDependentClassScopeExplicitSpecialization) {
  8376. ClassScopeFunctionSpecializationDecl *NewSpec =
  8377. ClassScopeFunctionSpecializationDecl::Create(
  8378. Context, CurContext, NewFD->getLocation(),
  8379. cast<CXXMethodDecl>(NewFD),
  8380. HasExplicitTemplateArgs, TemplateArgs);
  8381. CurContext->addDecl(NewSpec);
  8382. AddToScope = false;
  8383. }
  8384. // Diagnose availability attributes. Availability cannot be used on functions
  8385. // that are run during load/unload.
  8386. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8387. if (NewFD->hasAttr<ConstructorAttr>()) {
  8388. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8389. << 1;
  8390. NewFD->dropAttr<AvailabilityAttr>();
  8391. }
  8392. if (NewFD->hasAttr<DestructorAttr>()) {
  8393. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8394. << 2;
  8395. NewFD->dropAttr<AvailabilityAttr>();
  8396. }
  8397. }
  8398. return NewFD;
  8399. }
  8400. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8401. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8402. /// the class and nested classes -- this includes compiler-generated special
  8403. /// member functions -- are put in the specified segment."
  8404. /// The actual behavior is a little more complicated. The Microsoft compiler
  8405. /// won't check outer classes if there is an active value from #pragma code_seg.
  8406. /// The CodeSeg is always applied from the direct parent but only from outer
  8407. /// classes when the #pragma code_seg stack is empty. See:
  8408. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8409. /// available since MS has removed the page.
  8410. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8411. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8412. if (!Method)
  8413. return nullptr;
  8414. const CXXRecordDecl *Parent = Method->getParent();
  8415. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8416. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8417. NewAttr->setImplicit(true);
  8418. return NewAttr;
  8419. }
  8420. // The Microsoft compiler won't check outer classes for the CodeSeg
  8421. // when the #pragma code_seg stack is active.
  8422. if (S.CodeSegStack.CurrentValue)
  8423. return nullptr;
  8424. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8425. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8426. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8427. NewAttr->setImplicit(true);
  8428. return NewAttr;
  8429. }
  8430. }
  8431. return nullptr;
  8432. }
  8433. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8434. /// containing class. Otherwise it will return implicit SectionAttr if the
  8435. /// function is a definition and there is an active value on CodeSegStack
  8436. /// (from the current #pragma code-seg value).
  8437. ///
  8438. /// \param FD Function being declared.
  8439. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8440. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8441. /// nullptr if no attribute should be added.
  8442. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8443. bool IsDefinition) {
  8444. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8445. return A;
  8446. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8447. CodeSegStack.CurrentValue)
  8448. return SectionAttr::CreateImplicit(
  8449. getASTContext(), CodeSegStack.CurrentValue->getString(),
  8450. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  8451. SectionAttr::Declspec_allocate);
  8452. return nullptr;
  8453. }
  8454. /// Determines if we can perform a correct type check for \p D as a
  8455. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8456. /// best-effort check.
  8457. ///
  8458. /// \param NewD The new declaration.
  8459. /// \param OldD The old declaration.
  8460. /// \param NewT The portion of the type of the new declaration to check.
  8461. /// \param OldT The portion of the type of the old declaration to check.
  8462. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8463. QualType NewT, QualType OldT) {
  8464. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8465. return true;
  8466. // For dependently-typed local extern declarations and friends, we can't
  8467. // perform a correct type check in general until instantiation:
  8468. //
  8469. // int f();
  8470. // template<typename T> void g() { T f(); }
  8471. //
  8472. // (valid if g() is only instantiated with T = int).
  8473. if (NewT->isDependentType() &&
  8474. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8475. return false;
  8476. // Similarly, if the previous declaration was a dependent local extern
  8477. // declaration, we don't really know its type yet.
  8478. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8479. return false;
  8480. return true;
  8481. }
  8482. /// Checks if the new declaration declared in dependent context must be
  8483. /// put in the same redeclaration chain as the specified declaration.
  8484. ///
  8485. /// \param D Declaration that is checked.
  8486. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8487. /// same declaration name.
  8488. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8489. /// belongs to.
  8490. ///
  8491. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8492. if (!D->getLexicalDeclContext()->isDependentContext())
  8493. return true;
  8494. // Don't chain dependent friend function definitions until instantiation, to
  8495. // permit cases like
  8496. //
  8497. // void func();
  8498. // template<typename T> class C1 { friend void func() {} };
  8499. // template<typename T> class C2 { friend void func() {} };
  8500. //
  8501. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8502. //
  8503. // FIXME: This need only apply to function definitions. For now, we proxy
  8504. // this by checking for a file-scope function. We do not want this to apply
  8505. // to friend declarations nominating member functions, because that gets in
  8506. // the way of access checks.
  8507. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8508. return false;
  8509. auto *VD = dyn_cast<ValueDecl>(D);
  8510. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8511. return !VD || !PrevVD ||
  8512. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8513. PrevVD->getType());
  8514. }
  8515. /// Check the target attribute of the function for MultiVersion
  8516. /// validity.
  8517. ///
  8518. /// Returns true if there was an error, false otherwise.
  8519. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8520. const auto *TA = FD->getAttr<TargetAttr>();
  8521. assert(TA && "MultiVersion Candidate requires a target attribute");
  8522. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8523. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8524. enum ErrType { Feature = 0, Architecture = 1 };
  8525. if (!ParseInfo.Architecture.empty() &&
  8526. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8527. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8528. << Architecture << ParseInfo.Architecture;
  8529. return true;
  8530. }
  8531. for (const auto &Feat : ParseInfo.Features) {
  8532. auto BareFeat = StringRef{Feat}.substr(1);
  8533. if (Feat[0] == '-') {
  8534. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8535. << Feature << ("no-" + BareFeat).str();
  8536. return true;
  8537. }
  8538. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8539. !TargetInfo.isValidFeatureName(BareFeat)) {
  8540. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8541. << Feature << BareFeat;
  8542. return true;
  8543. }
  8544. }
  8545. return false;
  8546. }
  8547. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8548. MultiVersionKind MVType) {
  8549. for (const Attr *A : FD->attrs()) {
  8550. switch (A->getKind()) {
  8551. case attr::CPUDispatch:
  8552. case attr::CPUSpecific:
  8553. if (MVType != MultiVersionKind::CPUDispatch &&
  8554. MVType != MultiVersionKind::CPUSpecific)
  8555. return true;
  8556. break;
  8557. case attr::Target:
  8558. if (MVType != MultiVersionKind::Target)
  8559. return true;
  8560. break;
  8561. default:
  8562. return true;
  8563. }
  8564. }
  8565. return false;
  8566. }
  8567. bool Sema::areMultiversionVariantFunctionsCompatible(
  8568. const FunctionDecl *OldFD, const FunctionDecl *NewFD,
  8569. const PartialDiagnostic &NoProtoDiagID,
  8570. const PartialDiagnosticAt &NoteCausedDiagIDAt,
  8571. const PartialDiagnosticAt &NoSupportDiagIDAt,
  8572. const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
  8573. bool ConstexprSupported, bool CLinkageMayDiffer) {
  8574. enum DoesntSupport {
  8575. FuncTemplates = 0,
  8576. VirtFuncs = 1,
  8577. DeducedReturn = 2,
  8578. Constructors = 3,
  8579. Destructors = 4,
  8580. DeletedFuncs = 5,
  8581. DefaultedFuncs = 6,
  8582. ConstexprFuncs = 7,
  8583. ConstevalFuncs = 8,
  8584. };
  8585. enum Different {
  8586. CallingConv = 0,
  8587. ReturnType = 1,
  8588. ConstexprSpec = 2,
  8589. InlineSpec = 3,
  8590. StorageClass = 4,
  8591. Linkage = 5,
  8592. };
  8593. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8594. Diag(OldFD->getLocation(), NoProtoDiagID);
  8595. Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
  8596. return true;
  8597. }
  8598. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8599. return Diag(NewFD->getLocation(), NoProtoDiagID);
  8600. if (!TemplatesSupported &&
  8601. NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8602. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8603. << FuncTemplates;
  8604. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8605. if (NewCXXFD->isVirtual())
  8606. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8607. << VirtFuncs;
  8608. if (isa<CXXConstructorDecl>(NewCXXFD))
  8609. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8610. << Constructors;
  8611. if (isa<CXXDestructorDecl>(NewCXXFD))
  8612. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8613. << Destructors;
  8614. }
  8615. if (NewFD->isDeleted())
  8616. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8617. << DeletedFuncs;
  8618. if (NewFD->isDefaulted())
  8619. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8620. << DefaultedFuncs;
  8621. if (!ConstexprSupported && NewFD->isConstexpr())
  8622. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8623. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  8624. QualType NewQType = Context.getCanonicalType(NewFD->getType());
  8625. const auto *NewType = cast<FunctionType>(NewQType);
  8626. QualType NewReturnType = NewType->getReturnType();
  8627. if (NewReturnType->isUndeducedType())
  8628. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8629. << DeducedReturn;
  8630. // Ensure the return type is identical.
  8631. if (OldFD) {
  8632. QualType OldQType = Context.getCanonicalType(OldFD->getType());
  8633. const auto *OldType = cast<FunctionType>(OldQType);
  8634. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8635. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8636. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8637. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
  8638. QualType OldReturnType = OldType->getReturnType();
  8639. if (OldReturnType != NewReturnType)
  8640. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
  8641. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  8642. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
  8643. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8644. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
  8645. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8646. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
  8647. if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
  8648. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
  8649. if (CheckEquivalentExceptionSpec(
  8650. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8651. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8652. return true;
  8653. }
  8654. return false;
  8655. }
  8656. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8657. const FunctionDecl *NewFD,
  8658. bool CausesMV,
  8659. MultiVersionKind MVType) {
  8660. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8661. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8662. if (OldFD)
  8663. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8664. return true;
  8665. }
  8666. bool IsCPUSpecificCPUDispatchMVType =
  8667. MVType == MultiVersionKind::CPUDispatch ||
  8668. MVType == MultiVersionKind::CPUSpecific;
  8669. // For now, disallow all other attributes. These should be opt-in, but
  8670. // an analysis of all of them is a future FIXME.
  8671. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8672. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8673. << IsCPUSpecificCPUDispatchMVType;
  8674. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8675. return true;
  8676. }
  8677. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8678. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8679. << IsCPUSpecificCPUDispatchMVType;
  8680. // Only allow transition to MultiVersion if it hasn't been used.
  8681. if (OldFD && CausesMV && OldFD->isUsed(false))
  8682. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8683. return S.areMultiversionVariantFunctionsCompatible(
  8684. OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
  8685. PartialDiagnosticAt(NewFD->getLocation(),
  8686. S.PDiag(diag::note_multiversioning_caused_here)),
  8687. PartialDiagnosticAt(NewFD->getLocation(),
  8688. S.PDiag(diag::err_multiversion_doesnt_support)
  8689. << IsCPUSpecificCPUDispatchMVType),
  8690. PartialDiagnosticAt(NewFD->getLocation(),
  8691. S.PDiag(diag::err_multiversion_diff)),
  8692. /*TemplatesSupported=*/false,
  8693. /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
  8694. /*CLinkageMayDiffer=*/false);
  8695. }
  8696. /// Check the validity of a multiversion function declaration that is the
  8697. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8698. ///
  8699. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8700. ///
  8701. /// Returns true if there was an error, false otherwise.
  8702. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8703. MultiVersionKind MVType,
  8704. const TargetAttr *TA) {
  8705. assert(MVType != MultiVersionKind::None &&
  8706. "Function lacks multiversion attribute");
  8707. // Target only causes MV if it is default, otherwise this is a normal
  8708. // function.
  8709. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8710. return false;
  8711. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8712. FD->setInvalidDecl();
  8713. return true;
  8714. }
  8715. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8716. FD->setInvalidDecl();
  8717. return true;
  8718. }
  8719. FD->setIsMultiVersion();
  8720. return false;
  8721. }
  8722. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8723. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8724. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8725. return true;
  8726. }
  8727. return false;
  8728. }
  8729. static bool CheckTargetCausesMultiVersioning(
  8730. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8731. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8732. LookupResult &Previous) {
  8733. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8734. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8735. // Sort order doesn't matter, it just needs to be consistent.
  8736. llvm::sort(NewParsed.Features);
  8737. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8738. // to change, this is a simple redeclaration.
  8739. if (!NewTA->isDefaultVersion() &&
  8740. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8741. return false;
  8742. // Otherwise, this decl causes MultiVersioning.
  8743. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8744. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8745. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8746. NewFD->setInvalidDecl();
  8747. return true;
  8748. }
  8749. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8750. MultiVersionKind::Target)) {
  8751. NewFD->setInvalidDecl();
  8752. return true;
  8753. }
  8754. if (CheckMultiVersionValue(S, NewFD)) {
  8755. NewFD->setInvalidDecl();
  8756. return true;
  8757. }
  8758. // If this is 'default', permit the forward declaration.
  8759. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8760. Redeclaration = true;
  8761. OldDecl = OldFD;
  8762. OldFD->setIsMultiVersion();
  8763. NewFD->setIsMultiVersion();
  8764. return false;
  8765. }
  8766. if (CheckMultiVersionValue(S, OldFD)) {
  8767. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8768. NewFD->setInvalidDecl();
  8769. return true;
  8770. }
  8771. TargetAttr::ParsedTargetAttr OldParsed =
  8772. OldTA->parse(std::less<std::string>());
  8773. if (OldParsed == NewParsed) {
  8774. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8775. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8776. NewFD->setInvalidDecl();
  8777. return true;
  8778. }
  8779. for (const auto *FD : OldFD->redecls()) {
  8780. const auto *CurTA = FD->getAttr<TargetAttr>();
  8781. // We allow forward declarations before ANY multiversioning attributes, but
  8782. // nothing after the fact.
  8783. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8784. (!CurTA || CurTA->isInherited())) {
  8785. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8786. << 0;
  8787. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8788. NewFD->setInvalidDecl();
  8789. return true;
  8790. }
  8791. }
  8792. OldFD->setIsMultiVersion();
  8793. NewFD->setIsMultiVersion();
  8794. Redeclaration = false;
  8795. MergeTypeWithPrevious = false;
  8796. OldDecl = nullptr;
  8797. Previous.clear();
  8798. return false;
  8799. }
  8800. /// Check the validity of a new function declaration being added to an existing
  8801. /// multiversioned declaration collection.
  8802. static bool CheckMultiVersionAdditionalDecl(
  8803. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8804. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8805. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8806. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8807. LookupResult &Previous) {
  8808. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8809. // Disallow mixing of multiversioning types.
  8810. if ((OldMVType == MultiVersionKind::Target &&
  8811. NewMVType != MultiVersionKind::Target) ||
  8812. (NewMVType == MultiVersionKind::Target &&
  8813. OldMVType != MultiVersionKind::Target)) {
  8814. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8815. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8816. NewFD->setInvalidDecl();
  8817. return true;
  8818. }
  8819. TargetAttr::ParsedTargetAttr NewParsed;
  8820. if (NewTA) {
  8821. NewParsed = NewTA->parse();
  8822. llvm::sort(NewParsed.Features);
  8823. }
  8824. bool UseMemberUsingDeclRules =
  8825. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8826. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8827. // previous member of the MultiVersion set.
  8828. for (NamedDecl *ND : Previous) {
  8829. FunctionDecl *CurFD = ND->getAsFunction();
  8830. if (!CurFD)
  8831. continue;
  8832. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8833. continue;
  8834. if (NewMVType == MultiVersionKind::Target) {
  8835. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8836. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8837. NewFD->setIsMultiVersion();
  8838. Redeclaration = true;
  8839. OldDecl = ND;
  8840. return false;
  8841. }
  8842. TargetAttr::ParsedTargetAttr CurParsed =
  8843. CurTA->parse(std::less<std::string>());
  8844. if (CurParsed == NewParsed) {
  8845. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8846. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8847. NewFD->setInvalidDecl();
  8848. return true;
  8849. }
  8850. } else {
  8851. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8852. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8853. // Handle CPUDispatch/CPUSpecific versions.
  8854. // Only 1 CPUDispatch function is allowed, this will make it go through
  8855. // the redeclaration errors.
  8856. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8857. CurFD->hasAttr<CPUDispatchAttr>()) {
  8858. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8859. std::equal(
  8860. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8861. NewCPUDisp->cpus_begin(),
  8862. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8863. return Cur->getName() == New->getName();
  8864. })) {
  8865. NewFD->setIsMultiVersion();
  8866. Redeclaration = true;
  8867. OldDecl = ND;
  8868. return false;
  8869. }
  8870. // If the declarations don't match, this is an error condition.
  8871. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8872. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8873. NewFD->setInvalidDecl();
  8874. return true;
  8875. }
  8876. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8877. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8878. std::equal(
  8879. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8880. NewCPUSpec->cpus_begin(),
  8881. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8882. return Cur->getName() == New->getName();
  8883. })) {
  8884. NewFD->setIsMultiVersion();
  8885. Redeclaration = true;
  8886. OldDecl = ND;
  8887. return false;
  8888. }
  8889. // Only 1 version of CPUSpecific is allowed for each CPU.
  8890. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8891. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8892. if (CurII == NewII) {
  8893. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8894. << NewII;
  8895. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8896. NewFD->setInvalidDecl();
  8897. return true;
  8898. }
  8899. }
  8900. }
  8901. }
  8902. // If the two decls aren't the same MVType, there is no possible error
  8903. // condition.
  8904. }
  8905. }
  8906. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8907. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8908. // handled in the attribute adding step.
  8909. if (NewMVType == MultiVersionKind::Target &&
  8910. CheckMultiVersionValue(S, NewFD)) {
  8911. NewFD->setInvalidDecl();
  8912. return true;
  8913. }
  8914. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8915. !OldFD->isMultiVersion(), NewMVType)) {
  8916. NewFD->setInvalidDecl();
  8917. return true;
  8918. }
  8919. // Permit forward declarations in the case where these two are compatible.
  8920. if (!OldFD->isMultiVersion()) {
  8921. OldFD->setIsMultiVersion();
  8922. NewFD->setIsMultiVersion();
  8923. Redeclaration = true;
  8924. OldDecl = OldFD;
  8925. return false;
  8926. }
  8927. NewFD->setIsMultiVersion();
  8928. Redeclaration = false;
  8929. MergeTypeWithPrevious = false;
  8930. OldDecl = nullptr;
  8931. Previous.clear();
  8932. return false;
  8933. }
  8934. /// Check the validity of a mulitversion function declaration.
  8935. /// Also sets the multiversion'ness' of the function itself.
  8936. ///
  8937. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8938. ///
  8939. /// Returns true if there was an error, false otherwise.
  8940. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8941. bool &Redeclaration, NamedDecl *&OldDecl,
  8942. bool &MergeTypeWithPrevious,
  8943. LookupResult &Previous) {
  8944. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8945. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8946. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8947. // Mixing Multiversioning types is prohibited.
  8948. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8949. (NewCPUDisp && NewCPUSpec)) {
  8950. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8951. NewFD->setInvalidDecl();
  8952. return true;
  8953. }
  8954. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8955. // Main isn't allowed to become a multiversion function, however it IS
  8956. // permitted to have 'main' be marked with the 'target' optimization hint.
  8957. if (NewFD->isMain()) {
  8958. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8959. MVType == MultiVersionKind::CPUDispatch ||
  8960. MVType == MultiVersionKind::CPUSpecific) {
  8961. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8962. NewFD->setInvalidDecl();
  8963. return true;
  8964. }
  8965. return false;
  8966. }
  8967. if (!OldDecl || !OldDecl->getAsFunction() ||
  8968. OldDecl->getDeclContext()->getRedeclContext() !=
  8969. NewFD->getDeclContext()->getRedeclContext()) {
  8970. // If there's no previous declaration, AND this isn't attempting to cause
  8971. // multiversioning, this isn't an error condition.
  8972. if (MVType == MultiVersionKind::None)
  8973. return false;
  8974. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  8975. }
  8976. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8977. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8978. return false;
  8979. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8980. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8981. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8982. NewFD->setInvalidDecl();
  8983. return true;
  8984. }
  8985. // Handle the target potentially causes multiversioning case.
  8986. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8987. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8988. Redeclaration, OldDecl,
  8989. MergeTypeWithPrevious, Previous);
  8990. // At this point, we have a multiversion function decl (in OldFD) AND an
  8991. // appropriate attribute in the current function decl. Resolve that these are
  8992. // still compatible with previous declarations.
  8993. return CheckMultiVersionAdditionalDecl(
  8994. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8995. OldDecl, MergeTypeWithPrevious, Previous);
  8996. }
  8997. /// Perform semantic checking of a new function declaration.
  8998. ///
  8999. /// Performs semantic analysis of the new function declaration
  9000. /// NewFD. This routine performs all semantic checking that does not
  9001. /// require the actual declarator involved in the declaration, and is
  9002. /// used both for the declaration of functions as they are parsed
  9003. /// (called via ActOnDeclarator) and for the declaration of functions
  9004. /// that have been instantiated via C++ template instantiation (called
  9005. /// via InstantiateDecl).
  9006. ///
  9007. /// \param IsMemberSpecialization whether this new function declaration is
  9008. /// a member specialization (that replaces any definition provided by the
  9009. /// previous declaration).
  9010. ///
  9011. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9012. ///
  9013. /// \returns true if the function declaration is a redeclaration.
  9014. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  9015. LookupResult &Previous,
  9016. bool IsMemberSpecialization) {
  9017. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  9018. "Variably modified return types are not handled here");
  9019. // Determine whether the type of this function should be merged with
  9020. // a previous visible declaration. This never happens for functions in C++,
  9021. // and always happens in C if the previous declaration was visible.
  9022. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  9023. !Previous.isShadowed();
  9024. bool Redeclaration = false;
  9025. NamedDecl *OldDecl = nullptr;
  9026. bool MayNeedOverloadableChecks = false;
  9027. // Merge or overload the declaration with an existing declaration of
  9028. // the same name, if appropriate.
  9029. if (!Previous.empty()) {
  9030. // Determine whether NewFD is an overload of PrevDecl or
  9031. // a declaration that requires merging. If it's an overload,
  9032. // there's no more work to do here; we'll just add the new
  9033. // function to the scope.
  9034. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  9035. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  9036. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  9037. Redeclaration = true;
  9038. OldDecl = Candidate;
  9039. }
  9040. } else {
  9041. MayNeedOverloadableChecks = true;
  9042. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  9043. /*NewIsUsingDecl*/ false)) {
  9044. case Ovl_Match:
  9045. Redeclaration = true;
  9046. break;
  9047. case Ovl_NonFunction:
  9048. Redeclaration = true;
  9049. break;
  9050. case Ovl_Overload:
  9051. Redeclaration = false;
  9052. break;
  9053. }
  9054. }
  9055. }
  9056. // Check for a previous extern "C" declaration with this name.
  9057. if (!Redeclaration &&
  9058. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  9059. if (!Previous.empty()) {
  9060. // This is an extern "C" declaration with the same name as a previous
  9061. // declaration, and thus redeclares that entity...
  9062. Redeclaration = true;
  9063. OldDecl = Previous.getFoundDecl();
  9064. MergeTypeWithPrevious = false;
  9065. // ... except in the presence of __attribute__((overloadable)).
  9066. if (OldDecl->hasAttr<OverloadableAttr>() ||
  9067. NewFD->hasAttr<OverloadableAttr>()) {
  9068. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  9069. MayNeedOverloadableChecks = true;
  9070. Redeclaration = false;
  9071. OldDecl = nullptr;
  9072. }
  9073. }
  9074. }
  9075. }
  9076. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  9077. MergeTypeWithPrevious, Previous))
  9078. return Redeclaration;
  9079. // C++11 [dcl.constexpr]p8:
  9080. // A constexpr specifier for a non-static member function that is not
  9081. // a constructor declares that member function to be const.
  9082. //
  9083. // This needs to be delayed until we know whether this is an out-of-line
  9084. // definition of a static member function.
  9085. //
  9086. // This rule is not present in C++1y, so we produce a backwards
  9087. // compatibility warning whenever it happens in C++11.
  9088. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  9089. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  9090. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  9091. !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
  9092. CXXMethodDecl *OldMD = nullptr;
  9093. if (OldDecl)
  9094. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  9095. if (!OldMD || !OldMD->isStatic()) {
  9096. const FunctionProtoType *FPT =
  9097. MD->getType()->castAs<FunctionProtoType>();
  9098. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9099. EPI.TypeQuals.addConst();
  9100. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  9101. FPT->getParamTypes(), EPI));
  9102. // Warn that we did this, if we're not performing template instantiation.
  9103. // In that case, we'll have warned already when the template was defined.
  9104. if (!inTemplateInstantiation()) {
  9105. SourceLocation AddConstLoc;
  9106. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  9107. .IgnoreParens().getAs<FunctionTypeLoc>())
  9108. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  9109. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  9110. << FixItHint::CreateInsertion(AddConstLoc, " const");
  9111. }
  9112. }
  9113. }
  9114. if (Redeclaration) {
  9115. // NewFD and OldDecl represent declarations that need to be
  9116. // merged.
  9117. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  9118. NewFD->setInvalidDecl();
  9119. return Redeclaration;
  9120. }
  9121. Previous.clear();
  9122. Previous.addDecl(OldDecl);
  9123. if (FunctionTemplateDecl *OldTemplateDecl =
  9124. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  9125. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  9126. FunctionTemplateDecl *NewTemplateDecl
  9127. = NewFD->getDescribedFunctionTemplate();
  9128. assert(NewTemplateDecl && "Template/non-template mismatch");
  9129. // The call to MergeFunctionDecl above may have created some state in
  9130. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  9131. // can add it as a redeclaration.
  9132. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  9133. NewFD->setPreviousDeclaration(OldFD);
  9134. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9135. if (NewFD->isCXXClassMember()) {
  9136. NewFD->setAccess(OldTemplateDecl->getAccess());
  9137. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9138. }
  9139. // If this is an explicit specialization of a member that is a function
  9140. // template, mark it as a member specialization.
  9141. if (IsMemberSpecialization &&
  9142. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9143. NewTemplateDecl->setMemberSpecialization();
  9144. assert(OldTemplateDecl->isMemberSpecialization());
  9145. // Explicit specializations of a member template do not inherit deleted
  9146. // status from the parent member template that they are specializing.
  9147. if (OldFD->isDeleted()) {
  9148. // FIXME: This assert will not hold in the presence of modules.
  9149. assert(OldFD->getCanonicalDecl() == OldFD);
  9150. // FIXME: We need an update record for this AST mutation.
  9151. OldFD->setDeletedAsWritten(false);
  9152. }
  9153. }
  9154. } else {
  9155. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9156. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9157. // This needs to happen first so that 'inline' propagates.
  9158. NewFD->setPreviousDeclaration(OldFD);
  9159. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9160. if (NewFD->isCXXClassMember())
  9161. NewFD->setAccess(OldFD->getAccess());
  9162. }
  9163. }
  9164. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9165. !NewFD->getAttr<OverloadableAttr>()) {
  9166. assert((Previous.empty() ||
  9167. llvm::any_of(Previous,
  9168. [](const NamedDecl *ND) {
  9169. return ND->hasAttr<OverloadableAttr>();
  9170. })) &&
  9171. "Non-redecls shouldn't happen without overloadable present");
  9172. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9173. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9174. return FD && !FD->hasAttr<OverloadableAttr>();
  9175. });
  9176. if (OtherUnmarkedIter != Previous.end()) {
  9177. Diag(NewFD->getLocation(),
  9178. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9179. Diag((*OtherUnmarkedIter)->getLocation(),
  9180. diag::note_attribute_overloadable_prev_overload)
  9181. << false;
  9182. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9183. }
  9184. }
  9185. // Semantic checking for this function declaration (in isolation).
  9186. if (getLangOpts().CPlusPlus) {
  9187. // C++-specific checks.
  9188. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9189. CheckConstructor(Constructor);
  9190. } else if (CXXDestructorDecl *Destructor =
  9191. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9192. CXXRecordDecl *Record = Destructor->getParent();
  9193. QualType ClassType = Context.getTypeDeclType(Record);
  9194. // FIXME: Shouldn't we be able to perform this check even when the class
  9195. // type is dependent? Both gcc and edg can handle that.
  9196. if (!ClassType->isDependentType()) {
  9197. DeclarationName Name
  9198. = Context.DeclarationNames.getCXXDestructorName(
  9199. Context.getCanonicalType(ClassType));
  9200. if (NewFD->getDeclName() != Name) {
  9201. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9202. NewFD->setInvalidDecl();
  9203. return Redeclaration;
  9204. }
  9205. }
  9206. } else if (CXXConversionDecl *Conversion
  9207. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9208. ActOnConversionDeclarator(Conversion);
  9209. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9210. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9211. CheckDeductionGuideTemplate(TD);
  9212. // A deduction guide is not on the list of entities that can be
  9213. // explicitly specialized.
  9214. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9215. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9216. << /*explicit specialization*/ 1;
  9217. }
  9218. // Find any virtual functions that this function overrides.
  9219. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9220. if (!Method->isFunctionTemplateSpecialization() &&
  9221. !Method->getDescribedFunctionTemplate() &&
  9222. Method->isCanonicalDecl()) {
  9223. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9224. // If the function was marked as "static", we have a problem.
  9225. if (NewFD->getStorageClass() == SC_Static) {
  9226. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9227. }
  9228. }
  9229. }
  9230. if (Method->isStatic())
  9231. checkThisInStaticMemberFunctionType(Method);
  9232. }
  9233. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9234. if (NewFD->isOverloadedOperator() &&
  9235. CheckOverloadedOperatorDeclaration(NewFD)) {
  9236. NewFD->setInvalidDecl();
  9237. return Redeclaration;
  9238. }
  9239. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9240. if (NewFD->getLiteralIdentifier() &&
  9241. CheckLiteralOperatorDeclaration(NewFD)) {
  9242. NewFD->setInvalidDecl();
  9243. return Redeclaration;
  9244. }
  9245. // In C++, check default arguments now that we have merged decls. Unless
  9246. // the lexical context is the class, because in this case this is done
  9247. // during delayed parsing anyway.
  9248. if (!CurContext->isRecord())
  9249. CheckCXXDefaultArguments(NewFD);
  9250. // If this function declares a builtin function, check the type of this
  9251. // declaration against the expected type for the builtin.
  9252. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9253. ASTContext::GetBuiltinTypeError Error;
  9254. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9255. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9256. // If the type of the builtin differs only in its exception
  9257. // specification, that's OK.
  9258. // FIXME: If the types do differ in this way, it would be better to
  9259. // retain the 'noexcept' form of the type.
  9260. if (!T.isNull() &&
  9261. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9262. NewFD->getType()))
  9263. // The type of this function differs from the type of the builtin,
  9264. // so forget about the builtin entirely.
  9265. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9266. }
  9267. // If this function is declared as being extern "C", then check to see if
  9268. // the function returns a UDT (class, struct, or union type) that is not C
  9269. // compatible, and if it does, warn the user.
  9270. // But, issue any diagnostic on the first declaration only.
  9271. if (Previous.empty() && NewFD->isExternC()) {
  9272. QualType R = NewFD->getReturnType();
  9273. if (R->isIncompleteType() && !R->isVoidType())
  9274. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9275. << NewFD << R;
  9276. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9277. !R->isObjCObjectPointerType())
  9278. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9279. }
  9280. // C++1z [dcl.fct]p6:
  9281. // [...] whether the function has a non-throwing exception-specification
  9282. // [is] part of the function type
  9283. //
  9284. // This results in an ABI break between C++14 and C++17 for functions whose
  9285. // declared type includes an exception-specification in a parameter or
  9286. // return type. (Exception specifications on the function itself are OK in
  9287. // most cases, and exception specifications are not permitted in most other
  9288. // contexts where they could make it into a mangling.)
  9289. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9290. auto HasNoexcept = [&](QualType T) -> bool {
  9291. // Strip off declarator chunks that could be between us and a function
  9292. // type. We don't need to look far, exception specifications are very
  9293. // restricted prior to C++17.
  9294. if (auto *RT = T->getAs<ReferenceType>())
  9295. T = RT->getPointeeType();
  9296. else if (T->isAnyPointerType())
  9297. T = T->getPointeeType();
  9298. else if (auto *MPT = T->getAs<MemberPointerType>())
  9299. T = MPT->getPointeeType();
  9300. if (auto *FPT = T->getAs<FunctionProtoType>())
  9301. if (FPT->isNothrow())
  9302. return true;
  9303. return false;
  9304. };
  9305. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9306. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9307. for (QualType T : FPT->param_types())
  9308. AnyNoexcept |= HasNoexcept(T);
  9309. if (AnyNoexcept)
  9310. Diag(NewFD->getLocation(),
  9311. diag::warn_cxx17_compat_exception_spec_in_signature)
  9312. << NewFD;
  9313. }
  9314. if (!Redeclaration && LangOpts.CUDA)
  9315. checkCUDATargetOverload(NewFD, Previous);
  9316. }
  9317. return Redeclaration;
  9318. }
  9319. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9320. // C++11 [basic.start.main]p3:
  9321. // A program that [...] declares main to be inline, static or
  9322. // constexpr is ill-formed.
  9323. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9324. // appear in a declaration of main.
  9325. // static main is not an error under C99, but we should warn about it.
  9326. // We accept _Noreturn main as an extension.
  9327. if (FD->getStorageClass() == SC_Static)
  9328. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9329. ? diag::err_static_main : diag::warn_static_main)
  9330. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9331. if (FD->isInlineSpecified())
  9332. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9333. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9334. if (DS.isNoreturnSpecified()) {
  9335. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9336. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9337. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9338. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9339. << FixItHint::CreateRemoval(NoreturnRange);
  9340. }
  9341. if (FD->isConstexpr()) {
  9342. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9343. << FD->isConsteval()
  9344. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9345. FD->setConstexprKind(CSK_unspecified);
  9346. }
  9347. if (getLangOpts().OpenCL) {
  9348. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9349. << FD->hasAttr<OpenCLKernelAttr>();
  9350. FD->setInvalidDecl();
  9351. return;
  9352. }
  9353. QualType T = FD->getType();
  9354. assert(T->isFunctionType() && "function decl is not of function type");
  9355. const FunctionType* FT = T->castAs<FunctionType>();
  9356. // Set default calling convention for main()
  9357. if (FT->getCallConv() != CC_C) {
  9358. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9359. FD->setType(QualType(FT, 0));
  9360. T = Context.getCanonicalType(FD->getType());
  9361. }
  9362. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9363. // In C with GNU extensions we allow main() to have non-integer return
  9364. // type, but we should warn about the extension, and we disable the
  9365. // implicit-return-zero rule.
  9366. // GCC in C mode accepts qualified 'int'.
  9367. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9368. FD->setHasImplicitReturnZero(true);
  9369. else {
  9370. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9371. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9372. if (RTRange.isValid())
  9373. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9374. << FixItHint::CreateReplacement(RTRange, "int");
  9375. }
  9376. } else {
  9377. // In C and C++, main magically returns 0 if you fall off the end;
  9378. // set the flag which tells us that.
  9379. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9380. // All the standards say that main() should return 'int'.
  9381. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9382. FD->setHasImplicitReturnZero(true);
  9383. else {
  9384. // Otherwise, this is just a flat-out error.
  9385. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9386. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9387. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9388. : FixItHint());
  9389. FD->setInvalidDecl(true);
  9390. }
  9391. }
  9392. // Treat protoless main() as nullary.
  9393. if (isa<FunctionNoProtoType>(FT)) return;
  9394. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9395. unsigned nparams = FTP->getNumParams();
  9396. assert(FD->getNumParams() == nparams);
  9397. bool HasExtraParameters = (nparams > 3);
  9398. if (FTP->isVariadic()) {
  9399. Diag(FD->getLocation(), diag::ext_variadic_main);
  9400. // FIXME: if we had information about the location of the ellipsis, we
  9401. // could add a FixIt hint to remove it as a parameter.
  9402. }
  9403. // Darwin passes an undocumented fourth argument of type char**. If
  9404. // other platforms start sprouting these, the logic below will start
  9405. // getting shifty.
  9406. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9407. HasExtraParameters = false;
  9408. if (HasExtraParameters) {
  9409. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9410. FD->setInvalidDecl(true);
  9411. nparams = 3;
  9412. }
  9413. // FIXME: a lot of the following diagnostics would be improved
  9414. // if we had some location information about types.
  9415. QualType CharPP =
  9416. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9417. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9418. for (unsigned i = 0; i < nparams; ++i) {
  9419. QualType AT = FTP->getParamType(i);
  9420. bool mismatch = true;
  9421. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9422. mismatch = false;
  9423. else if (Expected[i] == CharPP) {
  9424. // As an extension, the following forms are okay:
  9425. // char const **
  9426. // char const * const *
  9427. // char * const *
  9428. QualifierCollector qs;
  9429. const PointerType* PT;
  9430. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9431. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9432. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9433. Context.CharTy)) {
  9434. qs.removeConst();
  9435. mismatch = !qs.empty();
  9436. }
  9437. }
  9438. if (mismatch) {
  9439. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9440. // TODO: suggest replacing given type with expected type
  9441. FD->setInvalidDecl(true);
  9442. }
  9443. }
  9444. if (nparams == 1 && !FD->isInvalidDecl()) {
  9445. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9446. }
  9447. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9448. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9449. FD->setInvalidDecl();
  9450. }
  9451. }
  9452. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9453. QualType T = FD->getType();
  9454. assert(T->isFunctionType() && "function decl is not of function type");
  9455. const FunctionType *FT = T->castAs<FunctionType>();
  9456. // Set an implicit return of 'zero' if the function can return some integral,
  9457. // enumeration, pointer or nullptr type.
  9458. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9459. FT->getReturnType()->isAnyPointerType() ||
  9460. FT->getReturnType()->isNullPtrType())
  9461. // DllMain is exempt because a return value of zero means it failed.
  9462. if (FD->getName() != "DllMain")
  9463. FD->setHasImplicitReturnZero(true);
  9464. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9465. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9466. FD->setInvalidDecl();
  9467. }
  9468. }
  9469. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9470. // FIXME: Need strict checking. In C89, we need to check for
  9471. // any assignment, increment, decrement, function-calls, or
  9472. // commas outside of a sizeof. In C99, it's the same list,
  9473. // except that the aforementioned are allowed in unevaluated
  9474. // expressions. Everything else falls under the
  9475. // "may accept other forms of constant expressions" exception.
  9476. // (We never end up here for C++, so the constant expression
  9477. // rules there don't matter.)
  9478. const Expr *Culprit;
  9479. if (Init->isConstantInitializer(Context, false, &Culprit))
  9480. return false;
  9481. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9482. << Culprit->getSourceRange();
  9483. return true;
  9484. }
  9485. namespace {
  9486. // Visits an initialization expression to see if OrigDecl is evaluated in
  9487. // its own initialization and throws a warning if it does.
  9488. class SelfReferenceChecker
  9489. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9490. Sema &S;
  9491. Decl *OrigDecl;
  9492. bool isRecordType;
  9493. bool isPODType;
  9494. bool isReferenceType;
  9495. bool isInitList;
  9496. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9497. public:
  9498. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9499. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9500. S(S), OrigDecl(OrigDecl) {
  9501. isPODType = false;
  9502. isRecordType = false;
  9503. isReferenceType = false;
  9504. isInitList = false;
  9505. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9506. isPODType = VD->getType().isPODType(S.Context);
  9507. isRecordType = VD->getType()->isRecordType();
  9508. isReferenceType = VD->getType()->isReferenceType();
  9509. }
  9510. }
  9511. // For most expressions, just call the visitor. For initializer lists,
  9512. // track the index of the field being initialized since fields are
  9513. // initialized in order allowing use of previously initialized fields.
  9514. void CheckExpr(Expr *E) {
  9515. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9516. if (!InitList) {
  9517. Visit(E);
  9518. return;
  9519. }
  9520. // Track and increment the index here.
  9521. isInitList = true;
  9522. InitFieldIndex.push_back(0);
  9523. for (auto Child : InitList->children()) {
  9524. CheckExpr(cast<Expr>(Child));
  9525. ++InitFieldIndex.back();
  9526. }
  9527. InitFieldIndex.pop_back();
  9528. }
  9529. // Returns true if MemberExpr is checked and no further checking is needed.
  9530. // Returns false if additional checking is required.
  9531. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9532. llvm::SmallVector<FieldDecl*, 4> Fields;
  9533. Expr *Base = E;
  9534. bool ReferenceField = false;
  9535. // Get the field members used.
  9536. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9537. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9538. if (!FD)
  9539. return false;
  9540. Fields.push_back(FD);
  9541. if (FD->getType()->isReferenceType())
  9542. ReferenceField = true;
  9543. Base = ME->getBase()->IgnoreParenImpCasts();
  9544. }
  9545. // Keep checking only if the base Decl is the same.
  9546. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9547. if (!DRE || DRE->getDecl() != OrigDecl)
  9548. return false;
  9549. // A reference field can be bound to an unininitialized field.
  9550. if (CheckReference && !ReferenceField)
  9551. return true;
  9552. // Convert FieldDecls to their index number.
  9553. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9554. for (const FieldDecl *I : llvm::reverse(Fields))
  9555. UsedFieldIndex.push_back(I->getFieldIndex());
  9556. // See if a warning is needed by checking the first difference in index
  9557. // numbers. If field being used has index less than the field being
  9558. // initialized, then the use is safe.
  9559. for (auto UsedIter = UsedFieldIndex.begin(),
  9560. UsedEnd = UsedFieldIndex.end(),
  9561. OrigIter = InitFieldIndex.begin(),
  9562. OrigEnd = InitFieldIndex.end();
  9563. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9564. if (*UsedIter < *OrigIter)
  9565. return true;
  9566. if (*UsedIter > *OrigIter)
  9567. break;
  9568. }
  9569. // TODO: Add a different warning which will print the field names.
  9570. HandleDeclRefExpr(DRE);
  9571. return true;
  9572. }
  9573. // For most expressions, the cast is directly above the DeclRefExpr.
  9574. // For conditional operators, the cast can be outside the conditional
  9575. // operator if both expressions are DeclRefExpr's.
  9576. void HandleValue(Expr *E) {
  9577. E = E->IgnoreParens();
  9578. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9579. HandleDeclRefExpr(DRE);
  9580. return;
  9581. }
  9582. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9583. Visit(CO->getCond());
  9584. HandleValue(CO->getTrueExpr());
  9585. HandleValue(CO->getFalseExpr());
  9586. return;
  9587. }
  9588. if (BinaryConditionalOperator *BCO =
  9589. dyn_cast<BinaryConditionalOperator>(E)) {
  9590. Visit(BCO->getCond());
  9591. HandleValue(BCO->getFalseExpr());
  9592. return;
  9593. }
  9594. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9595. HandleValue(OVE->getSourceExpr());
  9596. return;
  9597. }
  9598. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9599. if (BO->getOpcode() == BO_Comma) {
  9600. Visit(BO->getLHS());
  9601. HandleValue(BO->getRHS());
  9602. return;
  9603. }
  9604. }
  9605. if (isa<MemberExpr>(E)) {
  9606. if (isInitList) {
  9607. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9608. false /*CheckReference*/))
  9609. return;
  9610. }
  9611. Expr *Base = E->IgnoreParenImpCasts();
  9612. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9613. // Check for static member variables and don't warn on them.
  9614. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9615. return;
  9616. Base = ME->getBase()->IgnoreParenImpCasts();
  9617. }
  9618. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9619. HandleDeclRefExpr(DRE);
  9620. return;
  9621. }
  9622. Visit(E);
  9623. }
  9624. // Reference types not handled in HandleValue are handled here since all
  9625. // uses of references are bad, not just r-value uses.
  9626. void VisitDeclRefExpr(DeclRefExpr *E) {
  9627. if (isReferenceType)
  9628. HandleDeclRefExpr(E);
  9629. }
  9630. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9631. if (E->getCastKind() == CK_LValueToRValue) {
  9632. HandleValue(E->getSubExpr());
  9633. return;
  9634. }
  9635. Inherited::VisitImplicitCastExpr(E);
  9636. }
  9637. void VisitMemberExpr(MemberExpr *E) {
  9638. if (isInitList) {
  9639. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9640. return;
  9641. }
  9642. // Don't warn on arrays since they can be treated as pointers.
  9643. if (E->getType()->canDecayToPointerType()) return;
  9644. // Warn when a non-static method call is followed by non-static member
  9645. // field accesses, which is followed by a DeclRefExpr.
  9646. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9647. bool Warn = (MD && !MD->isStatic());
  9648. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9649. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9650. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9651. Warn = false;
  9652. Base = ME->getBase()->IgnoreParenImpCasts();
  9653. }
  9654. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9655. if (Warn)
  9656. HandleDeclRefExpr(DRE);
  9657. return;
  9658. }
  9659. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9660. // Visit that expression.
  9661. Visit(Base);
  9662. }
  9663. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9664. Expr *Callee = E->getCallee();
  9665. if (isa<UnresolvedLookupExpr>(Callee))
  9666. return Inherited::VisitCXXOperatorCallExpr(E);
  9667. Visit(Callee);
  9668. for (auto Arg: E->arguments())
  9669. HandleValue(Arg->IgnoreParenImpCasts());
  9670. }
  9671. void VisitUnaryOperator(UnaryOperator *E) {
  9672. // For POD record types, addresses of its own members are well-defined.
  9673. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9674. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9675. if (!isPODType)
  9676. HandleValue(E->getSubExpr());
  9677. return;
  9678. }
  9679. if (E->isIncrementDecrementOp()) {
  9680. HandleValue(E->getSubExpr());
  9681. return;
  9682. }
  9683. Inherited::VisitUnaryOperator(E);
  9684. }
  9685. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9686. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9687. if (E->getConstructor()->isCopyConstructor()) {
  9688. Expr *ArgExpr = E->getArg(0);
  9689. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9690. if (ILE->getNumInits() == 1)
  9691. ArgExpr = ILE->getInit(0);
  9692. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9693. if (ICE->getCastKind() == CK_NoOp)
  9694. ArgExpr = ICE->getSubExpr();
  9695. HandleValue(ArgExpr);
  9696. return;
  9697. }
  9698. Inherited::VisitCXXConstructExpr(E);
  9699. }
  9700. void VisitCallExpr(CallExpr *E) {
  9701. // Treat std::move as a use.
  9702. if (E->isCallToStdMove()) {
  9703. HandleValue(E->getArg(0));
  9704. return;
  9705. }
  9706. Inherited::VisitCallExpr(E);
  9707. }
  9708. void VisitBinaryOperator(BinaryOperator *E) {
  9709. if (E->isCompoundAssignmentOp()) {
  9710. HandleValue(E->getLHS());
  9711. Visit(E->getRHS());
  9712. return;
  9713. }
  9714. Inherited::VisitBinaryOperator(E);
  9715. }
  9716. // A custom visitor for BinaryConditionalOperator is needed because the
  9717. // regular visitor would check the condition and true expression separately
  9718. // but both point to the same place giving duplicate diagnostics.
  9719. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9720. Visit(E->getCond());
  9721. Visit(E->getFalseExpr());
  9722. }
  9723. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9724. Decl* ReferenceDecl = DRE->getDecl();
  9725. if (OrigDecl != ReferenceDecl) return;
  9726. unsigned diag;
  9727. if (isReferenceType) {
  9728. diag = diag::warn_uninit_self_reference_in_reference_init;
  9729. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9730. diag = diag::warn_static_self_reference_in_init;
  9731. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9732. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9733. DRE->getDecl()->getType()->isRecordType()) {
  9734. diag = diag::warn_uninit_self_reference_in_init;
  9735. } else {
  9736. // Local variables will be handled by the CFG analysis.
  9737. return;
  9738. }
  9739. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9740. S.PDiag(diag)
  9741. << DRE->getDecl() << OrigDecl->getLocation()
  9742. << DRE->getSourceRange());
  9743. }
  9744. };
  9745. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9746. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9747. bool DirectInit) {
  9748. // Parameters arguments are occassionially constructed with itself,
  9749. // for instance, in recursive functions. Skip them.
  9750. if (isa<ParmVarDecl>(OrigDecl))
  9751. return;
  9752. E = E->IgnoreParens();
  9753. // Skip checking T a = a where T is not a record or reference type.
  9754. // Doing so is a way to silence uninitialized warnings.
  9755. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9756. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9757. if (ICE->getCastKind() == CK_LValueToRValue)
  9758. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9759. if (DRE->getDecl() == OrigDecl)
  9760. return;
  9761. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9762. }
  9763. } // end anonymous namespace
  9764. namespace {
  9765. // Simple wrapper to add the name of a variable or (if no variable is
  9766. // available) a DeclarationName into a diagnostic.
  9767. struct VarDeclOrName {
  9768. VarDecl *VDecl;
  9769. DeclarationName Name;
  9770. friend const Sema::SemaDiagnosticBuilder &
  9771. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9772. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9773. }
  9774. };
  9775. } // end anonymous namespace
  9776. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9777. DeclarationName Name, QualType Type,
  9778. TypeSourceInfo *TSI,
  9779. SourceRange Range, bool DirectInit,
  9780. Expr *Init) {
  9781. bool IsInitCapture = !VDecl;
  9782. assert((!VDecl || !VDecl->isInitCapture()) &&
  9783. "init captures are expected to be deduced prior to initialization");
  9784. VarDeclOrName VN{VDecl, Name};
  9785. DeducedType *Deduced = Type->getContainedDeducedType();
  9786. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9787. // C++11 [dcl.spec.auto]p3
  9788. if (!Init) {
  9789. assert(VDecl && "no init for init capture deduction?");
  9790. // Except for class argument deduction, and then for an initializing
  9791. // declaration only, i.e. no static at class scope or extern.
  9792. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9793. VDecl->hasExternalStorage() ||
  9794. VDecl->isStaticDataMember()) {
  9795. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9796. << VDecl->getDeclName() << Type;
  9797. return QualType();
  9798. }
  9799. }
  9800. ArrayRef<Expr*> DeduceInits;
  9801. if (Init)
  9802. DeduceInits = Init;
  9803. if (DirectInit) {
  9804. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9805. DeduceInits = PL->exprs();
  9806. }
  9807. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9808. assert(VDecl && "non-auto type for init capture deduction?");
  9809. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9810. InitializationKind Kind = InitializationKind::CreateForInit(
  9811. VDecl->getLocation(), DirectInit, Init);
  9812. // FIXME: Initialization should not be taking a mutable list of inits.
  9813. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9814. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9815. InitsCopy);
  9816. }
  9817. if (DirectInit) {
  9818. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9819. DeduceInits = IL->inits();
  9820. }
  9821. // Deduction only works if we have exactly one source expression.
  9822. if (DeduceInits.empty()) {
  9823. // It isn't possible to write this directly, but it is possible to
  9824. // end up in this situation with "auto x(some_pack...);"
  9825. Diag(Init->getBeginLoc(), IsInitCapture
  9826. ? diag::err_init_capture_no_expression
  9827. : diag::err_auto_var_init_no_expression)
  9828. << VN << Type << Range;
  9829. return QualType();
  9830. }
  9831. if (DeduceInits.size() > 1) {
  9832. Diag(DeduceInits[1]->getBeginLoc(),
  9833. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9834. : diag::err_auto_var_init_multiple_expressions)
  9835. << VN << Type << Range;
  9836. return QualType();
  9837. }
  9838. Expr *DeduceInit = DeduceInits[0];
  9839. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9840. Diag(Init->getBeginLoc(), IsInitCapture
  9841. ? diag::err_init_capture_paren_braces
  9842. : diag::err_auto_var_init_paren_braces)
  9843. << isa<InitListExpr>(Init) << VN << Type << Range;
  9844. return QualType();
  9845. }
  9846. // Expressions default to 'id' when we're in a debugger.
  9847. bool DefaultedAnyToId = false;
  9848. if (getLangOpts().DebuggerCastResultToId &&
  9849. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9850. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9851. if (Result.isInvalid()) {
  9852. return QualType();
  9853. }
  9854. Init = Result.get();
  9855. DefaultedAnyToId = true;
  9856. }
  9857. // C++ [dcl.decomp]p1:
  9858. // If the assignment-expression [...] has array type A and no ref-qualifier
  9859. // is present, e has type cv A
  9860. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9861. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9862. DeduceInit->getType()->isConstantArrayType())
  9863. return Context.getQualifiedType(DeduceInit->getType(),
  9864. Type.getQualifiers());
  9865. QualType DeducedType;
  9866. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9867. if (!IsInitCapture)
  9868. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9869. else if (isa<InitListExpr>(Init))
  9870. Diag(Range.getBegin(),
  9871. diag::err_init_capture_deduction_failure_from_init_list)
  9872. << VN
  9873. << (DeduceInit->getType().isNull() ? TSI->getType()
  9874. : DeduceInit->getType())
  9875. << DeduceInit->getSourceRange();
  9876. else
  9877. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9878. << VN << TSI->getType()
  9879. << (DeduceInit->getType().isNull() ? TSI->getType()
  9880. : DeduceInit->getType())
  9881. << DeduceInit->getSourceRange();
  9882. }
  9883. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9884. // 'id' instead of a specific object type prevents most of our usual
  9885. // checks.
  9886. // We only want to warn outside of template instantiations, though:
  9887. // inside a template, the 'id' could have come from a parameter.
  9888. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9889. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9890. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9891. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9892. }
  9893. return DeducedType;
  9894. }
  9895. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9896. Expr *Init) {
  9897. QualType DeducedType = deduceVarTypeFromInitializer(
  9898. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9899. VDecl->getSourceRange(), DirectInit, Init);
  9900. if (DeducedType.isNull()) {
  9901. VDecl->setInvalidDecl();
  9902. return true;
  9903. }
  9904. VDecl->setType(DeducedType);
  9905. assert(VDecl->isLinkageValid());
  9906. // In ARC, infer lifetime.
  9907. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9908. VDecl->setInvalidDecl();
  9909. // If this is a redeclaration, check that the type we just deduced matches
  9910. // the previously declared type.
  9911. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9912. // We never need to merge the type, because we cannot form an incomplete
  9913. // array of auto, nor deduce such a type.
  9914. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9915. }
  9916. // Check the deduced type is valid for a variable declaration.
  9917. CheckVariableDeclarationType(VDecl);
  9918. return VDecl->isInvalidDecl();
  9919. }
  9920. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  9921. SourceLocation Loc) {
  9922. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  9923. Init = CE->getSubExpr();
  9924. QualType InitType = Init->getType();
  9925. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9926. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9927. "shouldn't be called if type doesn't have a non-trivial C struct");
  9928. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  9929. for (auto I : ILE->inits()) {
  9930. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  9931. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  9932. continue;
  9933. SourceLocation SL = I->getExprLoc();
  9934. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  9935. }
  9936. return;
  9937. }
  9938. if (isa<ImplicitValueInitExpr>(Init)) {
  9939. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9940. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  9941. NTCUK_Init);
  9942. } else {
  9943. // Assume all other explicit initializers involving copying some existing
  9944. // object.
  9945. // TODO: ignore any explicit initializers where we can guarantee
  9946. // copy-elision.
  9947. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  9948. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  9949. }
  9950. }
  9951. namespace {
  9952. bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
  9953. // Ignore unavailable fields. A field can be marked as unavailable explicitly
  9954. // in the source code or implicitly by the compiler if it is in a union
  9955. // defined in a system header and has non-trivial ObjC ownership
  9956. // qualifications. We don't want those fields to participate in determining
  9957. // whether the containing union is non-trivial.
  9958. return FD->hasAttr<UnavailableAttr>();
  9959. }
  9960. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  9961. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9962. void> {
  9963. using Super =
  9964. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9965. void>;
  9966. DiagNonTrivalCUnionDefaultInitializeVisitor(
  9967. QualType OrigTy, SourceLocation OrigLoc,
  9968. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  9969. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9970. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  9971. const FieldDecl *FD, bool InNonTrivialUnion) {
  9972. if (const auto *AT = S.Context.getAsArrayType(QT))
  9973. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9974. InNonTrivialUnion);
  9975. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  9976. }
  9977. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9978. bool InNonTrivialUnion) {
  9979. if (InNonTrivialUnion)
  9980. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9981. << 1 << 0 << QT << FD->getName();
  9982. }
  9983. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9984. if (InNonTrivialUnion)
  9985. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9986. << 1 << 0 << QT << FD->getName();
  9987. }
  9988. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9989. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9990. if (RD->isUnion()) {
  9991. if (OrigLoc.isValid()) {
  9992. bool IsUnion = false;
  9993. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9994. IsUnion = OrigRD->isUnion();
  9995. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9996. << 0 << OrigTy << IsUnion << UseContext;
  9997. // Reset OrigLoc so that this diagnostic is emitted only once.
  9998. OrigLoc = SourceLocation();
  9999. }
  10000. InNonTrivialUnion = true;
  10001. }
  10002. if (InNonTrivialUnion)
  10003. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10004. << 0 << 0 << QT.getUnqualifiedType() << "";
  10005. for (const FieldDecl *FD : RD->fields())
  10006. if (!shouldIgnoreForRecordTriviality(FD))
  10007. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10008. }
  10009. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10010. // The non-trivial C union type or the struct/union type that contains a
  10011. // non-trivial C union.
  10012. QualType OrigTy;
  10013. SourceLocation OrigLoc;
  10014. Sema::NonTrivialCUnionContext UseContext;
  10015. Sema &S;
  10016. };
  10017. struct DiagNonTrivalCUnionDestructedTypeVisitor
  10018. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  10019. using Super =
  10020. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  10021. DiagNonTrivalCUnionDestructedTypeVisitor(
  10022. QualType OrigTy, SourceLocation OrigLoc,
  10023. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  10024. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10025. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  10026. const FieldDecl *FD, bool InNonTrivialUnion) {
  10027. if (const auto *AT = S.Context.getAsArrayType(QT))
  10028. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10029. InNonTrivialUnion);
  10030. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  10031. }
  10032. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10033. bool InNonTrivialUnion) {
  10034. if (InNonTrivialUnion)
  10035. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10036. << 1 << 1 << QT << FD->getName();
  10037. }
  10038. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10039. if (InNonTrivialUnion)
  10040. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10041. << 1 << 1 << QT << FD->getName();
  10042. }
  10043. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10044. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10045. if (RD->isUnion()) {
  10046. if (OrigLoc.isValid()) {
  10047. bool IsUnion = false;
  10048. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10049. IsUnion = OrigRD->isUnion();
  10050. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10051. << 1 << OrigTy << IsUnion << UseContext;
  10052. // Reset OrigLoc so that this diagnostic is emitted only once.
  10053. OrigLoc = SourceLocation();
  10054. }
  10055. InNonTrivialUnion = true;
  10056. }
  10057. if (InNonTrivialUnion)
  10058. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10059. << 0 << 1 << QT.getUnqualifiedType() << "";
  10060. for (const FieldDecl *FD : RD->fields())
  10061. if (!shouldIgnoreForRecordTriviality(FD))
  10062. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10063. }
  10064. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10065. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  10066. bool InNonTrivialUnion) {}
  10067. // The non-trivial C union type or the struct/union type that contains a
  10068. // non-trivial C union.
  10069. QualType OrigTy;
  10070. SourceLocation OrigLoc;
  10071. Sema::NonTrivialCUnionContext UseContext;
  10072. Sema &S;
  10073. };
  10074. struct DiagNonTrivalCUnionCopyVisitor
  10075. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  10076. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  10077. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  10078. Sema::NonTrivialCUnionContext UseContext,
  10079. Sema &S)
  10080. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10081. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  10082. const FieldDecl *FD, bool InNonTrivialUnion) {
  10083. if (const auto *AT = S.Context.getAsArrayType(QT))
  10084. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10085. InNonTrivialUnion);
  10086. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  10087. }
  10088. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10089. bool InNonTrivialUnion) {
  10090. if (InNonTrivialUnion)
  10091. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10092. << 1 << 2 << QT << FD->getName();
  10093. }
  10094. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10095. if (InNonTrivialUnion)
  10096. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10097. << 1 << 2 << QT << FD->getName();
  10098. }
  10099. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10100. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10101. if (RD->isUnion()) {
  10102. if (OrigLoc.isValid()) {
  10103. bool IsUnion = false;
  10104. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10105. IsUnion = OrigRD->isUnion();
  10106. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10107. << 2 << OrigTy << IsUnion << UseContext;
  10108. // Reset OrigLoc so that this diagnostic is emitted only once.
  10109. OrigLoc = SourceLocation();
  10110. }
  10111. InNonTrivialUnion = true;
  10112. }
  10113. if (InNonTrivialUnion)
  10114. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10115. << 0 << 2 << QT.getUnqualifiedType() << "";
  10116. for (const FieldDecl *FD : RD->fields())
  10117. if (!shouldIgnoreForRecordTriviality(FD))
  10118. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10119. }
  10120. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  10121. const FieldDecl *FD, bool InNonTrivialUnion) {}
  10122. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10123. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  10124. bool InNonTrivialUnion) {}
  10125. // The non-trivial C union type or the struct/union type that contains a
  10126. // non-trivial C union.
  10127. QualType OrigTy;
  10128. SourceLocation OrigLoc;
  10129. Sema::NonTrivialCUnionContext UseContext;
  10130. Sema &S;
  10131. };
  10132. } // namespace
  10133. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  10134. NonTrivialCUnionContext UseContext,
  10135. unsigned NonTrivialKind) {
  10136. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10137. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  10138. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  10139. "shouldn't be called if type doesn't have a non-trivial C union");
  10140. if ((NonTrivialKind & NTCUK_Init) &&
  10141. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10142. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  10143. .visit(QT, nullptr, false);
  10144. if ((NonTrivialKind & NTCUK_Destruct) &&
  10145. QT.hasNonTrivialToPrimitiveDestructCUnion())
  10146. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  10147. .visit(QT, nullptr, false);
  10148. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  10149. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  10150. .visit(QT, nullptr, false);
  10151. }
  10152. /// AddInitializerToDecl - Adds the initializer Init to the
  10153. /// declaration dcl. If DirectInit is true, this is C++ direct
  10154. /// initialization rather than copy initialization.
  10155. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  10156. // If there is no declaration, there was an error parsing it. Just ignore
  10157. // the initializer.
  10158. if (!RealDecl || RealDecl->isInvalidDecl()) {
  10159. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  10160. return;
  10161. }
  10162. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  10163. // Pure-specifiers are handled in ActOnPureSpecifier.
  10164. Diag(Method->getLocation(), diag::err_member_function_initialization)
  10165. << Method->getDeclName() << Init->getSourceRange();
  10166. Method->setInvalidDecl();
  10167. return;
  10168. }
  10169. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  10170. if (!VDecl) {
  10171. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  10172. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  10173. RealDecl->setInvalidDecl();
  10174. return;
  10175. }
  10176. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  10177. if (VDecl->getType()->isUndeducedType()) {
  10178. // Attempt typo correction early so that the type of the init expression can
  10179. // be deduced based on the chosen correction if the original init contains a
  10180. // TypoExpr.
  10181. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  10182. if (!Res.isUsable()) {
  10183. RealDecl->setInvalidDecl();
  10184. return;
  10185. }
  10186. Init = Res.get();
  10187. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  10188. return;
  10189. }
  10190. // dllimport cannot be used on variable definitions.
  10191. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  10192. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  10193. VDecl->setInvalidDecl();
  10194. return;
  10195. }
  10196. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  10197. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  10198. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  10199. VDecl->setInvalidDecl();
  10200. return;
  10201. }
  10202. if (!VDecl->getType()->isDependentType()) {
  10203. // A definition must end up with a complete type, which means it must be
  10204. // complete with the restriction that an array type might be completed by
  10205. // the initializer; note that later code assumes this restriction.
  10206. QualType BaseDeclType = VDecl->getType();
  10207. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  10208. BaseDeclType = Array->getElementType();
  10209. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  10210. diag::err_typecheck_decl_incomplete_type)) {
  10211. RealDecl->setInvalidDecl();
  10212. return;
  10213. }
  10214. // The variable can not have an abstract class type.
  10215. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  10216. diag::err_abstract_type_in_decl,
  10217. AbstractVariableType))
  10218. VDecl->setInvalidDecl();
  10219. }
  10220. // If adding the initializer will turn this declaration into a definition,
  10221. // and we already have a definition for this variable, diagnose or otherwise
  10222. // handle the situation.
  10223. VarDecl *Def;
  10224. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  10225. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  10226. !VDecl->isThisDeclarationADemotedDefinition() &&
  10227. checkVarDeclRedefinition(Def, VDecl))
  10228. return;
  10229. if (getLangOpts().CPlusPlus) {
  10230. // C++ [class.static.data]p4
  10231. // If a static data member is of const integral or const
  10232. // enumeration type, its declaration in the class definition can
  10233. // specify a constant-initializer which shall be an integral
  10234. // constant expression (5.19). In that case, the member can appear
  10235. // in integral constant expressions. The member shall still be
  10236. // defined in a namespace scope if it is used in the program and the
  10237. // namespace scope definition shall not contain an initializer.
  10238. //
  10239. // We already performed a redefinition check above, but for static
  10240. // data members we also need to check whether there was an in-class
  10241. // declaration with an initializer.
  10242. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  10243. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  10244. << VDecl->getDeclName();
  10245. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  10246. diag::note_previous_initializer)
  10247. << 0;
  10248. return;
  10249. }
  10250. if (VDecl->hasLocalStorage())
  10251. setFunctionHasBranchProtectedScope();
  10252. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  10253. VDecl->setInvalidDecl();
  10254. return;
  10255. }
  10256. }
  10257. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10258. // a kernel function cannot be initialized."
  10259. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10260. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10261. VDecl->setInvalidDecl();
  10262. return;
  10263. }
  10264. // Get the decls type and save a reference for later, since
  10265. // CheckInitializerTypes may change it.
  10266. QualType DclT = VDecl->getType(), SavT = DclT;
  10267. // Expressions default to 'id' when we're in a debugger
  10268. // and we are assigning it to a variable of Objective-C pointer type.
  10269. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10270. Init->getType() == Context.UnknownAnyTy) {
  10271. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10272. if (Result.isInvalid()) {
  10273. VDecl->setInvalidDecl();
  10274. return;
  10275. }
  10276. Init = Result.get();
  10277. }
  10278. // Perform the initialization.
  10279. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  10280. if (!VDecl->isInvalidDecl()) {
  10281. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10282. InitializationKind Kind = InitializationKind::CreateForInit(
  10283. VDecl->getLocation(), DirectInit, Init);
  10284. MultiExprArg Args = Init;
  10285. if (CXXDirectInit)
  10286. Args = MultiExprArg(CXXDirectInit->getExprs(),
  10287. CXXDirectInit->getNumExprs());
  10288. // Try to correct any TypoExprs in the initialization arguments.
  10289. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  10290. ExprResult Res = CorrectDelayedTyposInExpr(
  10291. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  10292. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  10293. return Init.Failed() ? ExprError() : E;
  10294. });
  10295. if (Res.isInvalid()) {
  10296. VDecl->setInvalidDecl();
  10297. } else if (Res.get() != Args[Idx]) {
  10298. Args[Idx] = Res.get();
  10299. }
  10300. }
  10301. if (VDecl->isInvalidDecl())
  10302. return;
  10303. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  10304. /*TopLevelOfInitList=*/false,
  10305. /*TreatUnavailableAsInvalid=*/false);
  10306. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  10307. if (Result.isInvalid()) {
  10308. VDecl->setInvalidDecl();
  10309. return;
  10310. }
  10311. Init = Result.getAs<Expr>();
  10312. }
  10313. // Check for self-references within variable initializers.
  10314. // Variables declared within a function/method body (except for references)
  10315. // are handled by a dataflow analysis.
  10316. // This is undefined behavior in C++, but valid in C.
  10317. if (getLangOpts().CPlusPlus) {
  10318. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  10319. VDecl->getType()->isReferenceType()) {
  10320. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  10321. }
  10322. }
  10323. // If the type changed, it means we had an incomplete type that was
  10324. // completed by the initializer. For example:
  10325. // int ary[] = { 1, 3, 5 };
  10326. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  10327. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  10328. VDecl->setType(DclT);
  10329. if (!VDecl->isInvalidDecl()) {
  10330. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  10331. if (VDecl->hasAttr<BlocksAttr>())
  10332. checkRetainCycles(VDecl, Init);
  10333. // It is safe to assign a weak reference into a strong variable.
  10334. // Although this code can still have problems:
  10335. // id x = self.weakProp;
  10336. // id y = self.weakProp;
  10337. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10338. // paths through the function. This should be revisited if
  10339. // -Wrepeated-use-of-weak is made flow-sensitive.
  10340. if (FunctionScopeInfo *FSI = getCurFunction())
  10341. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  10342. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  10343. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10344. Init->getBeginLoc()))
  10345. FSI->markSafeWeakUse(Init);
  10346. }
  10347. // The initialization is usually a full-expression.
  10348. //
  10349. // FIXME: If this is a braced initialization of an aggregate, it is not
  10350. // an expression, and each individual field initializer is a separate
  10351. // full-expression. For instance, in:
  10352. //
  10353. // struct Temp { ~Temp(); };
  10354. // struct S { S(Temp); };
  10355. // struct T { S a, b; } t = { Temp(), Temp() }
  10356. //
  10357. // we should destroy the first Temp before constructing the second.
  10358. ExprResult Result =
  10359. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  10360. /*DiscardedValue*/ false, VDecl->isConstexpr());
  10361. if (Result.isInvalid()) {
  10362. VDecl->setInvalidDecl();
  10363. return;
  10364. }
  10365. Init = Result.get();
  10366. // Attach the initializer to the decl.
  10367. VDecl->setInit(Init);
  10368. if (VDecl->isLocalVarDecl()) {
  10369. // Don't check the initializer if the declaration is malformed.
  10370. if (VDecl->isInvalidDecl()) {
  10371. // do nothing
  10372. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  10373. // This is true even in C++ for OpenCL.
  10374. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  10375. CheckForConstantInitializer(Init, DclT);
  10376. // Otherwise, C++ does not restrict the initializer.
  10377. } else if (getLangOpts().CPlusPlus) {
  10378. // do nothing
  10379. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  10380. // static storage duration shall be constant expressions or string literals.
  10381. } else if (VDecl->getStorageClass() == SC_Static) {
  10382. CheckForConstantInitializer(Init, DclT);
  10383. // C89 is stricter than C99 for aggregate initializers.
  10384. // C89 6.5.7p3: All the expressions [...] in an initializer list
  10385. // for an object that has aggregate or union type shall be
  10386. // constant expressions.
  10387. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  10388. isa<InitListExpr>(Init)) {
  10389. const Expr *Culprit;
  10390. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  10391. Diag(Culprit->getExprLoc(),
  10392. diag::ext_aggregate_init_not_constant)
  10393. << Culprit->getSourceRange();
  10394. }
  10395. }
  10396. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10397. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10398. if (VDecl->hasLocalStorage())
  10399. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10400. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10401. VDecl->getLexicalDeclContext()->isRecord()) {
  10402. // This is an in-class initialization for a static data member, e.g.,
  10403. //
  10404. // struct S {
  10405. // static const int value = 17;
  10406. // };
  10407. // C++ [class.mem]p4:
  10408. // A member-declarator can contain a constant-initializer only
  10409. // if it declares a static member (9.4) of const integral or
  10410. // const enumeration type, see 9.4.2.
  10411. //
  10412. // C++11 [class.static.data]p3:
  10413. // If a non-volatile non-inline const static data member is of integral
  10414. // or enumeration type, its declaration in the class definition can
  10415. // specify a brace-or-equal-initializer in which every initializer-clause
  10416. // that is an assignment-expression is a constant expression. A static
  10417. // data member of literal type can be declared in the class definition
  10418. // with the constexpr specifier; if so, its declaration shall specify a
  10419. // brace-or-equal-initializer in which every initializer-clause that is
  10420. // an assignment-expression is a constant expression.
  10421. // Do nothing on dependent types.
  10422. if (DclT->isDependentType()) {
  10423. // Allow any 'static constexpr' members, whether or not they are of literal
  10424. // type. We separately check that every constexpr variable is of literal
  10425. // type.
  10426. } else if (VDecl->isConstexpr()) {
  10427. // Require constness.
  10428. } else if (!DclT.isConstQualified()) {
  10429. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10430. << Init->getSourceRange();
  10431. VDecl->setInvalidDecl();
  10432. // We allow integer constant expressions in all cases.
  10433. } else if (DclT->isIntegralOrEnumerationType()) {
  10434. // Check whether the expression is a constant expression.
  10435. SourceLocation Loc;
  10436. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10437. // In C++11, a non-constexpr const static data member with an
  10438. // in-class initializer cannot be volatile.
  10439. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10440. else if (Init->isValueDependent())
  10441. ; // Nothing to check.
  10442. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10443. ; // Ok, it's an ICE!
  10444. else if (Init->getType()->isScopedEnumeralType() &&
  10445. Init->isCXX11ConstantExpr(Context))
  10446. ; // Ok, it is a scoped-enum constant expression.
  10447. else if (Init->isEvaluatable(Context)) {
  10448. // If we can constant fold the initializer through heroics, accept it,
  10449. // but report this as a use of an extension for -pedantic.
  10450. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10451. << Init->getSourceRange();
  10452. } else {
  10453. // Otherwise, this is some crazy unknown case. Report the issue at the
  10454. // location provided by the isIntegerConstantExpr failed check.
  10455. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10456. << Init->getSourceRange();
  10457. VDecl->setInvalidDecl();
  10458. }
  10459. // We allow foldable floating-point constants as an extension.
  10460. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10461. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10462. // it anyway and provide a fixit to add the 'constexpr'.
  10463. if (getLangOpts().CPlusPlus11) {
  10464. Diag(VDecl->getLocation(),
  10465. diag::ext_in_class_initializer_float_type_cxx11)
  10466. << DclT << Init->getSourceRange();
  10467. Diag(VDecl->getBeginLoc(),
  10468. diag::note_in_class_initializer_float_type_cxx11)
  10469. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10470. } else {
  10471. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10472. << DclT << Init->getSourceRange();
  10473. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10474. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10475. << Init->getSourceRange();
  10476. VDecl->setInvalidDecl();
  10477. }
  10478. }
  10479. // Suggest adding 'constexpr' in C++11 for literal types.
  10480. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10481. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10482. << DclT << Init->getSourceRange()
  10483. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10484. VDecl->setConstexpr(true);
  10485. } else {
  10486. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10487. << DclT << Init->getSourceRange();
  10488. VDecl->setInvalidDecl();
  10489. }
  10490. } else if (VDecl->isFileVarDecl()) {
  10491. // In C, extern is typically used to avoid tentative definitions when
  10492. // declaring variables in headers, but adding an intializer makes it a
  10493. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10494. // In C++, extern is often used to give implictly static const variables
  10495. // external linkage, so don't warn in that case. If selectany is present,
  10496. // this might be header code intended for C and C++ inclusion, so apply the
  10497. // C++ rules.
  10498. if (VDecl->getStorageClass() == SC_Extern &&
  10499. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10500. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10501. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10502. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10503. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10504. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10505. // external linkage by default if the variable is declared with
  10506. // __declspec(dllexport).
  10507. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10508. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10509. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10510. VDecl->setStorageClass(SC_Extern);
  10511. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10512. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10513. CheckForConstantInitializer(Init, DclT);
  10514. }
  10515. QualType InitType = Init->getType();
  10516. if (!InitType.isNull() &&
  10517. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10518. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  10519. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  10520. // We will represent direct-initialization similarly to copy-initialization:
  10521. // int x(1); -as-> int x = 1;
  10522. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10523. //
  10524. // Clients that want to distinguish between the two forms, can check for
  10525. // direct initializer using VarDecl::getInitStyle().
  10526. // A major benefit is that clients that don't particularly care about which
  10527. // exactly form was it (like the CodeGen) can handle both cases without
  10528. // special case code.
  10529. // C++ 8.5p11:
  10530. // The form of initialization (using parentheses or '=') is generally
  10531. // insignificant, but does matter when the entity being initialized has a
  10532. // class type.
  10533. if (CXXDirectInit) {
  10534. assert(DirectInit && "Call-style initializer must be direct init.");
  10535. VDecl->setInitStyle(VarDecl::CallInit);
  10536. } else if (DirectInit) {
  10537. // This must be list-initialization. No other way is direct-initialization.
  10538. VDecl->setInitStyle(VarDecl::ListInit);
  10539. }
  10540. CheckCompleteVariableDeclaration(VDecl);
  10541. }
  10542. /// ActOnInitializerError - Given that there was an error parsing an
  10543. /// initializer for the given declaration, try to return to some form
  10544. /// of sanity.
  10545. void Sema::ActOnInitializerError(Decl *D) {
  10546. // Our main concern here is re-establishing invariants like "a
  10547. // variable's type is either dependent or complete".
  10548. if (!D || D->isInvalidDecl()) return;
  10549. VarDecl *VD = dyn_cast<VarDecl>(D);
  10550. if (!VD) return;
  10551. // Bindings are not usable if we can't make sense of the initializer.
  10552. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10553. for (auto *BD : DD->bindings())
  10554. BD->setInvalidDecl();
  10555. // Auto types are meaningless if we can't make sense of the initializer.
  10556. if (ParsingInitForAutoVars.count(D)) {
  10557. D->setInvalidDecl();
  10558. return;
  10559. }
  10560. QualType Ty = VD->getType();
  10561. if (Ty->isDependentType()) return;
  10562. // Require a complete type.
  10563. if (RequireCompleteType(VD->getLocation(),
  10564. Context.getBaseElementType(Ty),
  10565. diag::err_typecheck_decl_incomplete_type)) {
  10566. VD->setInvalidDecl();
  10567. return;
  10568. }
  10569. // Require a non-abstract type.
  10570. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10571. diag::err_abstract_type_in_decl,
  10572. AbstractVariableType)) {
  10573. VD->setInvalidDecl();
  10574. return;
  10575. }
  10576. // Don't bother complaining about constructors or destructors,
  10577. // though.
  10578. }
  10579. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10580. // If there is no declaration, there was an error parsing it. Just ignore it.
  10581. if (!RealDecl)
  10582. return;
  10583. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10584. QualType Type = Var->getType();
  10585. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10586. if (isa<DecompositionDecl>(RealDecl)) {
  10587. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10588. Var->setInvalidDecl();
  10589. return;
  10590. }
  10591. if (Type->isUndeducedType() &&
  10592. DeduceVariableDeclarationType(Var, false, nullptr))
  10593. return;
  10594. // C++11 [class.static.data]p3: A static data member can be declared with
  10595. // the constexpr specifier; if so, its declaration shall specify
  10596. // a brace-or-equal-initializer.
  10597. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10598. // the definition of a variable [...] or the declaration of a static data
  10599. // member.
  10600. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10601. !Var->isThisDeclarationADemotedDefinition()) {
  10602. if (Var->isStaticDataMember()) {
  10603. // C++1z removes the relevant rule; the in-class declaration is always
  10604. // a definition there.
  10605. if (!getLangOpts().CPlusPlus17 &&
  10606. !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  10607. Diag(Var->getLocation(),
  10608. diag::err_constexpr_static_mem_var_requires_init)
  10609. << Var->getDeclName();
  10610. Var->setInvalidDecl();
  10611. return;
  10612. }
  10613. } else {
  10614. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10615. Var->setInvalidDecl();
  10616. return;
  10617. }
  10618. }
  10619. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10620. // be initialized.
  10621. if (!Var->isInvalidDecl() &&
  10622. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10623. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10624. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10625. Var->setInvalidDecl();
  10626. return;
  10627. }
  10628. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  10629. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  10630. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10631. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  10632. NTCUC_DefaultInitializedObject, NTCUK_Init);
  10633. switch (DefKind) {
  10634. case VarDecl::Definition:
  10635. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10636. break;
  10637. // We have an out-of-line definition of a static data member
  10638. // that has an in-class initializer, so we type-check this like
  10639. // a declaration.
  10640. //
  10641. LLVM_FALLTHROUGH;
  10642. case VarDecl::DeclarationOnly:
  10643. // It's only a declaration.
  10644. // Block scope. C99 6.7p7: If an identifier for an object is
  10645. // declared with no linkage (C99 6.2.2p6), the type for the
  10646. // object shall be complete.
  10647. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10648. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10649. RequireCompleteType(Var->getLocation(), Type,
  10650. diag::err_typecheck_decl_incomplete_type))
  10651. Var->setInvalidDecl();
  10652. // Make sure that the type is not abstract.
  10653. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10654. RequireNonAbstractType(Var->getLocation(), Type,
  10655. diag::err_abstract_type_in_decl,
  10656. AbstractVariableType))
  10657. Var->setInvalidDecl();
  10658. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10659. Var->getStorageClass() == SC_PrivateExtern) {
  10660. Diag(Var->getLocation(), diag::warn_private_extern);
  10661. Diag(Var->getLocation(), diag::note_private_extern);
  10662. }
  10663. return;
  10664. case VarDecl::TentativeDefinition:
  10665. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10666. // object that has file scope without an initializer, and without a
  10667. // storage-class specifier or with the storage-class specifier "static",
  10668. // constitutes a tentative definition. Note: A tentative definition with
  10669. // external linkage is valid (C99 6.2.2p5).
  10670. if (!Var->isInvalidDecl()) {
  10671. if (const IncompleteArrayType *ArrayT
  10672. = Context.getAsIncompleteArrayType(Type)) {
  10673. if (RequireCompleteType(Var->getLocation(),
  10674. ArrayT->getElementType(),
  10675. diag::err_illegal_decl_array_incomplete_type))
  10676. Var->setInvalidDecl();
  10677. } else if (Var->getStorageClass() == SC_Static) {
  10678. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10679. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10680. // declared type shall not be an incomplete type.
  10681. // NOTE: code such as the following
  10682. // static struct s;
  10683. // struct s { int a; };
  10684. // is accepted by gcc. Hence here we issue a warning instead of
  10685. // an error and we do not invalidate the static declaration.
  10686. // NOTE: to avoid multiple warnings, only check the first declaration.
  10687. if (Var->isFirstDecl())
  10688. RequireCompleteType(Var->getLocation(), Type,
  10689. diag::ext_typecheck_decl_incomplete_type);
  10690. }
  10691. }
  10692. // Record the tentative definition; we're done.
  10693. if (!Var->isInvalidDecl())
  10694. TentativeDefinitions.push_back(Var);
  10695. return;
  10696. }
  10697. // Provide a specific diagnostic for uninitialized variable
  10698. // definitions with incomplete array type.
  10699. if (Type->isIncompleteArrayType()) {
  10700. Diag(Var->getLocation(),
  10701. diag::err_typecheck_incomplete_array_needs_initializer);
  10702. Var->setInvalidDecl();
  10703. return;
  10704. }
  10705. // Provide a specific diagnostic for uninitialized variable
  10706. // definitions with reference type.
  10707. if (Type->isReferenceType()) {
  10708. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10709. << Var->getDeclName()
  10710. << SourceRange(Var->getLocation(), Var->getLocation());
  10711. Var->setInvalidDecl();
  10712. return;
  10713. }
  10714. // Do not attempt to type-check the default initializer for a
  10715. // variable with dependent type.
  10716. if (Type->isDependentType())
  10717. return;
  10718. if (Var->isInvalidDecl())
  10719. return;
  10720. if (!Var->hasAttr<AliasAttr>()) {
  10721. if (RequireCompleteType(Var->getLocation(),
  10722. Context.getBaseElementType(Type),
  10723. diag::err_typecheck_decl_incomplete_type)) {
  10724. Var->setInvalidDecl();
  10725. return;
  10726. }
  10727. } else {
  10728. return;
  10729. }
  10730. // The variable can not have an abstract class type.
  10731. if (RequireNonAbstractType(Var->getLocation(), Type,
  10732. diag::err_abstract_type_in_decl,
  10733. AbstractVariableType)) {
  10734. Var->setInvalidDecl();
  10735. return;
  10736. }
  10737. // Check for jumps past the implicit initializer. C++0x
  10738. // clarifies that this applies to a "variable with automatic
  10739. // storage duration", not a "local variable".
  10740. // C++11 [stmt.dcl]p3
  10741. // A program that jumps from a point where a variable with automatic
  10742. // storage duration is not in scope to a point where it is in scope is
  10743. // ill-formed unless the variable has scalar type, class type with a
  10744. // trivial default constructor and a trivial destructor, a cv-qualified
  10745. // version of one of these types, or an array of one of the preceding
  10746. // types and is declared without an initializer.
  10747. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10748. if (const RecordType *Record
  10749. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10750. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10751. // Mark the function (if we're in one) for further checking even if the
  10752. // looser rules of C++11 do not require such checks, so that we can
  10753. // diagnose incompatibilities with C++98.
  10754. if (!CXXRecord->isPOD())
  10755. setFunctionHasBranchProtectedScope();
  10756. }
  10757. }
  10758. // In OpenCL, we can't initialize objects in the __local address space,
  10759. // even implicitly, so don't synthesize an implicit initializer.
  10760. if (getLangOpts().OpenCL &&
  10761. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10762. return;
  10763. // C++03 [dcl.init]p9:
  10764. // If no initializer is specified for an object, and the
  10765. // object is of (possibly cv-qualified) non-POD class type (or
  10766. // array thereof), the object shall be default-initialized; if
  10767. // the object is of const-qualified type, the underlying class
  10768. // type shall have a user-declared default
  10769. // constructor. Otherwise, if no initializer is specified for
  10770. // a non- static object, the object and its subobjects, if
  10771. // any, have an indeterminate initial value); if the object
  10772. // or any of its subobjects are of const-qualified type, the
  10773. // program is ill-formed.
  10774. // C++0x [dcl.init]p11:
  10775. // If no initializer is specified for an object, the object is
  10776. // default-initialized; [...].
  10777. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10778. InitializationKind Kind
  10779. = InitializationKind::CreateDefault(Var->getLocation());
  10780. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10781. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10782. if (Init.isInvalid())
  10783. Var->setInvalidDecl();
  10784. else if (Init.get()) {
  10785. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10786. // This is important for template substitution.
  10787. Var->setInitStyle(VarDecl::CallInit);
  10788. }
  10789. CheckCompleteVariableDeclaration(Var);
  10790. }
  10791. }
  10792. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10793. // If there is no declaration, there was an error parsing it. Ignore it.
  10794. if (!D)
  10795. return;
  10796. VarDecl *VD = dyn_cast<VarDecl>(D);
  10797. if (!VD) {
  10798. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10799. D->setInvalidDecl();
  10800. return;
  10801. }
  10802. VD->setCXXForRangeDecl(true);
  10803. // for-range-declaration cannot be given a storage class specifier.
  10804. int Error = -1;
  10805. switch (VD->getStorageClass()) {
  10806. case SC_None:
  10807. break;
  10808. case SC_Extern:
  10809. Error = 0;
  10810. break;
  10811. case SC_Static:
  10812. Error = 1;
  10813. break;
  10814. case SC_PrivateExtern:
  10815. Error = 2;
  10816. break;
  10817. case SC_Auto:
  10818. Error = 3;
  10819. break;
  10820. case SC_Register:
  10821. Error = 4;
  10822. break;
  10823. }
  10824. if (Error != -1) {
  10825. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10826. << VD->getDeclName() << Error;
  10827. D->setInvalidDecl();
  10828. }
  10829. }
  10830. StmtResult
  10831. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10832. IdentifierInfo *Ident,
  10833. ParsedAttributes &Attrs,
  10834. SourceLocation AttrEnd) {
  10835. // C++1y [stmt.iter]p1:
  10836. // A range-based for statement of the form
  10837. // for ( for-range-identifier : for-range-initializer ) statement
  10838. // is equivalent to
  10839. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10840. DeclSpec DS(Attrs.getPool().getFactory());
  10841. const char *PrevSpec;
  10842. unsigned DiagID;
  10843. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10844. getPrintingPolicy());
  10845. Declarator D(DS, DeclaratorContext::ForContext);
  10846. D.SetIdentifier(Ident, IdentLoc);
  10847. D.takeAttributes(Attrs, AttrEnd);
  10848. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10849. IdentLoc);
  10850. Decl *Var = ActOnDeclarator(S, D);
  10851. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10852. FinalizeDeclaration(Var);
  10853. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10854. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10855. }
  10856. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10857. if (var->isInvalidDecl()) return;
  10858. if (getLangOpts().OpenCL) {
  10859. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10860. // initialiser
  10861. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10862. !var->hasInit()) {
  10863. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10864. << 1 /*Init*/;
  10865. var->setInvalidDecl();
  10866. return;
  10867. }
  10868. }
  10869. // In Objective-C, don't allow jumps past the implicit initialization of a
  10870. // local retaining variable.
  10871. if (getLangOpts().ObjC &&
  10872. var->hasLocalStorage()) {
  10873. switch (var->getType().getObjCLifetime()) {
  10874. case Qualifiers::OCL_None:
  10875. case Qualifiers::OCL_ExplicitNone:
  10876. case Qualifiers::OCL_Autoreleasing:
  10877. break;
  10878. case Qualifiers::OCL_Weak:
  10879. case Qualifiers::OCL_Strong:
  10880. setFunctionHasBranchProtectedScope();
  10881. break;
  10882. }
  10883. }
  10884. if (var->hasLocalStorage() &&
  10885. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10886. setFunctionHasBranchProtectedScope();
  10887. // Warn about externally-visible variables being defined without a
  10888. // prior declaration. We only want to do this for global
  10889. // declarations, but we also specifically need to avoid doing it for
  10890. // class members because the linkage of an anonymous class can
  10891. // change if it's later given a typedef name.
  10892. if (var->isThisDeclarationADefinition() &&
  10893. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10894. var->isExternallyVisible() && var->hasLinkage() &&
  10895. !var->isInline() && !var->getDescribedVarTemplate() &&
  10896. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10897. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10898. var->getLocation())) {
  10899. // Find a previous declaration that's not a definition.
  10900. VarDecl *prev = var->getPreviousDecl();
  10901. while (prev && prev->isThisDeclarationADefinition())
  10902. prev = prev->getPreviousDecl();
  10903. if (!prev) {
  10904. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10905. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  10906. << /* variable */ 0;
  10907. }
  10908. }
  10909. // Cache the result of checking for constant initialization.
  10910. Optional<bool> CacheHasConstInit;
  10911. const Expr *CacheCulprit = nullptr;
  10912. auto checkConstInit = [&]() mutable {
  10913. if (!CacheHasConstInit)
  10914. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10915. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10916. return *CacheHasConstInit;
  10917. };
  10918. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10919. if (var->getType().isDestructedType()) {
  10920. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10921. // The type of an object with thread storage duration shall not
  10922. // have a non-trivial destructor.
  10923. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10924. if (getLangOpts().CPlusPlus11)
  10925. Diag(var->getLocation(), diag::note_use_thread_local);
  10926. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10927. if (!checkConstInit()) {
  10928. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10929. // An object of thread storage duration shall not require dynamic
  10930. // initialization.
  10931. // FIXME: Need strict checking here.
  10932. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10933. << CacheCulprit->getSourceRange();
  10934. if (getLangOpts().CPlusPlus11)
  10935. Diag(var->getLocation(), diag::note_use_thread_local);
  10936. }
  10937. }
  10938. }
  10939. // Apply section attributes and pragmas to global variables.
  10940. bool GlobalStorage = var->hasGlobalStorage();
  10941. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10942. !inTemplateInstantiation()) {
  10943. PragmaStack<StringLiteral *> *Stack = nullptr;
  10944. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10945. if (var->getType().isConstQualified())
  10946. Stack = &ConstSegStack;
  10947. else if (!var->getInit()) {
  10948. Stack = &BSSSegStack;
  10949. SectionFlags |= ASTContext::PSF_Write;
  10950. } else {
  10951. Stack = &DataSegStack;
  10952. SectionFlags |= ASTContext::PSF_Write;
  10953. }
  10954. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
  10955. var->addAttr(SectionAttr::CreateImplicit(
  10956. Context, Stack->CurrentValue->getString(),
  10957. Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  10958. SectionAttr::Declspec_allocate));
  10959. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10960. if (UnifySection(SA->getName(), SectionFlags, var))
  10961. var->dropAttr<SectionAttr>();
  10962. // Apply the init_seg attribute if this has an initializer. If the
  10963. // initializer turns out to not be dynamic, we'll end up ignoring this
  10964. // attribute.
  10965. if (CurInitSeg && var->getInit())
  10966. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10967. CurInitSegLoc,
  10968. AttributeCommonInfo::AS_Pragma));
  10969. }
  10970. // All the following checks are C++ only.
  10971. if (!getLangOpts().CPlusPlus) {
  10972. // If this variable must be emitted, add it as an initializer for the
  10973. // current module.
  10974. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10975. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10976. return;
  10977. }
  10978. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10979. CheckCompleteDecompositionDeclaration(DD);
  10980. QualType type = var->getType();
  10981. if (type->isDependentType()) return;
  10982. if (var->hasAttr<BlocksAttr>())
  10983. getCurFunction()->addByrefBlockVar(var);
  10984. Expr *Init = var->getInit();
  10985. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10986. QualType baseType = Context.getBaseElementType(type);
  10987. if (Init && !Init->isValueDependent()) {
  10988. if (var->isConstexpr()) {
  10989. SmallVector<PartialDiagnosticAt, 8> Notes;
  10990. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10991. SourceLocation DiagLoc = var->getLocation();
  10992. // If the note doesn't add any useful information other than a source
  10993. // location, fold it into the primary diagnostic.
  10994. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10995. diag::note_invalid_subexpr_in_const_expr) {
  10996. DiagLoc = Notes[0].first;
  10997. Notes.clear();
  10998. }
  10999. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  11000. << var << Init->getSourceRange();
  11001. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  11002. Diag(Notes[I].first, Notes[I].second);
  11003. }
  11004. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  11005. // Check whether the initializer of a const variable of integral or
  11006. // enumeration type is an ICE now, since we can't tell whether it was
  11007. // initialized by a constant expression if we check later.
  11008. var->checkInitIsICE();
  11009. }
  11010. // Don't emit further diagnostics about constexpr globals since they
  11011. // were just diagnosed.
  11012. if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
  11013. // FIXME: Need strict checking in C++03 here.
  11014. bool DiagErr = getLangOpts().CPlusPlus11
  11015. ? !var->checkInitIsICE() : !checkConstInit();
  11016. if (DiagErr) {
  11017. auto *Attr = var->getAttr<ConstInitAttr>();
  11018. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  11019. << Init->getSourceRange();
  11020. Diag(Attr->getLocation(),
  11021. diag::note_declared_required_constant_init_here)
  11022. << Attr->getRange() << Attr->isConstinit();
  11023. if (getLangOpts().CPlusPlus11) {
  11024. APValue Value;
  11025. SmallVector<PartialDiagnosticAt, 8> Notes;
  11026. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  11027. for (auto &it : Notes)
  11028. Diag(it.first, it.second);
  11029. } else {
  11030. Diag(CacheCulprit->getExprLoc(),
  11031. diag::note_invalid_subexpr_in_const_expr)
  11032. << CacheCulprit->getSourceRange();
  11033. }
  11034. }
  11035. }
  11036. else if (!var->isConstexpr() && IsGlobal &&
  11037. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  11038. var->getLocation())) {
  11039. // Warn about globals which don't have a constant initializer. Don't
  11040. // warn about globals with a non-trivial destructor because we already
  11041. // warned about them.
  11042. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  11043. if (!(RD && !RD->hasTrivialDestructor())) {
  11044. if (!checkConstInit())
  11045. Diag(var->getLocation(), diag::warn_global_constructor)
  11046. << Init->getSourceRange();
  11047. }
  11048. }
  11049. }
  11050. // Require the destructor.
  11051. if (const RecordType *recordType = baseType->getAs<RecordType>())
  11052. FinalizeVarWithDestructor(var, recordType);
  11053. // If this variable must be emitted, add it as an initializer for the current
  11054. // module.
  11055. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  11056. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  11057. }
  11058. /// Determines if a variable's alignment is dependent.
  11059. static bool hasDependentAlignment(VarDecl *VD) {
  11060. if (VD->getType()->isDependentType())
  11061. return true;
  11062. for (auto *I : VD->specific_attrs<AlignedAttr>())
  11063. if (I->isAlignmentDependent())
  11064. return true;
  11065. return false;
  11066. }
  11067. /// Check if VD needs to be dllexport/dllimport due to being in a
  11068. /// dllexport/import function.
  11069. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  11070. assert(VD->isStaticLocal());
  11071. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11072. // Find outermost function when VD is in lambda function.
  11073. while (FD && !getDLLAttr(FD) &&
  11074. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  11075. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  11076. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  11077. }
  11078. if (!FD)
  11079. return;
  11080. // Static locals inherit dll attributes from their function.
  11081. if (Attr *A = getDLLAttr(FD)) {
  11082. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  11083. NewAttr->setInherited(true);
  11084. VD->addAttr(NewAttr);
  11085. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  11086. auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
  11087. NewAttr->setInherited(true);
  11088. VD->addAttr(NewAttr);
  11089. // Export this function to enforce exporting this static variable even
  11090. // if it is not used in this compilation unit.
  11091. if (!FD->hasAttr<DLLExportAttr>())
  11092. FD->addAttr(NewAttr);
  11093. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  11094. auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
  11095. NewAttr->setInherited(true);
  11096. VD->addAttr(NewAttr);
  11097. }
  11098. }
  11099. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  11100. /// any semantic actions necessary after any initializer has been attached.
  11101. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  11102. // Note that we are no longer parsing the initializer for this declaration.
  11103. ParsingInitForAutoVars.erase(ThisDecl);
  11104. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  11105. if (!VD)
  11106. return;
  11107. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  11108. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  11109. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  11110. if (PragmaClangBSSSection.Valid)
  11111. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
  11112. Context, PragmaClangBSSSection.SectionName,
  11113. PragmaClangBSSSection.PragmaLocation,
  11114. AttributeCommonInfo::AS_Pragma));
  11115. if (PragmaClangDataSection.Valid)
  11116. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
  11117. Context, PragmaClangDataSection.SectionName,
  11118. PragmaClangDataSection.PragmaLocation,
  11119. AttributeCommonInfo::AS_Pragma));
  11120. if (PragmaClangRodataSection.Valid)
  11121. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
  11122. Context, PragmaClangRodataSection.SectionName,
  11123. PragmaClangRodataSection.PragmaLocation,
  11124. AttributeCommonInfo::AS_Pragma));
  11125. }
  11126. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  11127. for (auto *BD : DD->bindings()) {
  11128. FinalizeDeclaration(BD);
  11129. }
  11130. }
  11131. checkAttributesAfterMerging(*this, *VD);
  11132. // Perform TLS alignment check here after attributes attached to the variable
  11133. // which may affect the alignment have been processed. Only perform the check
  11134. // if the target has a maximum TLS alignment (zero means no constraints).
  11135. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  11136. // Protect the check so that it's not performed on dependent types and
  11137. // dependent alignments (we can't determine the alignment in that case).
  11138. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  11139. !VD->isInvalidDecl()) {
  11140. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  11141. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  11142. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  11143. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  11144. << (unsigned)MaxAlignChars.getQuantity();
  11145. }
  11146. }
  11147. }
  11148. if (VD->isStaticLocal()) {
  11149. CheckStaticLocalForDllExport(VD);
  11150. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  11151. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  11152. // function, only __shared__ variables or variables without any device
  11153. // memory qualifiers may be declared with static storage class.
  11154. // Note: It is unclear how a function-scope non-const static variable
  11155. // without device memory qualifier is implemented, therefore only static
  11156. // const variable without device memory qualifier is allowed.
  11157. [&]() {
  11158. if (!getLangOpts().CUDA)
  11159. return;
  11160. if (VD->hasAttr<CUDASharedAttr>())
  11161. return;
  11162. if (VD->getType().isConstQualified() &&
  11163. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  11164. return;
  11165. if (CUDADiagIfDeviceCode(VD->getLocation(),
  11166. diag::err_device_static_local_var)
  11167. << CurrentCUDATarget())
  11168. VD->setInvalidDecl();
  11169. }();
  11170. }
  11171. }
  11172. // Perform check for initializers of device-side global variables.
  11173. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  11174. // 7.5). We must also apply the same checks to all __shared__
  11175. // variables whether they are local or not. CUDA also allows
  11176. // constant initializers for __constant__ and __device__ variables.
  11177. if (getLangOpts().CUDA)
  11178. checkAllowedCUDAInitializer(VD);
  11179. // Grab the dllimport or dllexport attribute off of the VarDecl.
  11180. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  11181. // Imported static data members cannot be defined out-of-line.
  11182. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  11183. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  11184. VD->isThisDeclarationADefinition()) {
  11185. // We allow definitions of dllimport class template static data members
  11186. // with a warning.
  11187. CXXRecordDecl *Context =
  11188. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  11189. bool IsClassTemplateMember =
  11190. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  11191. Context->getDescribedClassTemplate();
  11192. Diag(VD->getLocation(),
  11193. IsClassTemplateMember
  11194. ? diag::warn_attribute_dllimport_static_field_definition
  11195. : diag::err_attribute_dllimport_static_field_definition);
  11196. Diag(IA->getLocation(), diag::note_attribute);
  11197. if (!IsClassTemplateMember)
  11198. VD->setInvalidDecl();
  11199. }
  11200. }
  11201. // dllimport/dllexport variables cannot be thread local, their TLS index
  11202. // isn't exported with the variable.
  11203. if (DLLAttr && VD->getTLSKind()) {
  11204. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11205. if (F && getDLLAttr(F)) {
  11206. assert(VD->isStaticLocal());
  11207. // But if this is a static local in a dlimport/dllexport function, the
  11208. // function will never be inlined, which means the var would never be
  11209. // imported, so having it marked import/export is safe.
  11210. } else {
  11211. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  11212. << DLLAttr;
  11213. VD->setInvalidDecl();
  11214. }
  11215. }
  11216. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  11217. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  11218. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  11219. VD->dropAttr<UsedAttr>();
  11220. }
  11221. }
  11222. const DeclContext *DC = VD->getDeclContext();
  11223. // If there's a #pragma GCC visibility in scope, and this isn't a class
  11224. // member, set the visibility of this variable.
  11225. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  11226. AddPushedVisibilityAttribute(VD);
  11227. // FIXME: Warn on unused var template partial specializations.
  11228. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  11229. MarkUnusedFileScopedDecl(VD);
  11230. // Now we have parsed the initializer and can update the table of magic
  11231. // tag values.
  11232. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  11233. !VD->getType()->isIntegralOrEnumerationType())
  11234. return;
  11235. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  11236. const Expr *MagicValueExpr = VD->getInit();
  11237. if (!MagicValueExpr) {
  11238. continue;
  11239. }
  11240. llvm::APSInt MagicValueInt;
  11241. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  11242. Diag(I->getRange().getBegin(),
  11243. diag::err_type_tag_for_datatype_not_ice)
  11244. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11245. continue;
  11246. }
  11247. if (MagicValueInt.getActiveBits() > 64) {
  11248. Diag(I->getRange().getBegin(),
  11249. diag::err_type_tag_for_datatype_too_large)
  11250. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11251. continue;
  11252. }
  11253. uint64_t MagicValue = MagicValueInt.getZExtValue();
  11254. RegisterTypeTagForDatatype(I->getArgumentKind(),
  11255. MagicValue,
  11256. I->getMatchingCType(),
  11257. I->getLayoutCompatible(),
  11258. I->getMustBeNull());
  11259. }
  11260. }
  11261. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  11262. auto *VD = dyn_cast<VarDecl>(DD);
  11263. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  11264. }
  11265. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  11266. ArrayRef<Decl *> Group) {
  11267. SmallVector<Decl*, 8> Decls;
  11268. if (DS.isTypeSpecOwned())
  11269. Decls.push_back(DS.getRepAsDecl());
  11270. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  11271. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  11272. bool DiagnosedMultipleDecomps = false;
  11273. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  11274. bool DiagnosedNonDeducedAuto = false;
  11275. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11276. if (Decl *D = Group[i]) {
  11277. // For declarators, there are some additional syntactic-ish checks we need
  11278. // to perform.
  11279. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  11280. if (!FirstDeclaratorInGroup)
  11281. FirstDeclaratorInGroup = DD;
  11282. if (!FirstDecompDeclaratorInGroup)
  11283. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  11284. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  11285. !hasDeducedAuto(DD))
  11286. FirstNonDeducedAutoInGroup = DD;
  11287. if (FirstDeclaratorInGroup != DD) {
  11288. // A decomposition declaration cannot be combined with any other
  11289. // declaration in the same group.
  11290. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  11291. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  11292. diag::err_decomp_decl_not_alone)
  11293. << FirstDeclaratorInGroup->getSourceRange()
  11294. << DD->getSourceRange();
  11295. DiagnosedMultipleDecomps = true;
  11296. }
  11297. // A declarator that uses 'auto' in any way other than to declare a
  11298. // variable with a deduced type cannot be combined with any other
  11299. // declarator in the same group.
  11300. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  11301. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  11302. diag::err_auto_non_deduced_not_alone)
  11303. << FirstNonDeducedAutoInGroup->getType()
  11304. ->hasAutoForTrailingReturnType()
  11305. << FirstDeclaratorInGroup->getSourceRange()
  11306. << DD->getSourceRange();
  11307. DiagnosedNonDeducedAuto = true;
  11308. }
  11309. }
  11310. }
  11311. Decls.push_back(D);
  11312. }
  11313. }
  11314. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  11315. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  11316. handleTagNumbering(Tag, S);
  11317. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  11318. getLangOpts().CPlusPlus)
  11319. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  11320. }
  11321. }
  11322. return BuildDeclaratorGroup(Decls);
  11323. }
  11324. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  11325. /// group, performing any necessary semantic checking.
  11326. Sema::DeclGroupPtrTy
  11327. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  11328. // C++14 [dcl.spec.auto]p7: (DR1347)
  11329. // If the type that replaces the placeholder type is not the same in each
  11330. // deduction, the program is ill-formed.
  11331. if (Group.size() > 1) {
  11332. QualType Deduced;
  11333. VarDecl *DeducedDecl = nullptr;
  11334. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11335. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  11336. if (!D || D->isInvalidDecl())
  11337. break;
  11338. DeducedType *DT = D->getType()->getContainedDeducedType();
  11339. if (!DT || DT->getDeducedType().isNull())
  11340. continue;
  11341. if (Deduced.isNull()) {
  11342. Deduced = DT->getDeducedType();
  11343. DeducedDecl = D;
  11344. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  11345. auto *AT = dyn_cast<AutoType>(DT);
  11346. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  11347. diag::err_auto_different_deductions)
  11348. << (AT ? (unsigned)AT->getKeyword() : 3)
  11349. << Deduced << DeducedDecl->getDeclName()
  11350. << DT->getDeducedType() << D->getDeclName()
  11351. << DeducedDecl->getInit()->getSourceRange()
  11352. << D->getInit()->getSourceRange();
  11353. D->setInvalidDecl();
  11354. break;
  11355. }
  11356. }
  11357. }
  11358. ActOnDocumentableDecls(Group);
  11359. return DeclGroupPtrTy::make(
  11360. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  11361. }
  11362. void Sema::ActOnDocumentableDecl(Decl *D) {
  11363. ActOnDocumentableDecls(D);
  11364. }
  11365. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  11366. // Don't parse the comment if Doxygen diagnostics are ignored.
  11367. if (Group.empty() || !Group[0])
  11368. return;
  11369. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  11370. Group[0]->getLocation()) &&
  11371. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  11372. Group[0]->getLocation()))
  11373. return;
  11374. if (Group.size() >= 2) {
  11375. // This is a decl group. Normally it will contain only declarations
  11376. // produced from declarator list. But in case we have any definitions or
  11377. // additional declaration references:
  11378. // 'typedef struct S {} S;'
  11379. // 'typedef struct S *S;'
  11380. // 'struct S *pS;'
  11381. // FinalizeDeclaratorGroup adds these as separate declarations.
  11382. Decl *MaybeTagDecl = Group[0];
  11383. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  11384. Group = Group.slice(1);
  11385. }
  11386. }
  11387. // FIMXE: We assume every Decl in the group is in the same file.
  11388. // This is false when preprocessor constructs the group from decls in
  11389. // different files (e. g. macros or #include).
  11390. Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
  11391. }
  11392. /// Common checks for a parameter-declaration that should apply to both function
  11393. /// parameters and non-type template parameters.
  11394. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  11395. // Check that there are no default arguments inside the type of this
  11396. // parameter.
  11397. if (getLangOpts().CPlusPlus)
  11398. CheckExtraCXXDefaultArguments(D);
  11399. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11400. if (D.getCXXScopeSpec().isSet()) {
  11401. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11402. << D.getCXXScopeSpec().getRange();
  11403. }
  11404. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  11405. // simple identifier except [...irrelevant cases...].
  11406. switch (D.getName().getKind()) {
  11407. case UnqualifiedIdKind::IK_Identifier:
  11408. break;
  11409. case UnqualifiedIdKind::IK_OperatorFunctionId:
  11410. case UnqualifiedIdKind::IK_ConversionFunctionId:
  11411. case UnqualifiedIdKind::IK_LiteralOperatorId:
  11412. case UnqualifiedIdKind::IK_ConstructorName:
  11413. case UnqualifiedIdKind::IK_DestructorName:
  11414. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  11415. case UnqualifiedIdKind::IK_DeductionGuideName:
  11416. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11417. << GetNameForDeclarator(D).getName();
  11418. break;
  11419. case UnqualifiedIdKind::IK_TemplateId:
  11420. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  11421. // GetNameForDeclarator would not produce a useful name in this case.
  11422. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  11423. break;
  11424. }
  11425. }
  11426. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  11427. /// to introduce parameters into function prototype scope.
  11428. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  11429. const DeclSpec &DS = D.getDeclSpec();
  11430. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  11431. // C++03 [dcl.stc]p2 also permits 'auto'.
  11432. StorageClass SC = SC_None;
  11433. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  11434. SC = SC_Register;
  11435. // In C++11, the 'register' storage class specifier is deprecated.
  11436. // In C++17, it is not allowed, but we tolerate it as an extension.
  11437. if (getLangOpts().CPlusPlus11) {
  11438. Diag(DS.getStorageClassSpecLoc(),
  11439. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11440. : diag::warn_deprecated_register)
  11441. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11442. }
  11443. } else if (getLangOpts().CPlusPlus &&
  11444. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11445. SC = SC_Auto;
  11446. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11447. Diag(DS.getStorageClassSpecLoc(),
  11448. diag::err_invalid_storage_class_in_func_decl);
  11449. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11450. }
  11451. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11452. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11453. << DeclSpec::getSpecifierName(TSCS);
  11454. if (DS.isInlineSpecified())
  11455. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11456. << getLangOpts().CPlusPlus17;
  11457. if (DS.hasConstexprSpecifier())
  11458. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11459. << 0 << D.getDeclSpec().getConstexprSpecifier();
  11460. DiagnoseFunctionSpecifiers(DS);
  11461. CheckFunctionOrTemplateParamDeclarator(S, D);
  11462. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11463. QualType parmDeclType = TInfo->getType();
  11464. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11465. IdentifierInfo *II = D.getIdentifier();
  11466. if (II) {
  11467. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11468. ForVisibleRedeclaration);
  11469. LookupName(R, S);
  11470. if (R.isSingleResult()) {
  11471. NamedDecl *PrevDecl = R.getFoundDecl();
  11472. if (PrevDecl->isTemplateParameter()) {
  11473. // Maybe we will complain about the shadowed template parameter.
  11474. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11475. // Just pretend that we didn't see the previous declaration.
  11476. PrevDecl = nullptr;
  11477. } else if (S->isDeclScope(PrevDecl)) {
  11478. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11479. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11480. // Recover by removing the name
  11481. II = nullptr;
  11482. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11483. D.setInvalidType(true);
  11484. }
  11485. }
  11486. }
  11487. // Temporarily put parameter variables in the translation unit, not
  11488. // the enclosing context. This prevents them from accidentally
  11489. // looking like class members in C++.
  11490. ParmVarDecl *New =
  11491. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11492. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11493. if (D.isInvalidType())
  11494. New->setInvalidDecl();
  11495. assert(S->isFunctionPrototypeScope());
  11496. assert(S->getFunctionPrototypeDepth() >= 1);
  11497. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11498. S->getNextFunctionPrototypeIndex());
  11499. // Add the parameter declaration into this scope.
  11500. S->AddDecl(New);
  11501. if (II)
  11502. IdResolver.AddDecl(New);
  11503. ProcessDeclAttributes(S, New, D);
  11504. if (D.getDeclSpec().isModulePrivateSpecified())
  11505. Diag(New->getLocation(), diag::err_module_private_local)
  11506. << 1 << New->getDeclName()
  11507. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11508. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11509. if (New->hasAttr<BlocksAttr>()) {
  11510. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11511. }
  11512. return New;
  11513. }
  11514. /// Synthesizes a variable for a parameter arising from a
  11515. /// typedef.
  11516. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11517. SourceLocation Loc,
  11518. QualType T) {
  11519. /* FIXME: setting StartLoc == Loc.
  11520. Would it be worth to modify callers so as to provide proper source
  11521. location for the unnamed parameters, embedding the parameter's type? */
  11522. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11523. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11524. SC_None, nullptr);
  11525. Param->setImplicit();
  11526. return Param;
  11527. }
  11528. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11529. // Don't diagnose unused-parameter errors in template instantiations; we
  11530. // will already have done so in the template itself.
  11531. if (inTemplateInstantiation())
  11532. return;
  11533. for (const ParmVarDecl *Parameter : Parameters) {
  11534. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11535. !Parameter->hasAttr<UnusedAttr>()) {
  11536. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11537. << Parameter->getDeclName();
  11538. }
  11539. }
  11540. }
  11541. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11542. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11543. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11544. return;
  11545. // Warn if the return value is pass-by-value and larger than the specified
  11546. // threshold.
  11547. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11548. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11549. if (Size > LangOpts.NumLargeByValueCopy)
  11550. Diag(D->getLocation(), diag::warn_return_value_size)
  11551. << D->getDeclName() << Size;
  11552. }
  11553. // Warn if any parameter is pass-by-value and larger than the specified
  11554. // threshold.
  11555. for (const ParmVarDecl *Parameter : Parameters) {
  11556. QualType T = Parameter->getType();
  11557. if (T->isDependentType() || !T.isPODType(Context))
  11558. continue;
  11559. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11560. if (Size > LangOpts.NumLargeByValueCopy)
  11561. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11562. << Parameter->getDeclName() << Size;
  11563. }
  11564. }
  11565. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11566. SourceLocation NameLoc, IdentifierInfo *Name,
  11567. QualType T, TypeSourceInfo *TSInfo,
  11568. StorageClass SC) {
  11569. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11570. if (getLangOpts().ObjCAutoRefCount &&
  11571. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11572. T->isObjCLifetimeType()) {
  11573. Qualifiers::ObjCLifetime lifetime;
  11574. // Special cases for arrays:
  11575. // - if it's const, use __unsafe_unretained
  11576. // - otherwise, it's an error
  11577. if (T->isArrayType()) {
  11578. if (!T.isConstQualified()) {
  11579. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11580. DelayedDiagnostics.add(
  11581. sema::DelayedDiagnostic::makeForbiddenType(
  11582. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11583. else
  11584. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11585. << TSInfo->getTypeLoc().getSourceRange();
  11586. }
  11587. lifetime = Qualifiers::OCL_ExplicitNone;
  11588. } else {
  11589. lifetime = T->getObjCARCImplicitLifetime();
  11590. }
  11591. T = Context.getLifetimeQualifiedType(T, lifetime);
  11592. }
  11593. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11594. Context.getAdjustedParameterType(T),
  11595. TSInfo, SC, nullptr);
  11596. // Make a note if we created a new pack in the scope of a lambda, so that
  11597. // we know that references to that pack must also be expanded within the
  11598. // lambda scope.
  11599. if (New->isParameterPack())
  11600. if (auto *LSI = getEnclosingLambda())
  11601. LSI->LocalPacks.push_back(New);
  11602. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  11603. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11604. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  11605. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  11606. // Parameters can not be abstract class types.
  11607. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11608. // the class has been completely parsed.
  11609. if (!CurContext->isRecord() &&
  11610. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11611. AbstractParamType))
  11612. New->setInvalidDecl();
  11613. // Parameter declarators cannot be interface types. All ObjC objects are
  11614. // passed by reference.
  11615. if (T->isObjCObjectType()) {
  11616. SourceLocation TypeEndLoc =
  11617. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11618. Diag(NameLoc,
  11619. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11620. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11621. T = Context.getObjCObjectPointerType(T);
  11622. New->setType(T);
  11623. }
  11624. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11625. // duration shall not be qualified by an address-space qualifier."
  11626. // Since all parameters have automatic store duration, they can not have
  11627. // an address space.
  11628. if (T.getAddressSpace() != LangAS::Default &&
  11629. // OpenCL allows function arguments declared to be an array of a type
  11630. // to be qualified with an address space.
  11631. !(getLangOpts().OpenCL &&
  11632. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11633. Diag(NameLoc, diag::err_arg_with_address_space);
  11634. New->setInvalidDecl();
  11635. }
  11636. return New;
  11637. }
  11638. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11639. SourceLocation LocAfterDecls) {
  11640. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11641. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11642. // for a K&R function.
  11643. if (!FTI.hasPrototype) {
  11644. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11645. --i;
  11646. if (FTI.Params[i].Param == nullptr) {
  11647. SmallString<256> Code;
  11648. llvm::raw_svector_ostream(Code)
  11649. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11650. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11651. << FTI.Params[i].Ident
  11652. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11653. // Implicitly declare the argument as type 'int' for lack of a better
  11654. // type.
  11655. AttributeFactory attrs;
  11656. DeclSpec DS(attrs);
  11657. const char* PrevSpec; // unused
  11658. unsigned DiagID; // unused
  11659. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11660. DiagID, Context.getPrintingPolicy());
  11661. // Use the identifier location for the type source range.
  11662. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11663. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11664. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11665. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11666. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11667. }
  11668. }
  11669. }
  11670. }
  11671. Decl *
  11672. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11673. MultiTemplateParamsArg TemplateParameterLists,
  11674. SkipBodyInfo *SkipBody) {
  11675. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11676. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11677. Scope *ParentScope = FnBodyScope->getParent();
  11678. D.setFunctionDefinitionKind(FDK_Definition);
  11679. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11680. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11681. }
  11682. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11683. Consumer.HandleInlineFunctionDefinition(D);
  11684. }
  11685. static bool
  11686. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11687. const FunctionDecl *&PossiblePrototype) {
  11688. // Don't warn about invalid declarations.
  11689. if (FD->isInvalidDecl())
  11690. return false;
  11691. // Or declarations that aren't global.
  11692. if (!FD->isGlobal())
  11693. return false;
  11694. // Don't warn about C++ member functions.
  11695. if (isa<CXXMethodDecl>(FD))
  11696. return false;
  11697. // Don't warn about 'main'.
  11698. if (FD->isMain())
  11699. return false;
  11700. // Don't warn about inline functions.
  11701. if (FD->isInlined())
  11702. return false;
  11703. // Don't warn about function templates.
  11704. if (FD->getDescribedFunctionTemplate())
  11705. return false;
  11706. // Don't warn about function template specializations.
  11707. if (FD->isFunctionTemplateSpecialization())
  11708. return false;
  11709. // Don't warn for OpenCL kernels.
  11710. if (FD->hasAttr<OpenCLKernelAttr>())
  11711. return false;
  11712. // Don't warn on explicitly deleted functions.
  11713. if (FD->isDeleted())
  11714. return false;
  11715. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11716. Prev; Prev = Prev->getPreviousDecl()) {
  11717. // Ignore any declarations that occur in function or method
  11718. // scope, because they aren't visible from the header.
  11719. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11720. continue;
  11721. PossiblePrototype = Prev;
  11722. return Prev->getType()->isFunctionNoProtoType();
  11723. }
  11724. return true;
  11725. }
  11726. void
  11727. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11728. const FunctionDecl *EffectiveDefinition,
  11729. SkipBodyInfo *SkipBody) {
  11730. const FunctionDecl *Definition = EffectiveDefinition;
  11731. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11732. // If this is a friend function defined in a class template, it does not
  11733. // have a body until it is used, nevertheless it is a definition, see
  11734. // [temp.inst]p2:
  11735. //
  11736. // ... for the purpose of determining whether an instantiated redeclaration
  11737. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11738. // corresponds to a definition in the template is considered to be a
  11739. // definition.
  11740. //
  11741. // The following code must produce redefinition error:
  11742. //
  11743. // template<typename T> struct C20 { friend void func_20() {} };
  11744. // C20<int> c20i;
  11745. // void func_20() {}
  11746. //
  11747. for (auto I : FD->redecls()) {
  11748. if (I != FD && !I->isInvalidDecl() &&
  11749. I->getFriendObjectKind() != Decl::FOK_None) {
  11750. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11751. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11752. // A merged copy of the same function, instantiated as a member of
  11753. // the same class, is OK.
  11754. if (declaresSameEntity(OrigFD, Original) &&
  11755. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11756. cast<Decl>(FD->getLexicalDeclContext())))
  11757. continue;
  11758. }
  11759. if (Original->isThisDeclarationADefinition()) {
  11760. Definition = I;
  11761. break;
  11762. }
  11763. }
  11764. }
  11765. }
  11766. }
  11767. if (!Definition)
  11768. // Similar to friend functions a friend function template may be a
  11769. // definition and do not have a body if it is instantiated in a class
  11770. // template.
  11771. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11772. for (auto I : FTD->redecls()) {
  11773. auto D = cast<FunctionTemplateDecl>(I);
  11774. if (D != FTD) {
  11775. assert(!D->isThisDeclarationADefinition() &&
  11776. "More than one definition in redeclaration chain");
  11777. if (D->getFriendObjectKind() != Decl::FOK_None)
  11778. if (FunctionTemplateDecl *FT =
  11779. D->getInstantiatedFromMemberTemplate()) {
  11780. if (FT->isThisDeclarationADefinition()) {
  11781. Definition = D->getTemplatedDecl();
  11782. break;
  11783. }
  11784. }
  11785. }
  11786. }
  11787. }
  11788. if (!Definition)
  11789. return;
  11790. if (canRedefineFunction(Definition, getLangOpts()))
  11791. return;
  11792. // Don't emit an error when this is redefinition of a typo-corrected
  11793. // definition.
  11794. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11795. return;
  11796. // If we don't have a visible definition of the function, and it's inline or
  11797. // a template, skip the new definition.
  11798. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11799. (Definition->getFormalLinkage() == InternalLinkage ||
  11800. Definition->isInlined() ||
  11801. Definition->getDescribedFunctionTemplate() ||
  11802. Definition->getNumTemplateParameterLists())) {
  11803. SkipBody->ShouldSkip = true;
  11804. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11805. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11806. makeMergedDefinitionVisible(TD);
  11807. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11808. return;
  11809. }
  11810. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11811. Definition->getStorageClass() == SC_Extern)
  11812. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11813. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11814. else
  11815. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11816. Diag(Definition->getLocation(), diag::note_previous_definition);
  11817. FD->setInvalidDecl();
  11818. }
  11819. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11820. Sema &S) {
  11821. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11822. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11823. LSI->CallOperator = CallOperator;
  11824. LSI->Lambda = LambdaClass;
  11825. LSI->ReturnType = CallOperator->getReturnType();
  11826. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11827. if (LCD == LCD_None)
  11828. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11829. else if (LCD == LCD_ByCopy)
  11830. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11831. else if (LCD == LCD_ByRef)
  11832. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11833. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11834. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11835. LSI->Mutable = !CallOperator->isConst();
  11836. // Add the captures to the LSI so they can be noted as already
  11837. // captured within tryCaptureVar.
  11838. auto I = LambdaClass->field_begin();
  11839. for (const auto &C : LambdaClass->captures()) {
  11840. if (C.capturesVariable()) {
  11841. VarDecl *VD = C.getCapturedVar();
  11842. if (VD->isInitCapture())
  11843. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11844. QualType CaptureType = VD->getType();
  11845. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11846. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11847. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11848. /*EllipsisLoc*/C.isPackExpansion()
  11849. ? C.getEllipsisLoc() : SourceLocation(),
  11850. CaptureType, /*Invalid*/false);
  11851. } else if (C.capturesThis()) {
  11852. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11853. C.getCaptureKind() == LCK_StarThis);
  11854. } else {
  11855. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11856. I->getType());
  11857. }
  11858. ++I;
  11859. }
  11860. }
  11861. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11862. SkipBodyInfo *SkipBody) {
  11863. if (!D) {
  11864. // Parsing the function declaration failed in some way. Push on a fake scope
  11865. // anyway so we can try to parse the function body.
  11866. PushFunctionScope();
  11867. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11868. return D;
  11869. }
  11870. FunctionDecl *FD = nullptr;
  11871. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11872. FD = FunTmpl->getTemplatedDecl();
  11873. else
  11874. FD = cast<FunctionDecl>(D);
  11875. // Do not push if it is a lambda because one is already pushed when building
  11876. // the lambda in ActOnStartOfLambdaDefinition().
  11877. if (!isLambdaCallOperator(FD))
  11878. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11879. // Check for defining attributes before the check for redefinition.
  11880. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11881. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11882. FD->dropAttr<AliasAttr>();
  11883. FD->setInvalidDecl();
  11884. }
  11885. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11886. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11887. FD->dropAttr<IFuncAttr>();
  11888. FD->setInvalidDecl();
  11889. }
  11890. // See if this is a redefinition. If 'will have body' is already set, then
  11891. // these checks were already performed when it was set.
  11892. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11893. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11894. // If we're skipping the body, we're done. Don't enter the scope.
  11895. if (SkipBody && SkipBody->ShouldSkip)
  11896. return D;
  11897. }
  11898. // Mark this function as "will have a body eventually". This lets users to
  11899. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11900. // this function.
  11901. FD->setWillHaveBody();
  11902. // If we are instantiating a generic lambda call operator, push
  11903. // a LambdaScopeInfo onto the function stack. But use the information
  11904. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11905. // LambdaScopeInfo.
  11906. // When the template operator is being specialized, the LambdaScopeInfo,
  11907. // has to be properly restored so that tryCaptureVariable doesn't try
  11908. // and capture any new variables. In addition when calculating potential
  11909. // captures during transformation of nested lambdas, it is necessary to
  11910. // have the LSI properly restored.
  11911. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11912. assert(inTemplateInstantiation() &&
  11913. "There should be an active template instantiation on the stack "
  11914. "when instantiating a generic lambda!");
  11915. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11916. } else {
  11917. // Enter a new function scope
  11918. PushFunctionScope();
  11919. }
  11920. // Builtin functions cannot be defined.
  11921. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11922. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11923. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11924. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11925. FD->setInvalidDecl();
  11926. }
  11927. }
  11928. // The return type of a function definition must be complete
  11929. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11930. QualType ResultType = FD->getReturnType();
  11931. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11932. !FD->isInvalidDecl() &&
  11933. RequireCompleteType(FD->getLocation(), ResultType,
  11934. diag::err_func_def_incomplete_result))
  11935. FD->setInvalidDecl();
  11936. if (FnBodyScope)
  11937. PushDeclContext(FnBodyScope, FD);
  11938. // Check the validity of our function parameters
  11939. CheckParmsForFunctionDef(FD->parameters(),
  11940. /*CheckParameterNames=*/true);
  11941. // Add non-parameter declarations already in the function to the current
  11942. // scope.
  11943. if (FnBodyScope) {
  11944. for (Decl *NPD : FD->decls()) {
  11945. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11946. if (!NonParmDecl)
  11947. continue;
  11948. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11949. "parameters should not be in newly created FD yet");
  11950. // If the decl has a name, make it accessible in the current scope.
  11951. if (NonParmDecl->getDeclName())
  11952. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11953. // Similarly, dive into enums and fish their constants out, making them
  11954. // accessible in this scope.
  11955. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11956. for (auto *EI : ED->enumerators())
  11957. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11958. }
  11959. }
  11960. }
  11961. // Introduce our parameters into the function scope
  11962. for (auto Param : FD->parameters()) {
  11963. Param->setOwningFunction(FD);
  11964. // If this has an identifier, add it to the scope stack.
  11965. if (Param->getIdentifier() && FnBodyScope) {
  11966. CheckShadow(FnBodyScope, Param);
  11967. PushOnScopeChains(Param, FnBodyScope);
  11968. }
  11969. }
  11970. // Ensure that the function's exception specification is instantiated.
  11971. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11972. ResolveExceptionSpec(D->getLocation(), FPT);
  11973. // dllimport cannot be applied to non-inline function definitions.
  11974. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11975. !FD->isTemplateInstantiation()) {
  11976. assert(!FD->hasAttr<DLLExportAttr>());
  11977. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11978. FD->setInvalidDecl();
  11979. return D;
  11980. }
  11981. // We want to attach documentation to original Decl (which might be
  11982. // a function template).
  11983. ActOnDocumentableDecl(D);
  11984. if (getCurLexicalContext()->isObjCContainer() &&
  11985. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11986. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11987. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11988. return D;
  11989. }
  11990. /// Given the set of return statements within a function body,
  11991. /// compute the variables that are subject to the named return value
  11992. /// optimization.
  11993. ///
  11994. /// Each of the variables that is subject to the named return value
  11995. /// optimization will be marked as NRVO variables in the AST, and any
  11996. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11997. /// use the named return value optimization.
  11998. ///
  11999. /// This function applies a very simplistic algorithm for NRVO: if every return
  12000. /// statement in the scope of a variable has the same NRVO candidate, that
  12001. /// candidate is an NRVO variable.
  12002. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  12003. ReturnStmt **Returns = Scope->Returns.data();
  12004. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  12005. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  12006. if (!NRVOCandidate->isNRVOVariable())
  12007. Returns[I]->setNRVOCandidate(nullptr);
  12008. }
  12009. }
  12010. }
  12011. bool Sema::canDelayFunctionBody(const Declarator &D) {
  12012. // We can't delay parsing the body of a constexpr function template (yet).
  12013. if (D.getDeclSpec().hasConstexprSpecifier())
  12014. return false;
  12015. // We can't delay parsing the body of a function template with a deduced
  12016. // return type (yet).
  12017. if (D.getDeclSpec().hasAutoTypeSpec()) {
  12018. // If the placeholder introduces a non-deduced trailing return type,
  12019. // we can still delay parsing it.
  12020. if (D.getNumTypeObjects()) {
  12021. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  12022. if (Outer.Kind == DeclaratorChunk::Function &&
  12023. Outer.Fun.hasTrailingReturnType()) {
  12024. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  12025. return Ty.isNull() || !Ty->isUndeducedType();
  12026. }
  12027. }
  12028. return false;
  12029. }
  12030. return true;
  12031. }
  12032. bool Sema::canSkipFunctionBody(Decl *D) {
  12033. // We cannot skip the body of a function (or function template) which is
  12034. // constexpr, since we may need to evaluate its body in order to parse the
  12035. // rest of the file.
  12036. // We cannot skip the body of a function with an undeduced return type,
  12037. // because any callers of that function need to know the type.
  12038. if (const FunctionDecl *FD = D->getAsFunction()) {
  12039. if (FD->isConstexpr())
  12040. return false;
  12041. // We can't simply call Type::isUndeducedType here, because inside template
  12042. // auto can be deduced to a dependent type, which is not considered
  12043. // "undeduced".
  12044. if (FD->getReturnType()->getContainedDeducedType())
  12045. return false;
  12046. }
  12047. return Consumer.shouldSkipFunctionBody(D);
  12048. }
  12049. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  12050. if (!Decl)
  12051. return nullptr;
  12052. if (FunctionDecl *FD = Decl->getAsFunction())
  12053. FD->setHasSkippedBody();
  12054. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  12055. MD->setHasSkippedBody();
  12056. return Decl;
  12057. }
  12058. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  12059. return ActOnFinishFunctionBody(D, BodyArg, false);
  12060. }
  12061. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  12062. /// body.
  12063. class ExitFunctionBodyRAII {
  12064. public:
  12065. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  12066. ~ExitFunctionBodyRAII() {
  12067. if (!IsLambda)
  12068. S.PopExpressionEvaluationContext();
  12069. }
  12070. private:
  12071. Sema &S;
  12072. bool IsLambda = false;
  12073. };
  12074. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  12075. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  12076. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  12077. if (EscapeInfo.count(BD))
  12078. return EscapeInfo[BD];
  12079. bool R = false;
  12080. const BlockDecl *CurBD = BD;
  12081. do {
  12082. R = !CurBD->doesNotEscape();
  12083. if (R)
  12084. break;
  12085. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  12086. } while (CurBD);
  12087. return EscapeInfo[BD] = R;
  12088. };
  12089. // If the location where 'self' is implicitly retained is inside a escaping
  12090. // block, emit a diagnostic.
  12091. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  12092. S.ImplicitlyRetainedSelfLocs)
  12093. if (IsOrNestedInEscapingBlock(P.second))
  12094. S.Diag(P.first, diag::warn_implicitly_retains_self)
  12095. << FixItHint::CreateInsertion(P.first, "self->");
  12096. }
  12097. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  12098. bool IsInstantiation) {
  12099. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  12100. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12101. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  12102. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  12103. CheckCompletedCoroutineBody(FD, Body);
  12104. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  12105. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  12106. // meant to pop the context added in ActOnStartOfFunctionDef().
  12107. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  12108. if (FD) {
  12109. FD->setBody(Body);
  12110. FD->setWillHaveBody(false);
  12111. if (getLangOpts().CPlusPlus14) {
  12112. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  12113. FD->getReturnType()->isUndeducedType()) {
  12114. // If the function has a deduced result type but contains no 'return'
  12115. // statements, the result type as written must be exactly 'auto', and
  12116. // the deduced result type is 'void'.
  12117. if (!FD->getReturnType()->getAs<AutoType>()) {
  12118. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  12119. << FD->getReturnType();
  12120. FD->setInvalidDecl();
  12121. } else {
  12122. // Substitute 'void' for the 'auto' in the type.
  12123. TypeLoc ResultType = getReturnTypeLoc(FD);
  12124. Context.adjustDeducedFunctionResultType(
  12125. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  12126. }
  12127. }
  12128. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  12129. // In C++11, we don't use 'auto' deduction rules for lambda call
  12130. // operators because we don't support return type deduction.
  12131. auto *LSI = getCurLambda();
  12132. if (LSI->HasImplicitReturnType) {
  12133. deduceClosureReturnType(*LSI);
  12134. // C++11 [expr.prim.lambda]p4:
  12135. // [...] if there are no return statements in the compound-statement
  12136. // [the deduced type is] the type void
  12137. QualType RetType =
  12138. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  12139. // Update the return type to the deduced type.
  12140. const FunctionProtoType *Proto =
  12141. FD->getType()->getAs<FunctionProtoType>();
  12142. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  12143. Proto->getExtProtoInfo()));
  12144. }
  12145. }
  12146. // If the function implicitly returns zero (like 'main') or is naked,
  12147. // don't complain about missing return statements.
  12148. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  12149. WP.disableCheckFallThrough();
  12150. // MSVC permits the use of pure specifier (=0) on function definition,
  12151. // defined at class scope, warn about this non-standard construct.
  12152. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  12153. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  12154. if (!FD->isInvalidDecl()) {
  12155. // Don't diagnose unused parameters of defaulted or deleted functions.
  12156. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  12157. DiagnoseUnusedParameters(FD->parameters());
  12158. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  12159. FD->getReturnType(), FD);
  12160. // If this is a structor, we need a vtable.
  12161. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  12162. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  12163. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  12164. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  12165. // Try to apply the named return value optimization. We have to check
  12166. // if we can do this here because lambdas keep return statements around
  12167. // to deduce an implicit return type.
  12168. if (FD->getReturnType()->isRecordType() &&
  12169. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  12170. computeNRVO(Body, getCurFunction());
  12171. }
  12172. // GNU warning -Wmissing-prototypes:
  12173. // Warn if a global function is defined without a previous
  12174. // prototype declaration. This warning is issued even if the
  12175. // definition itself provides a prototype. The aim is to detect
  12176. // global functions that fail to be declared in header files.
  12177. const FunctionDecl *PossiblePrototype = nullptr;
  12178. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  12179. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  12180. if (PossiblePrototype) {
  12181. // We found a declaration that is not a prototype,
  12182. // but that could be a zero-parameter prototype
  12183. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  12184. TypeLoc TL = TI->getTypeLoc();
  12185. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  12186. Diag(PossiblePrototype->getLocation(),
  12187. diag::note_declaration_not_a_prototype)
  12188. << (FD->getNumParams() != 0)
  12189. << (FD->getNumParams() == 0
  12190. ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
  12191. : FixItHint{});
  12192. }
  12193. } else {
  12194. Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  12195. << /* function */ 1
  12196. << (FD->getStorageClass() == SC_None
  12197. ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
  12198. "static ")
  12199. : FixItHint{});
  12200. }
  12201. // GNU warning -Wstrict-prototypes
  12202. // Warn if K&R function is defined without a previous declaration.
  12203. // This warning is issued only if the definition itself does not provide
  12204. // a prototype. Only K&R definitions do not provide a prototype.
  12205. // An empty list in a function declarator that is part of a definition
  12206. // of that function specifies that the function has no parameters
  12207. // (C99 6.7.5.3p14)
  12208. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  12209. !LangOpts.CPlusPlus) {
  12210. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  12211. TypeLoc TL = TI->getTypeLoc();
  12212. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  12213. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  12214. }
  12215. }
  12216. // Warn on CPUDispatch with an actual body.
  12217. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  12218. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  12219. if (!CmpndBody->body_empty())
  12220. Diag(CmpndBody->body_front()->getBeginLoc(),
  12221. diag::warn_dispatch_body_ignored);
  12222. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  12223. const CXXMethodDecl *KeyFunction;
  12224. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  12225. MD->isVirtual() &&
  12226. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  12227. MD == KeyFunction->getCanonicalDecl()) {
  12228. // Update the key-function state if necessary for this ABI.
  12229. if (FD->isInlined() &&
  12230. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  12231. Context.setNonKeyFunction(MD);
  12232. // If the newly-chosen key function is already defined, then we
  12233. // need to mark the vtable as used retroactively.
  12234. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  12235. const FunctionDecl *Definition;
  12236. if (KeyFunction && KeyFunction->isDefined(Definition))
  12237. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  12238. } else {
  12239. // We just defined they key function; mark the vtable as used.
  12240. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  12241. }
  12242. }
  12243. }
  12244. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  12245. "Function parsing confused");
  12246. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  12247. assert(MD == getCurMethodDecl() && "Method parsing confused");
  12248. MD->setBody(Body);
  12249. if (!MD->isInvalidDecl()) {
  12250. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  12251. MD->getReturnType(), MD);
  12252. if (Body)
  12253. computeNRVO(Body, getCurFunction());
  12254. }
  12255. if (getCurFunction()->ObjCShouldCallSuper) {
  12256. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  12257. << MD->getSelector().getAsString();
  12258. getCurFunction()->ObjCShouldCallSuper = false;
  12259. }
  12260. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  12261. const ObjCMethodDecl *InitMethod = nullptr;
  12262. bool isDesignated =
  12263. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  12264. assert(isDesignated && InitMethod);
  12265. (void)isDesignated;
  12266. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  12267. auto IFace = MD->getClassInterface();
  12268. if (!IFace)
  12269. return false;
  12270. auto SuperD = IFace->getSuperClass();
  12271. if (!SuperD)
  12272. return false;
  12273. return SuperD->getIdentifier() ==
  12274. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  12275. };
  12276. // Don't issue this warning for unavailable inits or direct subclasses
  12277. // of NSObject.
  12278. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  12279. Diag(MD->getLocation(),
  12280. diag::warn_objc_designated_init_missing_super_call);
  12281. Diag(InitMethod->getLocation(),
  12282. diag::note_objc_designated_init_marked_here);
  12283. }
  12284. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  12285. }
  12286. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  12287. // Don't issue this warning for unavaialable inits.
  12288. if (!MD->isUnavailable())
  12289. Diag(MD->getLocation(),
  12290. diag::warn_objc_secondary_init_missing_init_call);
  12291. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  12292. }
  12293. diagnoseImplicitlyRetainedSelf(*this);
  12294. } else {
  12295. // Parsing the function declaration failed in some way. Pop the fake scope
  12296. // we pushed on.
  12297. PopFunctionScopeInfo(ActivePolicy, dcl);
  12298. return nullptr;
  12299. }
  12300. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12301. DiagnoseUnguardedAvailabilityViolations(dcl);
  12302. assert(!getCurFunction()->ObjCShouldCallSuper &&
  12303. "This should only be set for ObjC methods, which should have been "
  12304. "handled in the block above.");
  12305. // Verify and clean out per-function state.
  12306. if (Body && (!FD || !FD->isDefaulted())) {
  12307. // C++ constructors that have function-try-blocks can't have return
  12308. // statements in the handlers of that block. (C++ [except.handle]p14)
  12309. // Verify this.
  12310. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  12311. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  12312. // Verify that gotos and switch cases don't jump into scopes illegally.
  12313. if (getCurFunction()->NeedsScopeChecking() &&
  12314. !PP.isCodeCompletionEnabled())
  12315. DiagnoseInvalidJumps(Body);
  12316. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  12317. if (!Destructor->getParent()->isDependentType())
  12318. CheckDestructor(Destructor);
  12319. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12320. Destructor->getParent());
  12321. }
  12322. // If any errors have occurred, clear out any temporaries that may have
  12323. // been leftover. This ensures that these temporaries won't be picked up for
  12324. // deletion in some later function.
  12325. if (getDiagnostics().hasErrorOccurred() ||
  12326. getDiagnostics().getSuppressAllDiagnostics()) {
  12327. DiscardCleanupsInEvaluationContext();
  12328. }
  12329. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  12330. !isa<FunctionTemplateDecl>(dcl)) {
  12331. // Since the body is valid, issue any analysis-based warnings that are
  12332. // enabled.
  12333. ActivePolicy = &WP;
  12334. }
  12335. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  12336. !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
  12337. FD->setInvalidDecl();
  12338. if (FD && FD->hasAttr<NakedAttr>()) {
  12339. for (const Stmt *S : Body->children()) {
  12340. // Allow local register variables without initializer as they don't
  12341. // require prologue.
  12342. bool RegisterVariables = false;
  12343. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  12344. for (const auto *Decl : DS->decls()) {
  12345. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  12346. RegisterVariables =
  12347. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  12348. if (!RegisterVariables)
  12349. break;
  12350. }
  12351. }
  12352. }
  12353. if (RegisterVariables)
  12354. continue;
  12355. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  12356. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  12357. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  12358. FD->setInvalidDecl();
  12359. break;
  12360. }
  12361. }
  12362. }
  12363. assert(ExprCleanupObjects.size() ==
  12364. ExprEvalContexts.back().NumCleanupObjects &&
  12365. "Leftover temporaries in function");
  12366. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  12367. assert(MaybeODRUseExprs.empty() &&
  12368. "Leftover expressions for odr-use checking");
  12369. }
  12370. if (!IsInstantiation)
  12371. PopDeclContext();
  12372. PopFunctionScopeInfo(ActivePolicy, dcl);
  12373. // If any errors have occurred, clear out any temporaries that may have
  12374. // been leftover. This ensures that these temporaries won't be picked up for
  12375. // deletion in some later function.
  12376. if (getDiagnostics().hasErrorOccurred()) {
  12377. DiscardCleanupsInEvaluationContext();
  12378. }
  12379. return dcl;
  12380. }
  12381. /// When we finish delayed parsing of an attribute, we must attach it to the
  12382. /// relevant Decl.
  12383. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  12384. ParsedAttributes &Attrs) {
  12385. // Always attach attributes to the underlying decl.
  12386. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  12387. D = TD->getTemplatedDecl();
  12388. ProcessDeclAttributeList(S, D, Attrs);
  12389. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  12390. if (Method->isStatic())
  12391. checkThisInStaticMemberFunctionAttributes(Method);
  12392. }
  12393. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  12394. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  12395. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  12396. IdentifierInfo &II, Scope *S) {
  12397. // Find the scope in which the identifier is injected and the corresponding
  12398. // DeclContext.
  12399. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  12400. // In that case, we inject the declaration into the translation unit scope
  12401. // instead.
  12402. Scope *BlockScope = S;
  12403. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  12404. BlockScope = BlockScope->getParent();
  12405. Scope *ContextScope = BlockScope;
  12406. while (!ContextScope->getEntity())
  12407. ContextScope = ContextScope->getParent();
  12408. ContextRAII SavedContext(*this, ContextScope->getEntity());
  12409. // Before we produce a declaration for an implicitly defined
  12410. // function, see whether there was a locally-scoped declaration of
  12411. // this name as a function or variable. If so, use that
  12412. // (non-visible) declaration, and complain about it.
  12413. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  12414. if (ExternCPrev) {
  12415. // We still need to inject the function into the enclosing block scope so
  12416. // that later (non-call) uses can see it.
  12417. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  12418. // C89 footnote 38:
  12419. // If in fact it is not defined as having type "function returning int",
  12420. // the behavior is undefined.
  12421. if (!isa<FunctionDecl>(ExternCPrev) ||
  12422. !Context.typesAreCompatible(
  12423. cast<FunctionDecl>(ExternCPrev)->getType(),
  12424. Context.getFunctionNoProtoType(Context.IntTy))) {
  12425. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  12426. << ExternCPrev << !getLangOpts().C99;
  12427. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  12428. return ExternCPrev;
  12429. }
  12430. }
  12431. // Extension in C99. Legal in C90, but warn about it.
  12432. unsigned diag_id;
  12433. if (II.getName().startswith("__builtin_"))
  12434. diag_id = diag::warn_builtin_unknown;
  12435. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12436. else if (getLangOpts().OpenCL)
  12437. diag_id = diag::err_opencl_implicit_function_decl;
  12438. else if (getLangOpts().C99)
  12439. diag_id = diag::ext_implicit_function_decl;
  12440. else
  12441. diag_id = diag::warn_implicit_function_decl;
  12442. Diag(Loc, diag_id) << &II;
  12443. // If we found a prior declaration of this function, don't bother building
  12444. // another one. We've already pushed that one into scope, so there's nothing
  12445. // more to do.
  12446. if (ExternCPrev)
  12447. return ExternCPrev;
  12448. // Because typo correction is expensive, only do it if the implicit
  12449. // function declaration is going to be treated as an error.
  12450. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12451. TypoCorrection Corrected;
  12452. DeclFilterCCC<FunctionDecl> CCC{};
  12453. if (S && (Corrected =
  12454. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12455. S, nullptr, CCC, CTK_NonError)))
  12456. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12457. /*ErrorRecovery*/false);
  12458. }
  12459. // Set a Declarator for the implicit definition: int foo();
  12460. const char *Dummy;
  12461. AttributeFactory attrFactory;
  12462. DeclSpec DS(attrFactory);
  12463. unsigned DiagID;
  12464. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12465. Context.getPrintingPolicy());
  12466. (void)Error; // Silence warning.
  12467. assert(!Error && "Error setting up implicit decl!");
  12468. SourceLocation NoLoc;
  12469. Declarator D(DS, DeclaratorContext::BlockContext);
  12470. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12471. /*IsAmbiguous=*/false,
  12472. /*LParenLoc=*/NoLoc,
  12473. /*Params=*/nullptr,
  12474. /*NumParams=*/0,
  12475. /*EllipsisLoc=*/NoLoc,
  12476. /*RParenLoc=*/NoLoc,
  12477. /*RefQualifierIsLvalueRef=*/true,
  12478. /*RefQualifierLoc=*/NoLoc,
  12479. /*MutableLoc=*/NoLoc, EST_None,
  12480. /*ESpecRange=*/SourceRange(),
  12481. /*Exceptions=*/nullptr,
  12482. /*ExceptionRanges=*/nullptr,
  12483. /*NumExceptions=*/0,
  12484. /*NoexceptExpr=*/nullptr,
  12485. /*ExceptionSpecTokens=*/nullptr,
  12486. /*DeclsInPrototype=*/None, Loc,
  12487. Loc, D),
  12488. std::move(DS.getAttributes()), SourceLocation());
  12489. D.SetIdentifier(&II, Loc);
  12490. // Insert this function into the enclosing block scope.
  12491. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12492. FD->setImplicit();
  12493. AddKnownFunctionAttributes(FD);
  12494. return FD;
  12495. }
  12496. /// Adds any function attributes that we know a priori based on
  12497. /// the declaration of this function.
  12498. ///
  12499. /// These attributes can apply both to implicitly-declared builtins
  12500. /// (like __builtin___printf_chk) or to library-declared functions
  12501. /// like NSLog or printf.
  12502. ///
  12503. /// We need to check for duplicate attributes both here and where user-written
  12504. /// attributes are applied to declarations.
  12505. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12506. if (FD->isInvalidDecl())
  12507. return;
  12508. // If this is a built-in function, map its builtin attributes to
  12509. // actual attributes.
  12510. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12511. // Handle printf-formatting attributes.
  12512. unsigned FormatIdx;
  12513. bool HasVAListArg;
  12514. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12515. if (!FD->hasAttr<FormatAttr>()) {
  12516. const char *fmt = "printf";
  12517. unsigned int NumParams = FD->getNumParams();
  12518. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12519. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12520. fmt = "NSString";
  12521. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12522. &Context.Idents.get(fmt),
  12523. FormatIdx+1,
  12524. HasVAListArg ? 0 : FormatIdx+2,
  12525. FD->getLocation()));
  12526. }
  12527. }
  12528. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12529. HasVAListArg)) {
  12530. if (!FD->hasAttr<FormatAttr>())
  12531. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12532. &Context.Idents.get("scanf"),
  12533. FormatIdx+1,
  12534. HasVAListArg ? 0 : FormatIdx+2,
  12535. FD->getLocation()));
  12536. }
  12537. // Handle automatically recognized callbacks.
  12538. SmallVector<int, 4> Encoding;
  12539. if (!FD->hasAttr<CallbackAttr>() &&
  12540. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12541. FD->addAttr(CallbackAttr::CreateImplicit(
  12542. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12543. // Mark const if we don't care about errno and that is the only thing
  12544. // preventing the function from being const. This allows IRgen to use LLVM
  12545. // intrinsics for such functions.
  12546. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12547. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12548. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12549. // We make "fma" on some platforms const because we know it does not set
  12550. // errno in those environments even though it could set errno based on the
  12551. // C standard.
  12552. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12553. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12554. !FD->hasAttr<ConstAttr>()) {
  12555. switch (BuiltinID) {
  12556. case Builtin::BI__builtin_fma:
  12557. case Builtin::BI__builtin_fmaf:
  12558. case Builtin::BI__builtin_fmal:
  12559. case Builtin::BIfma:
  12560. case Builtin::BIfmaf:
  12561. case Builtin::BIfmal:
  12562. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12563. break;
  12564. default:
  12565. break;
  12566. }
  12567. }
  12568. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12569. !FD->hasAttr<ReturnsTwiceAttr>())
  12570. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12571. FD->getLocation()));
  12572. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12573. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12574. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12575. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12576. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12577. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12578. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12579. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12580. // Add the appropriate attribute, depending on the CUDA compilation mode
  12581. // and which target the builtin belongs to. For example, during host
  12582. // compilation, aux builtins are __device__, while the rest are __host__.
  12583. if (getLangOpts().CUDAIsDevice !=
  12584. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12585. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12586. else
  12587. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12588. }
  12589. }
  12590. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12591. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12592. // across.
  12593. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12594. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12595. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12596. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12597. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12598. }
  12599. IdentifierInfo *Name = FD->getIdentifier();
  12600. if (!Name)
  12601. return;
  12602. if ((!getLangOpts().CPlusPlus &&
  12603. FD->getDeclContext()->isTranslationUnit()) ||
  12604. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12605. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12606. LinkageSpecDecl::lang_c)) {
  12607. // Okay: this could be a libc/libm/Objective-C function we know
  12608. // about.
  12609. } else
  12610. return;
  12611. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12612. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12613. // target-specific builtins, perhaps?
  12614. if (!FD->hasAttr<FormatAttr>())
  12615. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12616. &Context.Idents.get("printf"), 2,
  12617. Name->isStr("vasprintf") ? 0 : 3,
  12618. FD->getLocation()));
  12619. }
  12620. if (Name->isStr("__CFStringMakeConstantString")) {
  12621. // We already have a __builtin___CFStringMakeConstantString,
  12622. // but builds that use -fno-constant-cfstrings don't go through that.
  12623. if (!FD->hasAttr<FormatArgAttr>())
  12624. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12625. FD->getLocation()));
  12626. }
  12627. }
  12628. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12629. TypeSourceInfo *TInfo) {
  12630. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12631. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12632. if (!TInfo) {
  12633. assert(D.isInvalidType() && "no declarator info for valid type");
  12634. TInfo = Context.getTrivialTypeSourceInfo(T);
  12635. }
  12636. // Scope manipulation handled by caller.
  12637. TypedefDecl *NewTD =
  12638. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12639. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12640. // Bail out immediately if we have an invalid declaration.
  12641. if (D.isInvalidType()) {
  12642. NewTD->setInvalidDecl();
  12643. return NewTD;
  12644. }
  12645. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12646. if (CurContext->isFunctionOrMethod())
  12647. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12648. << 2 << NewTD->getDeclName()
  12649. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12650. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12651. else
  12652. NewTD->setModulePrivate();
  12653. }
  12654. // C++ [dcl.typedef]p8:
  12655. // If the typedef declaration defines an unnamed class (or
  12656. // enum), the first typedef-name declared by the declaration
  12657. // to be that class type (or enum type) is used to denote the
  12658. // class type (or enum type) for linkage purposes only.
  12659. // We need to check whether the type was declared in the declaration.
  12660. switch (D.getDeclSpec().getTypeSpecType()) {
  12661. case TST_enum:
  12662. case TST_struct:
  12663. case TST_interface:
  12664. case TST_union:
  12665. case TST_class: {
  12666. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12667. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12668. break;
  12669. }
  12670. default:
  12671. break;
  12672. }
  12673. return NewTD;
  12674. }
  12675. /// Check that this is a valid underlying type for an enum declaration.
  12676. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12677. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12678. QualType T = TI->getType();
  12679. if (T->isDependentType())
  12680. return false;
  12681. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12682. if (BT->isInteger())
  12683. return false;
  12684. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12685. return true;
  12686. }
  12687. /// Check whether this is a valid redeclaration of a previous enumeration.
  12688. /// \return true if the redeclaration was invalid.
  12689. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12690. QualType EnumUnderlyingTy, bool IsFixed,
  12691. const EnumDecl *Prev) {
  12692. if (IsScoped != Prev->isScoped()) {
  12693. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12694. << Prev->isScoped();
  12695. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12696. return true;
  12697. }
  12698. if (IsFixed && Prev->isFixed()) {
  12699. if (!EnumUnderlyingTy->isDependentType() &&
  12700. !Prev->getIntegerType()->isDependentType() &&
  12701. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12702. Prev->getIntegerType())) {
  12703. // TODO: Highlight the underlying type of the redeclaration.
  12704. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12705. << EnumUnderlyingTy << Prev->getIntegerType();
  12706. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12707. << Prev->getIntegerTypeRange();
  12708. return true;
  12709. }
  12710. } else if (IsFixed != Prev->isFixed()) {
  12711. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12712. << Prev->isFixed();
  12713. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12714. return true;
  12715. }
  12716. return false;
  12717. }
  12718. /// Get diagnostic %select index for tag kind for
  12719. /// redeclaration diagnostic message.
  12720. /// WARNING: Indexes apply to particular diagnostics only!
  12721. ///
  12722. /// \returns diagnostic %select index.
  12723. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12724. switch (Tag) {
  12725. case TTK_Struct: return 0;
  12726. case TTK_Interface: return 1;
  12727. case TTK_Class: return 2;
  12728. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12729. }
  12730. }
  12731. /// Determine if tag kind is a class-key compatible with
  12732. /// class for redeclaration (class, struct, or __interface).
  12733. ///
  12734. /// \returns true iff the tag kind is compatible.
  12735. static bool isClassCompatTagKind(TagTypeKind Tag)
  12736. {
  12737. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12738. }
  12739. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12740. TagTypeKind TTK) {
  12741. if (isa<TypedefDecl>(PrevDecl))
  12742. return NTK_Typedef;
  12743. else if (isa<TypeAliasDecl>(PrevDecl))
  12744. return NTK_TypeAlias;
  12745. else if (isa<ClassTemplateDecl>(PrevDecl))
  12746. return NTK_Template;
  12747. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12748. return NTK_TypeAliasTemplate;
  12749. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12750. return NTK_TemplateTemplateArgument;
  12751. switch (TTK) {
  12752. case TTK_Struct:
  12753. case TTK_Interface:
  12754. case TTK_Class:
  12755. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12756. case TTK_Union:
  12757. return NTK_NonUnion;
  12758. case TTK_Enum:
  12759. return NTK_NonEnum;
  12760. }
  12761. llvm_unreachable("invalid TTK");
  12762. }
  12763. /// Determine whether a tag with a given kind is acceptable
  12764. /// as a redeclaration of the given tag declaration.
  12765. ///
  12766. /// \returns true if the new tag kind is acceptable, false otherwise.
  12767. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12768. TagTypeKind NewTag, bool isDefinition,
  12769. SourceLocation NewTagLoc,
  12770. const IdentifierInfo *Name) {
  12771. // C++ [dcl.type.elab]p3:
  12772. // The class-key or enum keyword present in the
  12773. // elaborated-type-specifier shall agree in kind with the
  12774. // declaration to which the name in the elaborated-type-specifier
  12775. // refers. This rule also applies to the form of
  12776. // elaborated-type-specifier that declares a class-name or
  12777. // friend class since it can be construed as referring to the
  12778. // definition of the class. Thus, in any
  12779. // elaborated-type-specifier, the enum keyword shall be used to
  12780. // refer to an enumeration (7.2), the union class-key shall be
  12781. // used to refer to a union (clause 9), and either the class or
  12782. // struct class-key shall be used to refer to a class (clause 9)
  12783. // declared using the class or struct class-key.
  12784. TagTypeKind OldTag = Previous->getTagKind();
  12785. if (OldTag != NewTag &&
  12786. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12787. return false;
  12788. // Tags are compatible, but we might still want to warn on mismatched tags.
  12789. // Non-class tags can't be mismatched at this point.
  12790. if (!isClassCompatTagKind(NewTag))
  12791. return true;
  12792. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12793. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12794. // declarations in system headers that are designed to be specialized, but if
  12795. // a user asks us to warn, we should warn if their code contains mismatched
  12796. // declarations.
  12797. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12798. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12799. Loc);
  12800. };
  12801. if (IsIgnoredLoc(NewTagLoc))
  12802. return true;
  12803. auto IsIgnored = [&](const TagDecl *Tag) {
  12804. return IsIgnoredLoc(Tag->getLocation());
  12805. };
  12806. while (IsIgnored(Previous)) {
  12807. Previous = Previous->getPreviousDecl();
  12808. if (!Previous)
  12809. return true;
  12810. OldTag = Previous->getTagKind();
  12811. }
  12812. bool isTemplate = false;
  12813. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12814. isTemplate = Record->getDescribedClassTemplate();
  12815. if (inTemplateInstantiation()) {
  12816. if (OldTag != NewTag) {
  12817. // In a template instantiation, do not offer fix-its for tag mismatches
  12818. // since they usually mess up the template instead of fixing the problem.
  12819. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12820. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12821. << getRedeclDiagFromTagKind(OldTag);
  12822. // FIXME: Note previous location?
  12823. }
  12824. return true;
  12825. }
  12826. if (isDefinition) {
  12827. // On definitions, check all previous tags and issue a fix-it for each
  12828. // one that doesn't match the current tag.
  12829. if (Previous->getDefinition()) {
  12830. // Don't suggest fix-its for redefinitions.
  12831. return true;
  12832. }
  12833. bool previousMismatch = false;
  12834. for (const TagDecl *I : Previous->redecls()) {
  12835. if (I->getTagKind() != NewTag) {
  12836. // Ignore previous declarations for which the warning was disabled.
  12837. if (IsIgnored(I))
  12838. continue;
  12839. if (!previousMismatch) {
  12840. previousMismatch = true;
  12841. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12842. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12843. << getRedeclDiagFromTagKind(I->getTagKind());
  12844. }
  12845. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12846. << getRedeclDiagFromTagKind(NewTag)
  12847. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12848. TypeWithKeyword::getTagTypeKindName(NewTag));
  12849. }
  12850. }
  12851. return true;
  12852. }
  12853. // Identify the prevailing tag kind: this is the kind of the definition (if
  12854. // there is a non-ignored definition), or otherwise the kind of the prior
  12855. // (non-ignored) declaration.
  12856. const TagDecl *PrevDef = Previous->getDefinition();
  12857. if (PrevDef && IsIgnored(PrevDef))
  12858. PrevDef = nullptr;
  12859. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12860. if (Redecl->getTagKind() != NewTag) {
  12861. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12862. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12863. << getRedeclDiagFromTagKind(OldTag);
  12864. Diag(Redecl->getLocation(), diag::note_previous_use);
  12865. // If there is a previous definition, suggest a fix-it.
  12866. if (PrevDef) {
  12867. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12868. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12869. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12870. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12871. }
  12872. }
  12873. return true;
  12874. }
  12875. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12876. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12877. /// This should provide the commented out code in the following snippet:
  12878. /// namespace N {
  12879. /// struct X;
  12880. /// namespace M {
  12881. /// struct Y { friend struct /*N::*/ X; };
  12882. /// }
  12883. /// }
  12884. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12885. SourceLocation NameLoc) {
  12886. // While the decl is in a namespace, do repeated lookup of that name and see
  12887. // if we get the same namespace back. If we do not, continue until
  12888. // translation unit scope, at which point we have a fully qualified NNS.
  12889. SmallVector<IdentifierInfo *, 4> Namespaces;
  12890. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12891. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12892. // This tag should be declared in a namespace, which can only be enclosed by
  12893. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12894. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12895. if (!Namespace || Namespace->isAnonymousNamespace())
  12896. return FixItHint();
  12897. IdentifierInfo *II = Namespace->getIdentifier();
  12898. Namespaces.push_back(II);
  12899. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12900. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12901. if (Lookup == Namespace)
  12902. break;
  12903. }
  12904. // Once we have all the namespaces, reverse them to go outermost first, and
  12905. // build an NNS.
  12906. SmallString<64> Insertion;
  12907. llvm::raw_svector_ostream OS(Insertion);
  12908. if (DC->isTranslationUnit())
  12909. OS << "::";
  12910. std::reverse(Namespaces.begin(), Namespaces.end());
  12911. for (auto *II : Namespaces)
  12912. OS << II->getName() << "::";
  12913. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12914. }
  12915. /// Determine whether a tag originally declared in context \p OldDC can
  12916. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12917. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12918. /// using-declaration).
  12919. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12920. DeclContext *NewDC) {
  12921. OldDC = OldDC->getRedeclContext();
  12922. NewDC = NewDC->getRedeclContext();
  12923. if (OldDC->Equals(NewDC))
  12924. return true;
  12925. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12926. // encloses the other).
  12927. if (S.getLangOpts().MSVCCompat &&
  12928. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12929. return true;
  12930. return false;
  12931. }
  12932. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12933. /// former case, Name will be non-null. In the later case, Name will be null.
  12934. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12935. /// reference/declaration/definition of a tag.
  12936. ///
  12937. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12938. /// trailing-type-specifier) other than one in an alias-declaration.
  12939. ///
  12940. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12941. /// skip the definition of this tag and treat it as if it were a declaration.
  12942. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12943. SourceLocation KWLoc, CXXScopeSpec &SS,
  12944. IdentifierInfo *Name, SourceLocation NameLoc,
  12945. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12946. SourceLocation ModulePrivateLoc,
  12947. MultiTemplateParamsArg TemplateParameterLists,
  12948. bool &OwnedDecl, bool &IsDependent,
  12949. SourceLocation ScopedEnumKWLoc,
  12950. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12951. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12952. SkipBodyInfo *SkipBody) {
  12953. // If this is not a definition, it must have a name.
  12954. IdentifierInfo *OrigName = Name;
  12955. assert((Name != nullptr || TUK == TUK_Definition) &&
  12956. "Nameless record must be a definition!");
  12957. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12958. OwnedDecl = false;
  12959. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12960. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12961. // FIXME: Check member specializations more carefully.
  12962. bool isMemberSpecialization = false;
  12963. bool Invalid = false;
  12964. // We only need to do this matching if we have template parameters
  12965. // or a scope specifier, which also conveniently avoids this work
  12966. // for non-C++ cases.
  12967. if (TemplateParameterLists.size() > 0 ||
  12968. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12969. if (TemplateParameterList *TemplateParams =
  12970. MatchTemplateParametersToScopeSpecifier(
  12971. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12972. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12973. if (Kind == TTK_Enum) {
  12974. Diag(KWLoc, diag::err_enum_template);
  12975. return nullptr;
  12976. }
  12977. if (TemplateParams->size() > 0) {
  12978. // This is a declaration or definition of a class template (which may
  12979. // be a member of another template).
  12980. if (Invalid)
  12981. return nullptr;
  12982. OwnedDecl = false;
  12983. DeclResult Result = CheckClassTemplate(
  12984. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12985. AS, ModulePrivateLoc,
  12986. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12987. TemplateParameterLists.data(), SkipBody);
  12988. return Result.get();
  12989. } else {
  12990. // The "template<>" header is extraneous.
  12991. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12992. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12993. isMemberSpecialization = true;
  12994. }
  12995. }
  12996. }
  12997. // Figure out the underlying type if this a enum declaration. We need to do
  12998. // this early, because it's needed to detect if this is an incompatible
  12999. // redeclaration.
  13000. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  13001. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  13002. if (Kind == TTK_Enum) {
  13003. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  13004. // No underlying type explicitly specified, or we failed to parse the
  13005. // type, default to int.
  13006. EnumUnderlying = Context.IntTy.getTypePtr();
  13007. } else if (UnderlyingType.get()) {
  13008. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  13009. // integral type; any cv-qualification is ignored.
  13010. TypeSourceInfo *TI = nullptr;
  13011. GetTypeFromParser(UnderlyingType.get(), &TI);
  13012. EnumUnderlying = TI;
  13013. if (CheckEnumUnderlyingType(TI))
  13014. // Recover by falling back to int.
  13015. EnumUnderlying = Context.IntTy.getTypePtr();
  13016. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  13017. UPPC_FixedUnderlyingType))
  13018. EnumUnderlying = Context.IntTy.getTypePtr();
  13019. } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
  13020. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  13021. // of 'int'. However, if this is an unfixed forward declaration, don't set
  13022. // the underlying type unless the user enables -fms-compatibility. This
  13023. // makes unfixed forward declared enums incomplete and is more conforming.
  13024. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  13025. EnumUnderlying = Context.IntTy.getTypePtr();
  13026. }
  13027. }
  13028. DeclContext *SearchDC = CurContext;
  13029. DeclContext *DC = CurContext;
  13030. bool isStdBadAlloc = false;
  13031. bool isStdAlignValT = false;
  13032. RedeclarationKind Redecl = forRedeclarationInCurContext();
  13033. if (TUK == TUK_Friend || TUK == TUK_Reference)
  13034. Redecl = NotForRedeclaration;
  13035. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  13036. /// implemented asks for structural equivalence checking, the returned decl
  13037. /// here is passed back to the parser, allowing the tag body to be parsed.
  13038. auto createTagFromNewDecl = [&]() -> TagDecl * {
  13039. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  13040. // If there is an identifier, use the location of the identifier as the
  13041. // location of the decl, otherwise use the location of the struct/union
  13042. // keyword.
  13043. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13044. TagDecl *New = nullptr;
  13045. if (Kind == TTK_Enum) {
  13046. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  13047. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  13048. // If this is an undefined enum, bail.
  13049. if (TUK != TUK_Definition && !Invalid)
  13050. return nullptr;
  13051. if (EnumUnderlying) {
  13052. EnumDecl *ED = cast<EnumDecl>(New);
  13053. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  13054. ED->setIntegerTypeSourceInfo(TI);
  13055. else
  13056. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  13057. ED->setPromotionType(ED->getIntegerType());
  13058. }
  13059. } else { // struct/union
  13060. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13061. nullptr);
  13062. }
  13063. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13064. // Add alignment attributes if necessary; these attributes are checked
  13065. // when the ASTContext lays out the structure.
  13066. //
  13067. // It is important for implementing the correct semantics that this
  13068. // happen here (in ActOnTag). The #pragma pack stack is
  13069. // maintained as a result of parser callbacks which can occur at
  13070. // many points during the parsing of a struct declaration (because
  13071. // the #pragma tokens are effectively skipped over during the
  13072. // parsing of the struct).
  13073. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13074. AddAlignmentAttributesForRecord(RD);
  13075. AddMsStructLayoutForRecord(RD);
  13076. }
  13077. }
  13078. New->setLexicalDeclContext(CurContext);
  13079. return New;
  13080. };
  13081. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  13082. if (Name && SS.isNotEmpty()) {
  13083. // We have a nested-name tag ('struct foo::bar').
  13084. // Check for invalid 'foo::'.
  13085. if (SS.isInvalid()) {
  13086. Name = nullptr;
  13087. goto CreateNewDecl;
  13088. }
  13089. // If this is a friend or a reference to a class in a dependent
  13090. // context, don't try to make a decl for it.
  13091. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13092. DC = computeDeclContext(SS, false);
  13093. if (!DC) {
  13094. IsDependent = true;
  13095. return nullptr;
  13096. }
  13097. } else {
  13098. DC = computeDeclContext(SS, true);
  13099. if (!DC) {
  13100. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  13101. << SS.getRange();
  13102. return nullptr;
  13103. }
  13104. }
  13105. if (RequireCompleteDeclContext(SS, DC))
  13106. return nullptr;
  13107. SearchDC = DC;
  13108. // Look-up name inside 'foo::'.
  13109. LookupQualifiedName(Previous, DC);
  13110. if (Previous.isAmbiguous())
  13111. return nullptr;
  13112. if (Previous.empty()) {
  13113. // Name lookup did not find anything. However, if the
  13114. // nested-name-specifier refers to the current instantiation,
  13115. // and that current instantiation has any dependent base
  13116. // classes, we might find something at instantiation time: treat
  13117. // this as a dependent elaborated-type-specifier.
  13118. // But this only makes any sense for reference-like lookups.
  13119. if (Previous.wasNotFoundInCurrentInstantiation() &&
  13120. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  13121. IsDependent = true;
  13122. return nullptr;
  13123. }
  13124. // A tag 'foo::bar' must already exist.
  13125. Diag(NameLoc, diag::err_not_tag_in_scope)
  13126. << Kind << Name << DC << SS.getRange();
  13127. Name = nullptr;
  13128. Invalid = true;
  13129. goto CreateNewDecl;
  13130. }
  13131. } else if (Name) {
  13132. // C++14 [class.mem]p14:
  13133. // If T is the name of a class, then each of the following shall have a
  13134. // name different from T:
  13135. // -- every member of class T that is itself a type
  13136. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  13137. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  13138. return nullptr;
  13139. // If this is a named struct, check to see if there was a previous forward
  13140. // declaration or definition.
  13141. // FIXME: We're looking into outer scopes here, even when we
  13142. // shouldn't be. Doing so can result in ambiguities that we
  13143. // shouldn't be diagnosing.
  13144. LookupName(Previous, S);
  13145. // When declaring or defining a tag, ignore ambiguities introduced
  13146. // by types using'ed into this scope.
  13147. if (Previous.isAmbiguous() &&
  13148. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  13149. LookupResult::Filter F = Previous.makeFilter();
  13150. while (F.hasNext()) {
  13151. NamedDecl *ND = F.next();
  13152. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  13153. SearchDC->getRedeclContext()))
  13154. F.erase();
  13155. }
  13156. F.done();
  13157. }
  13158. // C++11 [namespace.memdef]p3:
  13159. // If the name in a friend declaration is neither qualified nor
  13160. // a template-id and the declaration is a function or an
  13161. // elaborated-type-specifier, the lookup to determine whether
  13162. // the entity has been previously declared shall not consider
  13163. // any scopes outside the innermost enclosing namespace.
  13164. //
  13165. // MSVC doesn't implement the above rule for types, so a friend tag
  13166. // declaration may be a redeclaration of a type declared in an enclosing
  13167. // scope. They do implement this rule for friend functions.
  13168. //
  13169. // Does it matter that this should be by scope instead of by
  13170. // semantic context?
  13171. if (!Previous.empty() && TUK == TUK_Friend) {
  13172. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  13173. LookupResult::Filter F = Previous.makeFilter();
  13174. bool FriendSawTagOutsideEnclosingNamespace = false;
  13175. while (F.hasNext()) {
  13176. NamedDecl *ND = F.next();
  13177. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  13178. if (DC->isFileContext() &&
  13179. !EnclosingNS->Encloses(ND->getDeclContext())) {
  13180. if (getLangOpts().MSVCCompat)
  13181. FriendSawTagOutsideEnclosingNamespace = true;
  13182. else
  13183. F.erase();
  13184. }
  13185. }
  13186. F.done();
  13187. // Diagnose this MSVC extension in the easy case where lookup would have
  13188. // unambiguously found something outside the enclosing namespace.
  13189. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  13190. NamedDecl *ND = Previous.getFoundDecl();
  13191. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  13192. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  13193. }
  13194. }
  13195. // Note: there used to be some attempt at recovery here.
  13196. if (Previous.isAmbiguous())
  13197. return nullptr;
  13198. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  13199. // FIXME: This makes sure that we ignore the contexts associated
  13200. // with C structs, unions, and enums when looking for a matching
  13201. // tag declaration or definition. See the similar lookup tweak
  13202. // in Sema::LookupName; is there a better way to deal with this?
  13203. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  13204. SearchDC = SearchDC->getParent();
  13205. }
  13206. }
  13207. if (Previous.isSingleResult() &&
  13208. Previous.getFoundDecl()->isTemplateParameter()) {
  13209. // Maybe we will complain about the shadowed template parameter.
  13210. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  13211. // Just pretend that we didn't see the previous declaration.
  13212. Previous.clear();
  13213. }
  13214. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  13215. DC->Equals(getStdNamespace())) {
  13216. if (Name->isStr("bad_alloc")) {
  13217. // This is a declaration of or a reference to "std::bad_alloc".
  13218. isStdBadAlloc = true;
  13219. // If std::bad_alloc has been implicitly declared (but made invisible to
  13220. // name lookup), fill in this implicit declaration as the previous
  13221. // declaration, so that the declarations get chained appropriately.
  13222. if (Previous.empty() && StdBadAlloc)
  13223. Previous.addDecl(getStdBadAlloc());
  13224. } else if (Name->isStr("align_val_t")) {
  13225. isStdAlignValT = true;
  13226. if (Previous.empty() && StdAlignValT)
  13227. Previous.addDecl(getStdAlignValT());
  13228. }
  13229. }
  13230. // If we didn't find a previous declaration, and this is a reference
  13231. // (or friend reference), move to the correct scope. In C++, we
  13232. // also need to do a redeclaration lookup there, just in case
  13233. // there's a shadow friend decl.
  13234. if (Name && Previous.empty() &&
  13235. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  13236. if (Invalid) goto CreateNewDecl;
  13237. assert(SS.isEmpty());
  13238. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  13239. // C++ [basic.scope.pdecl]p5:
  13240. // -- for an elaborated-type-specifier of the form
  13241. //
  13242. // class-key identifier
  13243. //
  13244. // if the elaborated-type-specifier is used in the
  13245. // decl-specifier-seq or parameter-declaration-clause of a
  13246. // function defined in namespace scope, the identifier is
  13247. // declared as a class-name in the namespace that contains
  13248. // the declaration; otherwise, except as a friend
  13249. // declaration, the identifier is declared in the smallest
  13250. // non-class, non-function-prototype scope that contains the
  13251. // declaration.
  13252. //
  13253. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  13254. // C structs and unions.
  13255. //
  13256. // It is an error in C++ to declare (rather than define) an enum
  13257. // type, including via an elaborated type specifier. We'll
  13258. // diagnose that later; for now, declare the enum in the same
  13259. // scope as we would have picked for any other tag type.
  13260. //
  13261. // GNU C also supports this behavior as part of its incomplete
  13262. // enum types extension, while GNU C++ does not.
  13263. //
  13264. // Find the context where we'll be declaring the tag.
  13265. // FIXME: We would like to maintain the current DeclContext as the
  13266. // lexical context,
  13267. SearchDC = getTagInjectionContext(SearchDC);
  13268. // Find the scope where we'll be declaring the tag.
  13269. S = getTagInjectionScope(S, getLangOpts());
  13270. } else {
  13271. assert(TUK == TUK_Friend);
  13272. // C++ [namespace.memdef]p3:
  13273. // If a friend declaration in a non-local class first declares a
  13274. // class or function, the friend class or function is a member of
  13275. // the innermost enclosing namespace.
  13276. SearchDC = SearchDC->getEnclosingNamespaceContext();
  13277. }
  13278. // In C++, we need to do a redeclaration lookup to properly
  13279. // diagnose some problems.
  13280. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  13281. // hidden declaration so that we don't get ambiguity errors when using a
  13282. // type declared by an elaborated-type-specifier. In C that is not correct
  13283. // and we should instead merge compatible types found by lookup.
  13284. if (getLangOpts().CPlusPlus) {
  13285. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13286. LookupQualifiedName(Previous, SearchDC);
  13287. } else {
  13288. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13289. LookupName(Previous, S);
  13290. }
  13291. }
  13292. // If we have a known previous declaration to use, then use it.
  13293. if (Previous.empty() && SkipBody && SkipBody->Previous)
  13294. Previous.addDecl(SkipBody->Previous);
  13295. if (!Previous.empty()) {
  13296. NamedDecl *PrevDecl = Previous.getFoundDecl();
  13297. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  13298. // It's okay to have a tag decl in the same scope as a typedef
  13299. // which hides a tag decl in the same scope. Finding this
  13300. // insanity with a redeclaration lookup can only actually happen
  13301. // in C++.
  13302. //
  13303. // This is also okay for elaborated-type-specifiers, which is
  13304. // technically forbidden by the current standard but which is
  13305. // okay according to the likely resolution of an open issue;
  13306. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  13307. if (getLangOpts().CPlusPlus) {
  13308. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13309. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  13310. TagDecl *Tag = TT->getDecl();
  13311. if (Tag->getDeclName() == Name &&
  13312. Tag->getDeclContext()->getRedeclContext()
  13313. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  13314. PrevDecl = Tag;
  13315. Previous.clear();
  13316. Previous.addDecl(Tag);
  13317. Previous.resolveKind();
  13318. }
  13319. }
  13320. }
  13321. }
  13322. // If this is a redeclaration of a using shadow declaration, it must
  13323. // declare a tag in the same context. In MSVC mode, we allow a
  13324. // redefinition if either context is within the other.
  13325. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  13326. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  13327. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  13328. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  13329. !(OldTag && isAcceptableTagRedeclContext(
  13330. *this, OldTag->getDeclContext(), SearchDC))) {
  13331. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  13332. Diag(Shadow->getTargetDecl()->getLocation(),
  13333. diag::note_using_decl_target);
  13334. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  13335. << 0;
  13336. // Recover by ignoring the old declaration.
  13337. Previous.clear();
  13338. goto CreateNewDecl;
  13339. }
  13340. }
  13341. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  13342. // If this is a use of a previous tag, or if the tag is already declared
  13343. // in the same scope (so that the definition/declaration completes or
  13344. // rementions the tag), reuse the decl.
  13345. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  13346. isDeclInScope(DirectPrevDecl, SearchDC, S,
  13347. SS.isNotEmpty() || isMemberSpecialization)) {
  13348. // Make sure that this wasn't declared as an enum and now used as a
  13349. // struct or something similar.
  13350. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  13351. TUK == TUK_Definition, KWLoc,
  13352. Name)) {
  13353. bool SafeToContinue
  13354. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  13355. Kind != TTK_Enum);
  13356. if (SafeToContinue)
  13357. Diag(KWLoc, diag::err_use_with_wrong_tag)
  13358. << Name
  13359. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  13360. PrevTagDecl->getKindName());
  13361. else
  13362. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  13363. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  13364. if (SafeToContinue)
  13365. Kind = PrevTagDecl->getTagKind();
  13366. else {
  13367. // Recover by making this an anonymous redefinition.
  13368. Name = nullptr;
  13369. Previous.clear();
  13370. Invalid = true;
  13371. }
  13372. }
  13373. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  13374. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  13375. // If this is an elaborated-type-specifier for a scoped enumeration,
  13376. // the 'class' keyword is not necessary and not permitted.
  13377. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13378. if (ScopedEnum)
  13379. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  13380. << PrevEnum->isScoped()
  13381. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  13382. return PrevTagDecl;
  13383. }
  13384. QualType EnumUnderlyingTy;
  13385. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13386. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  13387. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  13388. EnumUnderlyingTy = QualType(T, 0);
  13389. // All conflicts with previous declarations are recovered by
  13390. // returning the previous declaration, unless this is a definition,
  13391. // in which case we want the caller to bail out.
  13392. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  13393. ScopedEnum, EnumUnderlyingTy,
  13394. IsFixed, PrevEnum))
  13395. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  13396. }
  13397. // C++11 [class.mem]p1:
  13398. // A member shall not be declared twice in the member-specification,
  13399. // except that a nested class or member class template can be declared
  13400. // and then later defined.
  13401. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  13402. S->isDeclScope(PrevDecl)) {
  13403. Diag(NameLoc, diag::ext_member_redeclared);
  13404. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  13405. }
  13406. if (!Invalid) {
  13407. // If this is a use, just return the declaration we found, unless
  13408. // we have attributes.
  13409. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13410. if (!Attrs.empty()) {
  13411. // FIXME: Diagnose these attributes. For now, we create a new
  13412. // declaration to hold them.
  13413. } else if (TUK == TUK_Reference &&
  13414. (PrevTagDecl->getFriendObjectKind() ==
  13415. Decl::FOK_Undeclared ||
  13416. PrevDecl->getOwningModule() != getCurrentModule()) &&
  13417. SS.isEmpty()) {
  13418. // This declaration is a reference to an existing entity, but
  13419. // has different visibility from that entity: it either makes
  13420. // a friend visible or it makes a type visible in a new module.
  13421. // In either case, create a new declaration. We only do this if
  13422. // the declaration would have meant the same thing if no prior
  13423. // declaration were found, that is, if it was found in the same
  13424. // scope where we would have injected a declaration.
  13425. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  13426. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  13427. return PrevTagDecl;
  13428. // This is in the injected scope, create a new declaration in
  13429. // that scope.
  13430. S = getTagInjectionScope(S, getLangOpts());
  13431. } else {
  13432. return PrevTagDecl;
  13433. }
  13434. }
  13435. // Diagnose attempts to redefine a tag.
  13436. if (TUK == TUK_Definition) {
  13437. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13438. // If we're defining a specialization and the previous definition
  13439. // is from an implicit instantiation, don't emit an error
  13440. // here; we'll catch this in the general case below.
  13441. bool IsExplicitSpecializationAfterInstantiation = false;
  13442. if (isMemberSpecialization) {
  13443. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13444. IsExplicitSpecializationAfterInstantiation =
  13445. RD->getTemplateSpecializationKind() !=
  13446. TSK_ExplicitSpecialization;
  13447. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13448. IsExplicitSpecializationAfterInstantiation =
  13449. ED->getTemplateSpecializationKind() !=
  13450. TSK_ExplicitSpecialization;
  13451. }
  13452. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13453. // not keep more that one definition around (merge them). However,
  13454. // ensure the decl passes the structural compatibility check in
  13455. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13456. NamedDecl *Hidden = nullptr;
  13457. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13458. // There is a definition of this tag, but it is not visible. We
  13459. // explicitly make use of C++'s one definition rule here, and
  13460. // assume that this definition is identical to the hidden one
  13461. // we already have. Make the existing definition visible and
  13462. // use it in place of this one.
  13463. if (!getLangOpts().CPlusPlus) {
  13464. // Postpone making the old definition visible until after we
  13465. // complete parsing the new one and do the structural
  13466. // comparison.
  13467. SkipBody->CheckSameAsPrevious = true;
  13468. SkipBody->New = createTagFromNewDecl();
  13469. SkipBody->Previous = Def;
  13470. return Def;
  13471. } else {
  13472. SkipBody->ShouldSkip = true;
  13473. SkipBody->Previous = Def;
  13474. makeMergedDefinitionVisible(Hidden);
  13475. // Carry on and handle it like a normal definition. We'll
  13476. // skip starting the definitiion later.
  13477. }
  13478. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13479. // A redeclaration in function prototype scope in C isn't
  13480. // visible elsewhere, so merely issue a warning.
  13481. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13482. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13483. else
  13484. Diag(NameLoc, diag::err_redefinition) << Name;
  13485. notePreviousDefinition(Def,
  13486. NameLoc.isValid() ? NameLoc : KWLoc);
  13487. // If this is a redefinition, recover by making this
  13488. // struct be anonymous, which will make any later
  13489. // references get the previous definition.
  13490. Name = nullptr;
  13491. Previous.clear();
  13492. Invalid = true;
  13493. }
  13494. } else {
  13495. // If the type is currently being defined, complain
  13496. // about a nested redefinition.
  13497. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13498. if (TD->isBeingDefined()) {
  13499. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13500. Diag(PrevTagDecl->getLocation(),
  13501. diag::note_previous_definition);
  13502. Name = nullptr;
  13503. Previous.clear();
  13504. Invalid = true;
  13505. }
  13506. }
  13507. // Okay, this is definition of a previously declared or referenced
  13508. // tag. We're going to create a new Decl for it.
  13509. }
  13510. // Okay, we're going to make a redeclaration. If this is some kind
  13511. // of reference, make sure we build the redeclaration in the same DC
  13512. // as the original, and ignore the current access specifier.
  13513. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13514. SearchDC = PrevTagDecl->getDeclContext();
  13515. AS = AS_none;
  13516. }
  13517. }
  13518. // If we get here we have (another) forward declaration or we
  13519. // have a definition. Just create a new decl.
  13520. } else {
  13521. // If we get here, this is a definition of a new tag type in a nested
  13522. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13523. // new decl/type. We set PrevDecl to NULL so that the entities
  13524. // have distinct types.
  13525. Previous.clear();
  13526. }
  13527. // If we get here, we're going to create a new Decl. If PrevDecl
  13528. // is non-NULL, it's a definition of the tag declared by
  13529. // PrevDecl. If it's NULL, we have a new definition.
  13530. // Otherwise, PrevDecl is not a tag, but was found with tag
  13531. // lookup. This is only actually possible in C++, where a few
  13532. // things like templates still live in the tag namespace.
  13533. } else {
  13534. // Use a better diagnostic if an elaborated-type-specifier
  13535. // found the wrong kind of type on the first
  13536. // (non-redeclaration) lookup.
  13537. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13538. !Previous.isForRedeclaration()) {
  13539. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13540. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13541. << Kind;
  13542. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13543. Invalid = true;
  13544. // Otherwise, only diagnose if the declaration is in scope.
  13545. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13546. SS.isNotEmpty() || isMemberSpecialization)) {
  13547. // do nothing
  13548. // Diagnose implicit declarations introduced by elaborated types.
  13549. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13550. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13551. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13552. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13553. Invalid = true;
  13554. // Otherwise it's a declaration. Call out a particularly common
  13555. // case here.
  13556. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13557. unsigned Kind = 0;
  13558. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13559. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13560. << Name << Kind << TND->getUnderlyingType();
  13561. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13562. Invalid = true;
  13563. // Otherwise, diagnose.
  13564. } else {
  13565. // The tag name clashes with something else in the target scope,
  13566. // issue an error and recover by making this tag be anonymous.
  13567. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13568. notePreviousDefinition(PrevDecl, NameLoc);
  13569. Name = nullptr;
  13570. Invalid = true;
  13571. }
  13572. // The existing declaration isn't relevant to us; we're in a
  13573. // new scope, so clear out the previous declaration.
  13574. Previous.clear();
  13575. }
  13576. }
  13577. CreateNewDecl:
  13578. TagDecl *PrevDecl = nullptr;
  13579. if (Previous.isSingleResult())
  13580. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13581. // If there is an identifier, use the location of the identifier as the
  13582. // location of the decl, otherwise use the location of the struct/union
  13583. // keyword.
  13584. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13585. // Otherwise, create a new declaration. If there is a previous
  13586. // declaration of the same entity, the two will be linked via
  13587. // PrevDecl.
  13588. TagDecl *New;
  13589. if (Kind == TTK_Enum) {
  13590. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13591. // enum X { A, B, C } D; D should chain to X.
  13592. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13593. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13594. ScopedEnumUsesClassTag, IsFixed);
  13595. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13596. StdAlignValT = cast<EnumDecl>(New);
  13597. // If this is an undefined enum, warn.
  13598. if (TUK != TUK_Definition && !Invalid) {
  13599. TagDecl *Def;
  13600. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13601. // C++0x: 7.2p2: opaque-enum-declaration.
  13602. // Conflicts are diagnosed above. Do nothing.
  13603. }
  13604. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13605. Diag(Loc, diag::ext_forward_ref_enum_def)
  13606. << New;
  13607. Diag(Def->getLocation(), diag::note_previous_definition);
  13608. } else {
  13609. unsigned DiagID = diag::ext_forward_ref_enum;
  13610. if (getLangOpts().MSVCCompat)
  13611. DiagID = diag::ext_ms_forward_ref_enum;
  13612. else if (getLangOpts().CPlusPlus)
  13613. DiagID = diag::err_forward_ref_enum;
  13614. Diag(Loc, DiagID);
  13615. }
  13616. }
  13617. if (EnumUnderlying) {
  13618. EnumDecl *ED = cast<EnumDecl>(New);
  13619. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13620. ED->setIntegerTypeSourceInfo(TI);
  13621. else
  13622. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13623. ED->setPromotionType(ED->getIntegerType());
  13624. assert(ED->isComplete() && "enum with type should be complete");
  13625. }
  13626. } else {
  13627. // struct/union/class
  13628. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13629. // struct X { int A; } D; D should chain to X.
  13630. if (getLangOpts().CPlusPlus) {
  13631. // FIXME: Look for a way to use RecordDecl for simple structs.
  13632. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13633. cast_or_null<CXXRecordDecl>(PrevDecl));
  13634. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13635. StdBadAlloc = cast<CXXRecordDecl>(New);
  13636. } else
  13637. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13638. cast_or_null<RecordDecl>(PrevDecl));
  13639. }
  13640. // C++11 [dcl.type]p3:
  13641. // A type-specifier-seq shall not define a class or enumeration [...].
  13642. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13643. TUK == TUK_Definition) {
  13644. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13645. << Context.getTagDeclType(New);
  13646. Invalid = true;
  13647. }
  13648. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13649. DC->getDeclKind() == Decl::Enum) {
  13650. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13651. << Context.getTagDeclType(New);
  13652. Invalid = true;
  13653. }
  13654. // Maybe add qualifier info.
  13655. if (SS.isNotEmpty()) {
  13656. if (SS.isSet()) {
  13657. // If this is either a declaration or a definition, check the
  13658. // nested-name-specifier against the current context.
  13659. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13660. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13661. isMemberSpecialization))
  13662. Invalid = true;
  13663. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13664. if (TemplateParameterLists.size() > 0) {
  13665. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13666. }
  13667. }
  13668. else
  13669. Invalid = true;
  13670. }
  13671. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13672. // Add alignment attributes if necessary; these attributes are checked when
  13673. // the ASTContext lays out the structure.
  13674. //
  13675. // It is important for implementing the correct semantics that this
  13676. // happen here (in ActOnTag). The #pragma pack stack is
  13677. // maintained as a result of parser callbacks which can occur at
  13678. // many points during the parsing of a struct declaration (because
  13679. // the #pragma tokens are effectively skipped over during the
  13680. // parsing of the struct).
  13681. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13682. AddAlignmentAttributesForRecord(RD);
  13683. AddMsStructLayoutForRecord(RD);
  13684. }
  13685. }
  13686. if (ModulePrivateLoc.isValid()) {
  13687. if (isMemberSpecialization)
  13688. Diag(New->getLocation(), diag::err_module_private_specialization)
  13689. << 2
  13690. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13691. // __module_private__ does not apply to local classes. However, we only
  13692. // diagnose this as an error when the declaration specifiers are
  13693. // freestanding. Here, we just ignore the __module_private__.
  13694. else if (!SearchDC->isFunctionOrMethod())
  13695. New->setModulePrivate();
  13696. }
  13697. // If this is a specialization of a member class (of a class template),
  13698. // check the specialization.
  13699. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13700. Invalid = true;
  13701. // If we're declaring or defining a tag in function prototype scope in C,
  13702. // note that this type can only be used within the function and add it to
  13703. // the list of decls to inject into the function definition scope.
  13704. if ((Name || Kind == TTK_Enum) &&
  13705. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13706. if (getLangOpts().CPlusPlus) {
  13707. // C++ [dcl.fct]p6:
  13708. // Types shall not be defined in return or parameter types.
  13709. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13710. Diag(Loc, diag::err_type_defined_in_param_type)
  13711. << Name;
  13712. Invalid = true;
  13713. }
  13714. } else if (!PrevDecl) {
  13715. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13716. }
  13717. }
  13718. if (Invalid)
  13719. New->setInvalidDecl();
  13720. // Set the lexical context. If the tag has a C++ scope specifier, the
  13721. // lexical context will be different from the semantic context.
  13722. New->setLexicalDeclContext(CurContext);
  13723. // Mark this as a friend decl if applicable.
  13724. // In Microsoft mode, a friend declaration also acts as a forward
  13725. // declaration so we always pass true to setObjectOfFriendDecl to make
  13726. // the tag name visible.
  13727. if (TUK == TUK_Friend)
  13728. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13729. // Set the access specifier.
  13730. if (!Invalid && SearchDC->isRecord())
  13731. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13732. if (PrevDecl)
  13733. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13734. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13735. New->startDefinition();
  13736. ProcessDeclAttributeList(S, New, Attrs);
  13737. AddPragmaAttributes(S, New);
  13738. // If this has an identifier, add it to the scope stack.
  13739. if (TUK == TUK_Friend) {
  13740. // We might be replacing an existing declaration in the lookup tables;
  13741. // if so, borrow its access specifier.
  13742. if (PrevDecl)
  13743. New->setAccess(PrevDecl->getAccess());
  13744. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13745. DC->makeDeclVisibleInContext(New);
  13746. if (Name) // can be null along some error paths
  13747. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13748. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13749. } else if (Name) {
  13750. S = getNonFieldDeclScope(S);
  13751. PushOnScopeChains(New, S, true);
  13752. } else {
  13753. CurContext->addDecl(New);
  13754. }
  13755. // If this is the C FILE type, notify the AST context.
  13756. if (IdentifierInfo *II = New->getIdentifier())
  13757. if (!New->isInvalidDecl() &&
  13758. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13759. II->isStr("FILE"))
  13760. Context.setFILEDecl(New);
  13761. if (PrevDecl)
  13762. mergeDeclAttributes(New, PrevDecl);
  13763. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
  13764. inferGslOwnerPointerAttribute(CXXRD);
  13765. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13766. // record.
  13767. AddPushedVisibilityAttribute(New);
  13768. if (isMemberSpecialization && !New->isInvalidDecl())
  13769. CompleteMemberSpecialization(New, Previous);
  13770. OwnedDecl = true;
  13771. // In C++, don't return an invalid declaration. We can't recover well from
  13772. // the cases where we make the type anonymous.
  13773. if (Invalid && getLangOpts().CPlusPlus) {
  13774. if (New->isBeingDefined())
  13775. if (auto RD = dyn_cast<RecordDecl>(New))
  13776. RD->completeDefinition();
  13777. return nullptr;
  13778. } else if (SkipBody && SkipBody->ShouldSkip) {
  13779. return SkipBody->Previous;
  13780. } else {
  13781. return New;
  13782. }
  13783. }
  13784. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13785. AdjustDeclIfTemplate(TagD);
  13786. TagDecl *Tag = cast<TagDecl>(TagD);
  13787. // Enter the tag context.
  13788. PushDeclContext(S, Tag);
  13789. ActOnDocumentableDecl(TagD);
  13790. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13791. // record.
  13792. AddPushedVisibilityAttribute(Tag);
  13793. }
  13794. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13795. SkipBodyInfo &SkipBody) {
  13796. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13797. return false;
  13798. // Make the previous decl visible.
  13799. makeMergedDefinitionVisible(SkipBody.Previous);
  13800. return true;
  13801. }
  13802. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13803. assert(isa<ObjCContainerDecl>(IDecl) &&
  13804. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13805. DeclContext *OCD = cast<DeclContext>(IDecl);
  13806. assert(getContainingDC(OCD) == CurContext &&
  13807. "The next DeclContext should be lexically contained in the current one.");
  13808. CurContext = OCD;
  13809. return IDecl;
  13810. }
  13811. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13812. SourceLocation FinalLoc,
  13813. bool IsFinalSpelledSealed,
  13814. SourceLocation LBraceLoc) {
  13815. AdjustDeclIfTemplate(TagD);
  13816. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13817. FieldCollector->StartClass();
  13818. if (!Record->getIdentifier())
  13819. return;
  13820. if (FinalLoc.isValid())
  13821. Record->addAttr(FinalAttr::Create(
  13822. Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
  13823. static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
  13824. // C++ [class]p2:
  13825. // [...] The class-name is also inserted into the scope of the
  13826. // class itself; this is known as the injected-class-name. For
  13827. // purposes of access checking, the injected-class-name is treated
  13828. // as if it were a public member name.
  13829. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13830. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13831. Record->getLocation(), Record->getIdentifier(),
  13832. /*PrevDecl=*/nullptr,
  13833. /*DelayTypeCreation=*/true);
  13834. Context.getTypeDeclType(InjectedClassName, Record);
  13835. InjectedClassName->setImplicit();
  13836. InjectedClassName->setAccess(AS_public);
  13837. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13838. InjectedClassName->setDescribedClassTemplate(Template);
  13839. PushOnScopeChains(InjectedClassName, S);
  13840. assert(InjectedClassName->isInjectedClassName() &&
  13841. "Broken injected-class-name");
  13842. }
  13843. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13844. SourceRange BraceRange) {
  13845. AdjustDeclIfTemplate(TagD);
  13846. TagDecl *Tag = cast<TagDecl>(TagD);
  13847. Tag->setBraceRange(BraceRange);
  13848. // Make sure we "complete" the definition even it is invalid.
  13849. if (Tag->isBeingDefined()) {
  13850. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13851. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13852. RD->completeDefinition();
  13853. }
  13854. if (isa<CXXRecordDecl>(Tag)) {
  13855. FieldCollector->FinishClass();
  13856. }
  13857. // Exit this scope of this tag's definition.
  13858. PopDeclContext();
  13859. if (getCurLexicalContext()->isObjCContainer() &&
  13860. Tag->getDeclContext()->isFileContext())
  13861. Tag->setTopLevelDeclInObjCContainer();
  13862. // Notify the consumer that we've defined a tag.
  13863. if (!Tag->isInvalidDecl())
  13864. Consumer.HandleTagDeclDefinition(Tag);
  13865. }
  13866. void Sema::ActOnObjCContainerFinishDefinition() {
  13867. // Exit this scope of this interface definition.
  13868. PopDeclContext();
  13869. }
  13870. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13871. assert(DC == CurContext && "Mismatch of container contexts");
  13872. OriginalLexicalContext = DC;
  13873. ActOnObjCContainerFinishDefinition();
  13874. }
  13875. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13876. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13877. OriginalLexicalContext = nullptr;
  13878. }
  13879. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13880. AdjustDeclIfTemplate(TagD);
  13881. TagDecl *Tag = cast<TagDecl>(TagD);
  13882. Tag->setInvalidDecl();
  13883. // Make sure we "complete" the definition even it is invalid.
  13884. if (Tag->isBeingDefined()) {
  13885. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13886. RD->completeDefinition();
  13887. }
  13888. // We're undoing ActOnTagStartDefinition here, not
  13889. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13890. // the FieldCollector.
  13891. PopDeclContext();
  13892. }
  13893. // Note that FieldName may be null for anonymous bitfields.
  13894. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13895. IdentifierInfo *FieldName,
  13896. QualType FieldTy, bool IsMsStruct,
  13897. Expr *BitWidth, bool *ZeroWidth) {
  13898. // Default to true; that shouldn't confuse checks for emptiness
  13899. if (ZeroWidth)
  13900. *ZeroWidth = true;
  13901. // C99 6.7.2.1p4 - verify the field type.
  13902. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13903. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13904. // Handle incomplete types with specific error.
  13905. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13906. return ExprError();
  13907. if (FieldName)
  13908. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13909. << FieldName << FieldTy << BitWidth->getSourceRange();
  13910. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13911. << FieldTy << BitWidth->getSourceRange();
  13912. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13913. UPPC_BitFieldWidth))
  13914. return ExprError();
  13915. // If the bit-width is type- or value-dependent, don't try to check
  13916. // it now.
  13917. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13918. return BitWidth;
  13919. llvm::APSInt Value;
  13920. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13921. if (ICE.isInvalid())
  13922. return ICE;
  13923. BitWidth = ICE.get();
  13924. if (Value != 0 && ZeroWidth)
  13925. *ZeroWidth = false;
  13926. // Zero-width bitfield is ok for anonymous field.
  13927. if (Value == 0 && FieldName)
  13928. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13929. if (Value.isSigned() && Value.isNegative()) {
  13930. if (FieldName)
  13931. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13932. << FieldName << Value.toString(10);
  13933. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13934. << Value.toString(10);
  13935. }
  13936. if (!FieldTy->isDependentType()) {
  13937. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13938. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13939. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13940. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13941. // ABI.
  13942. bool CStdConstraintViolation =
  13943. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13944. bool MSBitfieldViolation =
  13945. Value.ugt(TypeStorageSize) &&
  13946. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13947. if (CStdConstraintViolation || MSBitfieldViolation) {
  13948. unsigned DiagWidth =
  13949. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13950. if (FieldName)
  13951. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13952. << FieldName << (unsigned)Value.getZExtValue()
  13953. << !CStdConstraintViolation << DiagWidth;
  13954. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13955. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13956. << DiagWidth;
  13957. }
  13958. // Warn on types where the user might conceivably expect to get all
  13959. // specified bits as value bits: that's all integral types other than
  13960. // 'bool'.
  13961. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13962. if (FieldName)
  13963. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13964. << FieldName << (unsigned)Value.getZExtValue()
  13965. << (unsigned)TypeWidth;
  13966. else
  13967. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13968. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13969. }
  13970. }
  13971. return BitWidth;
  13972. }
  13973. /// ActOnField - Each field of a C struct/union is passed into this in order
  13974. /// to create a FieldDecl object for it.
  13975. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13976. Declarator &D, Expr *BitfieldWidth) {
  13977. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13978. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13979. /*InitStyle=*/ICIS_NoInit, AS_public);
  13980. return Res;
  13981. }
  13982. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13983. ///
  13984. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13985. SourceLocation DeclStart,
  13986. Declarator &D, Expr *BitWidth,
  13987. InClassInitStyle InitStyle,
  13988. AccessSpecifier AS) {
  13989. if (D.isDecompositionDeclarator()) {
  13990. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13991. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13992. << Decomp.getSourceRange();
  13993. return nullptr;
  13994. }
  13995. IdentifierInfo *II = D.getIdentifier();
  13996. SourceLocation Loc = DeclStart;
  13997. if (II) Loc = D.getIdentifierLoc();
  13998. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13999. QualType T = TInfo->getType();
  14000. if (getLangOpts().CPlusPlus) {
  14001. CheckExtraCXXDefaultArguments(D);
  14002. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  14003. UPPC_DataMemberType)) {
  14004. D.setInvalidType();
  14005. T = Context.IntTy;
  14006. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  14007. }
  14008. }
  14009. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  14010. if (D.getDeclSpec().isInlineSpecified())
  14011. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  14012. << getLangOpts().CPlusPlus17;
  14013. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  14014. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  14015. diag::err_invalid_thread)
  14016. << DeclSpec::getSpecifierName(TSCS);
  14017. // Check to see if this name was declared as a member previously
  14018. NamedDecl *PrevDecl = nullptr;
  14019. LookupResult Previous(*this, II, Loc, LookupMemberName,
  14020. ForVisibleRedeclaration);
  14021. LookupName(Previous, S);
  14022. switch (Previous.getResultKind()) {
  14023. case LookupResult::Found:
  14024. case LookupResult::FoundUnresolvedValue:
  14025. PrevDecl = Previous.getAsSingle<NamedDecl>();
  14026. break;
  14027. case LookupResult::FoundOverloaded:
  14028. PrevDecl = Previous.getRepresentativeDecl();
  14029. break;
  14030. case LookupResult::NotFound:
  14031. case LookupResult::NotFoundInCurrentInstantiation:
  14032. case LookupResult::Ambiguous:
  14033. break;
  14034. }
  14035. Previous.suppressDiagnostics();
  14036. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14037. // Maybe we will complain about the shadowed template parameter.
  14038. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  14039. // Just pretend that we didn't see the previous declaration.
  14040. PrevDecl = nullptr;
  14041. }
  14042. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  14043. PrevDecl = nullptr;
  14044. bool Mutable
  14045. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  14046. SourceLocation TSSL = D.getBeginLoc();
  14047. FieldDecl *NewFD
  14048. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  14049. TSSL, AS, PrevDecl, &D);
  14050. if (NewFD->isInvalidDecl())
  14051. Record->setInvalidDecl();
  14052. if (D.getDeclSpec().isModulePrivateSpecified())
  14053. NewFD->setModulePrivate();
  14054. if (NewFD->isInvalidDecl() && PrevDecl) {
  14055. // Don't introduce NewFD into scope; there's already something
  14056. // with the same name in the same scope.
  14057. } else if (II) {
  14058. PushOnScopeChains(NewFD, S);
  14059. } else
  14060. Record->addDecl(NewFD);
  14061. return NewFD;
  14062. }
  14063. /// Build a new FieldDecl and check its well-formedness.
  14064. ///
  14065. /// This routine builds a new FieldDecl given the fields name, type,
  14066. /// record, etc. \p PrevDecl should refer to any previous declaration
  14067. /// with the same name and in the same scope as the field to be
  14068. /// created.
  14069. ///
  14070. /// \returns a new FieldDecl.
  14071. ///
  14072. /// \todo The Declarator argument is a hack. It will be removed once
  14073. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  14074. TypeSourceInfo *TInfo,
  14075. RecordDecl *Record, SourceLocation Loc,
  14076. bool Mutable, Expr *BitWidth,
  14077. InClassInitStyle InitStyle,
  14078. SourceLocation TSSL,
  14079. AccessSpecifier AS, NamedDecl *PrevDecl,
  14080. Declarator *D) {
  14081. IdentifierInfo *II = Name.getAsIdentifierInfo();
  14082. bool InvalidDecl = false;
  14083. if (D) InvalidDecl = D->isInvalidType();
  14084. // If we receive a broken type, recover by assuming 'int' and
  14085. // marking this declaration as invalid.
  14086. if (T.isNull()) {
  14087. InvalidDecl = true;
  14088. T = Context.IntTy;
  14089. }
  14090. QualType EltTy = Context.getBaseElementType(T);
  14091. if (!EltTy->isDependentType()) {
  14092. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  14093. // Fields of incomplete type force their record to be invalid.
  14094. Record->setInvalidDecl();
  14095. InvalidDecl = true;
  14096. } else {
  14097. NamedDecl *Def;
  14098. EltTy->isIncompleteType(&Def);
  14099. if (Def && Def->isInvalidDecl()) {
  14100. Record->setInvalidDecl();
  14101. InvalidDecl = true;
  14102. }
  14103. }
  14104. }
  14105. // TR 18037 does not allow fields to be declared with address space
  14106. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  14107. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  14108. Diag(Loc, diag::err_field_with_address_space);
  14109. Record->setInvalidDecl();
  14110. InvalidDecl = true;
  14111. }
  14112. if (LangOpts.OpenCL) {
  14113. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  14114. // used as structure or union field: image, sampler, event or block types.
  14115. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  14116. T->isBlockPointerType()) {
  14117. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  14118. Record->setInvalidDecl();
  14119. InvalidDecl = true;
  14120. }
  14121. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  14122. if (BitWidth) {
  14123. Diag(Loc, diag::err_opencl_bitfields);
  14124. InvalidDecl = true;
  14125. }
  14126. }
  14127. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  14128. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  14129. T.hasQualifiers()) {
  14130. InvalidDecl = true;
  14131. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  14132. }
  14133. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14134. // than a variably modified type.
  14135. if (!InvalidDecl && T->isVariablyModifiedType()) {
  14136. bool SizeIsNegative;
  14137. llvm::APSInt Oversized;
  14138. TypeSourceInfo *FixedTInfo =
  14139. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  14140. SizeIsNegative,
  14141. Oversized);
  14142. if (FixedTInfo) {
  14143. Diag(Loc, diag::warn_illegal_constant_array_size);
  14144. TInfo = FixedTInfo;
  14145. T = FixedTInfo->getType();
  14146. } else {
  14147. if (SizeIsNegative)
  14148. Diag(Loc, diag::err_typecheck_negative_array_size);
  14149. else if (Oversized.getBoolValue())
  14150. Diag(Loc, diag::err_array_too_large)
  14151. << Oversized.toString(10);
  14152. else
  14153. Diag(Loc, diag::err_typecheck_field_variable_size);
  14154. InvalidDecl = true;
  14155. }
  14156. }
  14157. // Fields can not have abstract class types
  14158. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  14159. diag::err_abstract_type_in_decl,
  14160. AbstractFieldType))
  14161. InvalidDecl = true;
  14162. bool ZeroWidth = false;
  14163. if (InvalidDecl)
  14164. BitWidth = nullptr;
  14165. // If this is declared as a bit-field, check the bit-field.
  14166. if (BitWidth) {
  14167. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  14168. &ZeroWidth).get();
  14169. if (!BitWidth) {
  14170. InvalidDecl = true;
  14171. BitWidth = nullptr;
  14172. ZeroWidth = false;
  14173. }
  14174. }
  14175. // Check that 'mutable' is consistent with the type of the declaration.
  14176. if (!InvalidDecl && Mutable) {
  14177. unsigned DiagID = 0;
  14178. if (T->isReferenceType())
  14179. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  14180. : diag::err_mutable_reference;
  14181. else if (T.isConstQualified())
  14182. DiagID = diag::err_mutable_const;
  14183. if (DiagID) {
  14184. SourceLocation ErrLoc = Loc;
  14185. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  14186. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  14187. Diag(ErrLoc, DiagID);
  14188. if (DiagID != diag::ext_mutable_reference) {
  14189. Mutable = false;
  14190. InvalidDecl = true;
  14191. }
  14192. }
  14193. }
  14194. // C++11 [class.union]p8 (DR1460):
  14195. // At most one variant member of a union may have a
  14196. // brace-or-equal-initializer.
  14197. if (InitStyle != ICIS_NoInit)
  14198. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  14199. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  14200. BitWidth, Mutable, InitStyle);
  14201. if (InvalidDecl)
  14202. NewFD->setInvalidDecl();
  14203. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  14204. Diag(Loc, diag::err_duplicate_member) << II;
  14205. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14206. NewFD->setInvalidDecl();
  14207. }
  14208. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  14209. if (Record->isUnion()) {
  14210. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14211. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14212. if (RDecl->getDefinition()) {
  14213. // C++ [class.union]p1: An object of a class with a non-trivial
  14214. // constructor, a non-trivial copy constructor, a non-trivial
  14215. // destructor, or a non-trivial copy assignment operator
  14216. // cannot be a member of a union, nor can an array of such
  14217. // objects.
  14218. if (CheckNontrivialField(NewFD))
  14219. NewFD->setInvalidDecl();
  14220. }
  14221. }
  14222. // C++ [class.union]p1: If a union contains a member of reference type,
  14223. // the program is ill-formed, except when compiling with MSVC extensions
  14224. // enabled.
  14225. if (EltTy->isReferenceType()) {
  14226. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  14227. diag::ext_union_member_of_reference_type :
  14228. diag::err_union_member_of_reference_type)
  14229. << NewFD->getDeclName() << EltTy;
  14230. if (!getLangOpts().MicrosoftExt)
  14231. NewFD->setInvalidDecl();
  14232. }
  14233. }
  14234. }
  14235. // FIXME: We need to pass in the attributes given an AST
  14236. // representation, not a parser representation.
  14237. if (D) {
  14238. // FIXME: The current scope is almost... but not entirely... correct here.
  14239. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  14240. if (NewFD->hasAttrs())
  14241. CheckAlignasUnderalignment(NewFD);
  14242. }
  14243. // In auto-retain/release, infer strong retension for fields of
  14244. // retainable type.
  14245. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  14246. NewFD->setInvalidDecl();
  14247. if (T.isObjCGCWeak())
  14248. Diag(Loc, diag::warn_attribute_weak_on_field);
  14249. NewFD->setAccess(AS);
  14250. return NewFD;
  14251. }
  14252. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  14253. assert(FD);
  14254. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  14255. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  14256. return false;
  14257. QualType EltTy = Context.getBaseElementType(FD->getType());
  14258. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14259. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14260. if (RDecl->getDefinition()) {
  14261. // We check for copy constructors before constructors
  14262. // because otherwise we'll never get complaints about
  14263. // copy constructors.
  14264. CXXSpecialMember member = CXXInvalid;
  14265. // We're required to check for any non-trivial constructors. Since the
  14266. // implicit default constructor is suppressed if there are any
  14267. // user-declared constructors, we just need to check that there is a
  14268. // trivial default constructor and a trivial copy constructor. (We don't
  14269. // worry about move constructors here, since this is a C++98 check.)
  14270. if (RDecl->hasNonTrivialCopyConstructor())
  14271. member = CXXCopyConstructor;
  14272. else if (!RDecl->hasTrivialDefaultConstructor())
  14273. member = CXXDefaultConstructor;
  14274. else if (RDecl->hasNonTrivialCopyAssignment())
  14275. member = CXXCopyAssignment;
  14276. else if (RDecl->hasNonTrivialDestructor())
  14277. member = CXXDestructor;
  14278. if (member != CXXInvalid) {
  14279. if (!getLangOpts().CPlusPlus11 &&
  14280. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  14281. // Objective-C++ ARC: it is an error to have a non-trivial field of
  14282. // a union. However, system headers in Objective-C programs
  14283. // occasionally have Objective-C lifetime objects within unions,
  14284. // and rather than cause the program to fail, we make those
  14285. // members unavailable.
  14286. SourceLocation Loc = FD->getLocation();
  14287. if (getSourceManager().isInSystemHeader(Loc)) {
  14288. if (!FD->hasAttr<UnavailableAttr>())
  14289. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14290. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  14291. return false;
  14292. }
  14293. }
  14294. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  14295. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  14296. diag::err_illegal_union_or_anon_struct_member)
  14297. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  14298. DiagnoseNontrivial(RDecl, member);
  14299. return !getLangOpts().CPlusPlus11;
  14300. }
  14301. }
  14302. }
  14303. return false;
  14304. }
  14305. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  14306. /// AST enum value.
  14307. static ObjCIvarDecl::AccessControl
  14308. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  14309. switch (ivarVisibility) {
  14310. default: llvm_unreachable("Unknown visitibility kind");
  14311. case tok::objc_private: return ObjCIvarDecl::Private;
  14312. case tok::objc_public: return ObjCIvarDecl::Public;
  14313. case tok::objc_protected: return ObjCIvarDecl::Protected;
  14314. case tok::objc_package: return ObjCIvarDecl::Package;
  14315. }
  14316. }
  14317. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  14318. /// in order to create an IvarDecl object for it.
  14319. Decl *Sema::ActOnIvar(Scope *S,
  14320. SourceLocation DeclStart,
  14321. Declarator &D, Expr *BitfieldWidth,
  14322. tok::ObjCKeywordKind Visibility) {
  14323. IdentifierInfo *II = D.getIdentifier();
  14324. Expr *BitWidth = (Expr*)BitfieldWidth;
  14325. SourceLocation Loc = DeclStart;
  14326. if (II) Loc = D.getIdentifierLoc();
  14327. // FIXME: Unnamed fields can be handled in various different ways, for
  14328. // example, unnamed unions inject all members into the struct namespace!
  14329. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14330. QualType T = TInfo->getType();
  14331. if (BitWidth) {
  14332. // 6.7.2.1p3, 6.7.2.1p4
  14333. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  14334. if (!BitWidth)
  14335. D.setInvalidType();
  14336. } else {
  14337. // Not a bitfield.
  14338. // validate II.
  14339. }
  14340. if (T->isReferenceType()) {
  14341. Diag(Loc, diag::err_ivar_reference_type);
  14342. D.setInvalidType();
  14343. }
  14344. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14345. // than a variably modified type.
  14346. else if (T->isVariablyModifiedType()) {
  14347. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  14348. D.setInvalidType();
  14349. }
  14350. // Get the visibility (access control) for this ivar.
  14351. ObjCIvarDecl::AccessControl ac =
  14352. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  14353. : ObjCIvarDecl::None;
  14354. // Must set ivar's DeclContext to its enclosing interface.
  14355. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  14356. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  14357. return nullptr;
  14358. ObjCContainerDecl *EnclosingContext;
  14359. if (ObjCImplementationDecl *IMPDecl =
  14360. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14361. if (LangOpts.ObjCRuntime.isFragile()) {
  14362. // Case of ivar declared in an implementation. Context is that of its class.
  14363. EnclosingContext = IMPDecl->getClassInterface();
  14364. assert(EnclosingContext && "Implementation has no class interface!");
  14365. }
  14366. else
  14367. EnclosingContext = EnclosingDecl;
  14368. } else {
  14369. if (ObjCCategoryDecl *CDecl =
  14370. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14371. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  14372. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  14373. return nullptr;
  14374. }
  14375. }
  14376. EnclosingContext = EnclosingDecl;
  14377. }
  14378. // Construct the decl.
  14379. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  14380. DeclStart, Loc, II, T,
  14381. TInfo, ac, (Expr *)BitfieldWidth);
  14382. if (II) {
  14383. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  14384. ForVisibleRedeclaration);
  14385. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  14386. && !isa<TagDecl>(PrevDecl)) {
  14387. Diag(Loc, diag::err_duplicate_member) << II;
  14388. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14389. NewID->setInvalidDecl();
  14390. }
  14391. }
  14392. // Process attributes attached to the ivar.
  14393. ProcessDeclAttributes(S, NewID, D);
  14394. if (D.isInvalidType())
  14395. NewID->setInvalidDecl();
  14396. // In ARC, infer 'retaining' for ivars of retainable type.
  14397. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  14398. NewID->setInvalidDecl();
  14399. if (D.getDeclSpec().isModulePrivateSpecified())
  14400. NewID->setModulePrivate();
  14401. if (II) {
  14402. // FIXME: When interfaces are DeclContexts, we'll need to add
  14403. // these to the interface.
  14404. S->AddDecl(NewID);
  14405. IdResolver.AddDecl(NewID);
  14406. }
  14407. if (LangOpts.ObjCRuntime.isNonFragile() &&
  14408. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  14409. Diag(Loc, diag::warn_ivars_in_interface);
  14410. return NewID;
  14411. }
  14412. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  14413. /// class and class extensions. For every class \@interface and class
  14414. /// extension \@interface, if the last ivar is a bitfield of any type,
  14415. /// then add an implicit `char :0` ivar to the end of that interface.
  14416. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  14417. SmallVectorImpl<Decl *> &AllIvarDecls) {
  14418. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  14419. return;
  14420. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  14421. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  14422. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  14423. return;
  14424. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  14425. if (!ID) {
  14426. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  14427. if (!CD->IsClassExtension())
  14428. return;
  14429. }
  14430. // No need to add this to end of @implementation.
  14431. else
  14432. return;
  14433. }
  14434. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14435. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14436. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14437. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14438. DeclLoc, DeclLoc, nullptr,
  14439. Context.CharTy,
  14440. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14441. DeclLoc),
  14442. ObjCIvarDecl::Private, BW,
  14443. true);
  14444. AllIvarDecls.push_back(Ivar);
  14445. }
  14446. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14447. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14448. SourceLocation RBrac,
  14449. const ParsedAttributesView &Attrs) {
  14450. assert(EnclosingDecl && "missing record or interface decl");
  14451. // If this is an Objective-C @implementation or category and we have
  14452. // new fields here we should reset the layout of the interface since
  14453. // it will now change.
  14454. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14455. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14456. switch (DC->getKind()) {
  14457. default: break;
  14458. case Decl::ObjCCategory:
  14459. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14460. break;
  14461. case Decl::ObjCImplementation:
  14462. Context.
  14463. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14464. break;
  14465. }
  14466. }
  14467. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14468. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14469. // Start counting up the number of named members; make sure to include
  14470. // members of anonymous structs and unions in the total.
  14471. unsigned NumNamedMembers = 0;
  14472. if (Record) {
  14473. for (const auto *I : Record->decls()) {
  14474. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14475. if (IFD->getDeclName())
  14476. ++NumNamedMembers;
  14477. }
  14478. }
  14479. // Verify that all the fields are okay.
  14480. SmallVector<FieldDecl*, 32> RecFields;
  14481. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14482. i != end; ++i) {
  14483. FieldDecl *FD = cast<FieldDecl>(*i);
  14484. // Get the type for the field.
  14485. const Type *FDTy = FD->getType().getTypePtr();
  14486. if (!FD->isAnonymousStructOrUnion()) {
  14487. // Remember all fields written by the user.
  14488. RecFields.push_back(FD);
  14489. }
  14490. // If the field is already invalid for some reason, don't emit more
  14491. // diagnostics about it.
  14492. if (FD->isInvalidDecl()) {
  14493. EnclosingDecl->setInvalidDecl();
  14494. continue;
  14495. }
  14496. // C99 6.7.2.1p2:
  14497. // A structure or union shall not contain a member with
  14498. // incomplete or function type (hence, a structure shall not
  14499. // contain an instance of itself, but may contain a pointer to
  14500. // an instance of itself), except that the last member of a
  14501. // structure with more than one named member may have incomplete
  14502. // array type; such a structure (and any union containing,
  14503. // possibly recursively, a member that is such a structure)
  14504. // shall not be a member of a structure or an element of an
  14505. // array.
  14506. bool IsLastField = (i + 1 == Fields.end());
  14507. if (FDTy->isFunctionType()) {
  14508. // Field declared as a function.
  14509. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14510. << FD->getDeclName();
  14511. FD->setInvalidDecl();
  14512. EnclosingDecl->setInvalidDecl();
  14513. continue;
  14514. } else if (FDTy->isIncompleteArrayType() &&
  14515. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14516. if (Record) {
  14517. // Flexible array member.
  14518. // Microsoft and g++ is more permissive regarding flexible array.
  14519. // It will accept flexible array in union and also
  14520. // as the sole element of a struct/class.
  14521. unsigned DiagID = 0;
  14522. if (!Record->isUnion() && !IsLastField) {
  14523. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14524. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14525. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14526. FD->setInvalidDecl();
  14527. EnclosingDecl->setInvalidDecl();
  14528. continue;
  14529. } else if (Record->isUnion())
  14530. DiagID = getLangOpts().MicrosoftExt
  14531. ? diag::ext_flexible_array_union_ms
  14532. : getLangOpts().CPlusPlus
  14533. ? diag::ext_flexible_array_union_gnu
  14534. : diag::err_flexible_array_union;
  14535. else if (NumNamedMembers < 1)
  14536. DiagID = getLangOpts().MicrosoftExt
  14537. ? diag::ext_flexible_array_empty_aggregate_ms
  14538. : getLangOpts().CPlusPlus
  14539. ? diag::ext_flexible_array_empty_aggregate_gnu
  14540. : diag::err_flexible_array_empty_aggregate;
  14541. if (DiagID)
  14542. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14543. << Record->getTagKind();
  14544. // While the layout of types that contain virtual bases is not specified
  14545. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14546. // virtual bases after the derived members. This would make a flexible
  14547. // array member declared at the end of an object not adjacent to the end
  14548. // of the type.
  14549. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14550. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14551. << FD->getDeclName() << Record->getTagKind();
  14552. if (!getLangOpts().C99)
  14553. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14554. << FD->getDeclName() << Record->getTagKind();
  14555. // If the element type has a non-trivial destructor, we would not
  14556. // implicitly destroy the elements, so disallow it for now.
  14557. //
  14558. // FIXME: GCC allows this. We should probably either implicitly delete
  14559. // the destructor of the containing class, or just allow this.
  14560. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14561. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14562. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14563. << FD->getDeclName() << FD->getType();
  14564. FD->setInvalidDecl();
  14565. EnclosingDecl->setInvalidDecl();
  14566. continue;
  14567. }
  14568. // Okay, we have a legal flexible array member at the end of the struct.
  14569. Record->setHasFlexibleArrayMember(true);
  14570. } else {
  14571. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14572. // unless they are followed by another ivar. That check is done
  14573. // elsewhere, after synthesized ivars are known.
  14574. }
  14575. } else if (!FDTy->isDependentType() &&
  14576. RequireCompleteType(FD->getLocation(), FD->getType(),
  14577. diag::err_field_incomplete)) {
  14578. // Incomplete type
  14579. FD->setInvalidDecl();
  14580. EnclosingDecl->setInvalidDecl();
  14581. continue;
  14582. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14583. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14584. // A type which contains a flexible array member is considered to be a
  14585. // flexible array member.
  14586. Record->setHasFlexibleArrayMember(true);
  14587. if (!Record->isUnion()) {
  14588. // If this is a struct/class and this is not the last element, reject
  14589. // it. Note that GCC supports variable sized arrays in the middle of
  14590. // structures.
  14591. if (!IsLastField)
  14592. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14593. << FD->getDeclName() << FD->getType();
  14594. else {
  14595. // We support flexible arrays at the end of structs in
  14596. // other structs as an extension.
  14597. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14598. << FD->getDeclName();
  14599. }
  14600. }
  14601. }
  14602. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14603. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14604. diag::err_abstract_type_in_decl,
  14605. AbstractIvarType)) {
  14606. // Ivars can not have abstract class types
  14607. FD->setInvalidDecl();
  14608. }
  14609. if (Record && FDTTy->getDecl()->hasObjectMember())
  14610. Record->setHasObjectMember(true);
  14611. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14612. Record->setHasVolatileMember(true);
  14613. } else if (FDTy->isObjCObjectType()) {
  14614. /// A field cannot be an Objective-c object
  14615. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14616. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14617. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14618. FD->setType(T);
  14619. } else if (Record && Record->isUnion() &&
  14620. FD->getType().hasNonTrivialObjCLifetime() &&
  14621. getSourceManager().isInSystemHeader(FD->getLocation()) &&
  14622. !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
  14623. (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
  14624. !Context.hasDirectOwnershipQualifier(FD->getType()))) {
  14625. // For backward compatibility, fields of C unions declared in system
  14626. // headers that have non-trivial ObjC ownership qualifications are marked
  14627. // as unavailable unless the qualifier is explicit and __strong. This can
  14628. // break ABI compatibility between programs compiled with ARC and MRR, but
  14629. // is a better option than rejecting programs using those unions under
  14630. // ARC.
  14631. FD->addAttr(UnavailableAttr::CreateImplicit(
  14632. Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
  14633. FD->getLocation()));
  14634. } else if (getLangOpts().ObjC &&
  14635. getLangOpts().getGC() != LangOptions::NonGC &&
  14636. Record && !Record->hasObjectMember()) {
  14637. if (FD->getType()->isObjCObjectPointerType() ||
  14638. FD->getType().isObjCGCStrong())
  14639. Record->setHasObjectMember(true);
  14640. else if (Context.getAsArrayType(FD->getType())) {
  14641. QualType BaseType = Context.getBaseElementType(FD->getType());
  14642. if (BaseType->isRecordType() &&
  14643. BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
  14644. Record->setHasObjectMember(true);
  14645. else if (BaseType->isObjCObjectPointerType() ||
  14646. BaseType.isObjCGCStrong())
  14647. Record->setHasObjectMember(true);
  14648. }
  14649. }
  14650. if (Record && !getLangOpts().CPlusPlus &&
  14651. !shouldIgnoreForRecordTriviality(FD)) {
  14652. QualType FT = FD->getType();
  14653. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  14654. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14655. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  14656. Record->isUnion())
  14657. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  14658. }
  14659. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14660. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  14661. Record->setNonTrivialToPrimitiveCopy(true);
  14662. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  14663. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  14664. }
  14665. if (FT.isDestructedType()) {
  14666. Record->setNonTrivialToPrimitiveDestroy(true);
  14667. Record->setParamDestroyedInCallee(true);
  14668. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  14669. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  14670. }
  14671. if (const auto *RT = FT->getAs<RecordType>()) {
  14672. if (RT->getDecl()->getArgPassingRestrictions() ==
  14673. RecordDecl::APK_CanNeverPassInRegs)
  14674. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14675. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14676. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14677. }
  14678. if (Record && FD->getType().isVolatileQualified())
  14679. Record->setHasVolatileMember(true);
  14680. // Keep track of the number of named members.
  14681. if (FD->getIdentifier())
  14682. ++NumNamedMembers;
  14683. }
  14684. // Okay, we successfully defined 'Record'.
  14685. if (Record) {
  14686. bool Completed = false;
  14687. if (CXXRecord) {
  14688. if (!CXXRecord->isInvalidDecl()) {
  14689. // Set access bits correctly on the directly-declared conversions.
  14690. for (CXXRecordDecl::conversion_iterator
  14691. I = CXXRecord->conversion_begin(),
  14692. E = CXXRecord->conversion_end(); I != E; ++I)
  14693. I.setAccess((*I)->getAccess());
  14694. }
  14695. if (!CXXRecord->isDependentType()) {
  14696. // Add any implicitly-declared members to this class.
  14697. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14698. if (!CXXRecord->isInvalidDecl()) {
  14699. // If we have virtual base classes, we may end up finding multiple
  14700. // final overriders for a given virtual function. Check for this
  14701. // problem now.
  14702. if (CXXRecord->getNumVBases()) {
  14703. CXXFinalOverriderMap FinalOverriders;
  14704. CXXRecord->getFinalOverriders(FinalOverriders);
  14705. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14706. MEnd = FinalOverriders.end();
  14707. M != MEnd; ++M) {
  14708. for (OverridingMethods::iterator SO = M->second.begin(),
  14709. SOEnd = M->second.end();
  14710. SO != SOEnd; ++SO) {
  14711. assert(SO->second.size() > 0 &&
  14712. "Virtual function without overriding functions?");
  14713. if (SO->second.size() == 1)
  14714. continue;
  14715. // C++ [class.virtual]p2:
  14716. // In a derived class, if a virtual member function of a base
  14717. // class subobject has more than one final overrider the
  14718. // program is ill-formed.
  14719. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14720. << (const NamedDecl *)M->first << Record;
  14721. Diag(M->first->getLocation(),
  14722. diag::note_overridden_virtual_function);
  14723. for (OverridingMethods::overriding_iterator
  14724. OM = SO->second.begin(),
  14725. OMEnd = SO->second.end();
  14726. OM != OMEnd; ++OM)
  14727. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14728. << (const NamedDecl *)M->first << OM->Method->getParent();
  14729. Record->setInvalidDecl();
  14730. }
  14731. }
  14732. CXXRecord->completeDefinition(&FinalOverriders);
  14733. Completed = true;
  14734. }
  14735. }
  14736. }
  14737. }
  14738. if (!Completed)
  14739. Record->completeDefinition();
  14740. // Handle attributes before checking the layout.
  14741. ProcessDeclAttributeList(S, Record, Attrs);
  14742. // We may have deferred checking for a deleted destructor. Check now.
  14743. if (CXXRecord) {
  14744. auto *Dtor = CXXRecord->getDestructor();
  14745. if (Dtor && Dtor->isImplicit() &&
  14746. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14747. CXXRecord->setImplicitDestructorIsDeleted();
  14748. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14749. }
  14750. }
  14751. if (Record->hasAttrs()) {
  14752. CheckAlignasUnderalignment(Record);
  14753. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14754. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14755. IA->getRange(), IA->getBestCase(),
  14756. IA->getSemanticSpelling());
  14757. }
  14758. // Check if the structure/union declaration is a type that can have zero
  14759. // size in C. For C this is a language extension, for C++ it may cause
  14760. // compatibility problems.
  14761. bool CheckForZeroSize;
  14762. if (!getLangOpts().CPlusPlus) {
  14763. CheckForZeroSize = true;
  14764. } else {
  14765. // For C++ filter out types that cannot be referenced in C code.
  14766. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14767. CheckForZeroSize =
  14768. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14769. !CXXRecord->isDependentType() &&
  14770. CXXRecord->isCLike();
  14771. }
  14772. if (CheckForZeroSize) {
  14773. bool ZeroSize = true;
  14774. bool IsEmpty = true;
  14775. unsigned NonBitFields = 0;
  14776. for (RecordDecl::field_iterator I = Record->field_begin(),
  14777. E = Record->field_end();
  14778. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14779. IsEmpty = false;
  14780. if (I->isUnnamedBitfield()) {
  14781. if (!I->isZeroLengthBitField(Context))
  14782. ZeroSize = false;
  14783. } else {
  14784. ++NonBitFields;
  14785. QualType FieldType = I->getType();
  14786. if (FieldType->isIncompleteType() ||
  14787. !Context.getTypeSizeInChars(FieldType).isZero())
  14788. ZeroSize = false;
  14789. }
  14790. }
  14791. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14792. // allowed in C++, but warn if its declaration is inside
  14793. // extern "C" block.
  14794. if (ZeroSize) {
  14795. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14796. diag::warn_zero_size_struct_union_in_extern_c :
  14797. diag::warn_zero_size_struct_union_compat)
  14798. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14799. }
  14800. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14801. // but are accepted by GCC.
  14802. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14803. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14804. diag::ext_no_named_members_in_struct_union)
  14805. << Record->isUnion();
  14806. }
  14807. }
  14808. } else {
  14809. ObjCIvarDecl **ClsFields =
  14810. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14811. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14812. ID->setEndOfDefinitionLoc(RBrac);
  14813. // Add ivar's to class's DeclContext.
  14814. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14815. ClsFields[i]->setLexicalDeclContext(ID);
  14816. ID->addDecl(ClsFields[i]);
  14817. }
  14818. // Must enforce the rule that ivars in the base classes may not be
  14819. // duplicates.
  14820. if (ID->getSuperClass())
  14821. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14822. } else if (ObjCImplementationDecl *IMPDecl =
  14823. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14824. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14825. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14826. // Ivar declared in @implementation never belongs to the implementation.
  14827. // Only it is in implementation's lexical context.
  14828. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14829. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14830. IMPDecl->setIvarLBraceLoc(LBrac);
  14831. IMPDecl->setIvarRBraceLoc(RBrac);
  14832. } else if (ObjCCategoryDecl *CDecl =
  14833. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14834. // case of ivars in class extension; all other cases have been
  14835. // reported as errors elsewhere.
  14836. // FIXME. Class extension does not have a LocEnd field.
  14837. // CDecl->setLocEnd(RBrac);
  14838. // Add ivar's to class extension's DeclContext.
  14839. // Diagnose redeclaration of private ivars.
  14840. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14841. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14842. if (IDecl) {
  14843. if (const ObjCIvarDecl *ClsIvar =
  14844. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14845. Diag(ClsFields[i]->getLocation(),
  14846. diag::err_duplicate_ivar_declaration);
  14847. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14848. continue;
  14849. }
  14850. for (const auto *Ext : IDecl->known_extensions()) {
  14851. if (const ObjCIvarDecl *ClsExtIvar
  14852. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14853. Diag(ClsFields[i]->getLocation(),
  14854. diag::err_duplicate_ivar_declaration);
  14855. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14856. continue;
  14857. }
  14858. }
  14859. }
  14860. ClsFields[i]->setLexicalDeclContext(CDecl);
  14861. CDecl->addDecl(ClsFields[i]);
  14862. }
  14863. CDecl->setIvarLBraceLoc(LBrac);
  14864. CDecl->setIvarRBraceLoc(RBrac);
  14865. }
  14866. }
  14867. }
  14868. /// Determine whether the given integral value is representable within
  14869. /// the given type T.
  14870. static bool isRepresentableIntegerValue(ASTContext &Context,
  14871. llvm::APSInt &Value,
  14872. QualType T) {
  14873. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14874. "Integral type required!");
  14875. unsigned BitWidth = Context.getIntWidth(T);
  14876. if (Value.isUnsigned() || Value.isNonNegative()) {
  14877. if (T->isSignedIntegerOrEnumerationType())
  14878. --BitWidth;
  14879. return Value.getActiveBits() <= BitWidth;
  14880. }
  14881. return Value.getMinSignedBits() <= BitWidth;
  14882. }
  14883. // Given an integral type, return the next larger integral type
  14884. // (or a NULL type of no such type exists).
  14885. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14886. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14887. // enum checking below.
  14888. assert((T->isIntegralType(Context) ||
  14889. T->isEnumeralType()) && "Integral type required!");
  14890. const unsigned NumTypes = 4;
  14891. QualType SignedIntegralTypes[NumTypes] = {
  14892. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14893. };
  14894. QualType UnsignedIntegralTypes[NumTypes] = {
  14895. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14896. Context.UnsignedLongLongTy
  14897. };
  14898. unsigned BitWidth = Context.getTypeSize(T);
  14899. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14900. : UnsignedIntegralTypes;
  14901. for (unsigned I = 0; I != NumTypes; ++I)
  14902. if (Context.getTypeSize(Types[I]) > BitWidth)
  14903. return Types[I];
  14904. return QualType();
  14905. }
  14906. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14907. EnumConstantDecl *LastEnumConst,
  14908. SourceLocation IdLoc,
  14909. IdentifierInfo *Id,
  14910. Expr *Val) {
  14911. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14912. llvm::APSInt EnumVal(IntWidth);
  14913. QualType EltTy;
  14914. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14915. Val = nullptr;
  14916. if (Val)
  14917. Val = DefaultLvalueConversion(Val).get();
  14918. if (Val) {
  14919. if (Enum->isDependentType() || Val->isTypeDependent())
  14920. EltTy = Context.DependentTy;
  14921. else {
  14922. if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
  14923. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14924. // constant-expression in the enumerator-definition shall be a converted
  14925. // constant expression of the underlying type.
  14926. EltTy = Enum->getIntegerType();
  14927. ExprResult Converted =
  14928. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14929. CCEK_Enumerator);
  14930. if (Converted.isInvalid())
  14931. Val = nullptr;
  14932. else
  14933. Val = Converted.get();
  14934. } else if (!Val->isValueDependent() &&
  14935. !(Val = VerifyIntegerConstantExpression(Val,
  14936. &EnumVal).get())) {
  14937. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14938. } else {
  14939. if (Enum->isComplete()) {
  14940. EltTy = Enum->getIntegerType();
  14941. // In Obj-C and Microsoft mode, require the enumeration value to be
  14942. // representable in the underlying type of the enumeration. In C++11,
  14943. // we perform a non-narrowing conversion as part of converted constant
  14944. // expression checking.
  14945. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14946. if (Context.getTargetInfo()
  14947. .getTriple()
  14948. .isWindowsMSVCEnvironment()) {
  14949. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14950. } else {
  14951. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14952. }
  14953. }
  14954. // Cast to the underlying type.
  14955. Val = ImpCastExprToType(Val, EltTy,
  14956. EltTy->isBooleanType() ? CK_IntegralToBoolean
  14957. : CK_IntegralCast)
  14958. .get();
  14959. } else if (getLangOpts().CPlusPlus) {
  14960. // C++11 [dcl.enum]p5:
  14961. // If the underlying type is not fixed, the type of each enumerator
  14962. // is the type of its initializing value:
  14963. // - If an initializer is specified for an enumerator, the
  14964. // initializing value has the same type as the expression.
  14965. EltTy = Val->getType();
  14966. } else {
  14967. // C99 6.7.2.2p2:
  14968. // The expression that defines the value of an enumeration constant
  14969. // shall be an integer constant expression that has a value
  14970. // representable as an int.
  14971. // Complain if the value is not representable in an int.
  14972. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14973. Diag(IdLoc, diag::ext_enum_value_not_int)
  14974. << EnumVal.toString(10) << Val->getSourceRange()
  14975. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14976. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14977. // Force the type of the expression to 'int'.
  14978. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14979. }
  14980. EltTy = Val->getType();
  14981. }
  14982. }
  14983. }
  14984. }
  14985. if (!Val) {
  14986. if (Enum->isDependentType())
  14987. EltTy = Context.DependentTy;
  14988. else if (!LastEnumConst) {
  14989. // C++0x [dcl.enum]p5:
  14990. // If the underlying type is not fixed, the type of each enumerator
  14991. // is the type of its initializing value:
  14992. // - If no initializer is specified for the first enumerator, the
  14993. // initializing value has an unspecified integral type.
  14994. //
  14995. // GCC uses 'int' for its unspecified integral type, as does
  14996. // C99 6.7.2.2p3.
  14997. if (Enum->isFixed()) {
  14998. EltTy = Enum->getIntegerType();
  14999. }
  15000. else {
  15001. EltTy = Context.IntTy;
  15002. }
  15003. } else {
  15004. // Assign the last value + 1.
  15005. EnumVal = LastEnumConst->getInitVal();
  15006. ++EnumVal;
  15007. EltTy = LastEnumConst->getType();
  15008. // Check for overflow on increment.
  15009. if (EnumVal < LastEnumConst->getInitVal()) {
  15010. // C++0x [dcl.enum]p5:
  15011. // If the underlying type is not fixed, the type of each enumerator
  15012. // is the type of its initializing value:
  15013. //
  15014. // - Otherwise the type of the initializing value is the same as
  15015. // the type of the initializing value of the preceding enumerator
  15016. // unless the incremented value is not representable in that type,
  15017. // in which case the type is an unspecified integral type
  15018. // sufficient to contain the incremented value. If no such type
  15019. // exists, the program is ill-formed.
  15020. QualType T = getNextLargerIntegralType(Context, EltTy);
  15021. if (T.isNull() || Enum->isFixed()) {
  15022. // There is no integral type larger enough to represent this
  15023. // value. Complain, then allow the value to wrap around.
  15024. EnumVal = LastEnumConst->getInitVal();
  15025. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  15026. ++EnumVal;
  15027. if (Enum->isFixed())
  15028. // When the underlying type is fixed, this is ill-formed.
  15029. Diag(IdLoc, diag::err_enumerator_wrapped)
  15030. << EnumVal.toString(10)
  15031. << EltTy;
  15032. else
  15033. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  15034. << EnumVal.toString(10);
  15035. } else {
  15036. EltTy = T;
  15037. }
  15038. // Retrieve the last enumerator's value, extent that type to the
  15039. // type that is supposed to be large enough to represent the incremented
  15040. // value, then increment.
  15041. EnumVal = LastEnumConst->getInitVal();
  15042. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  15043. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  15044. ++EnumVal;
  15045. // If we're not in C++, diagnose the overflow of enumerator values,
  15046. // which in C99 means that the enumerator value is not representable in
  15047. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  15048. // permits enumerator values that are representable in some larger
  15049. // integral type.
  15050. if (!getLangOpts().CPlusPlus && !T.isNull())
  15051. Diag(IdLoc, diag::warn_enum_value_overflow);
  15052. } else if (!getLangOpts().CPlusPlus &&
  15053. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  15054. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  15055. Diag(IdLoc, diag::ext_enum_value_not_int)
  15056. << EnumVal.toString(10) << 1;
  15057. }
  15058. }
  15059. }
  15060. if (!EltTy->isDependentType()) {
  15061. // Make the enumerator value match the signedness and size of the
  15062. // enumerator's type.
  15063. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  15064. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  15065. }
  15066. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  15067. Val, EnumVal);
  15068. }
  15069. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  15070. SourceLocation IILoc) {
  15071. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  15072. !getLangOpts().CPlusPlus)
  15073. return SkipBodyInfo();
  15074. // We have an anonymous enum definition. Look up the first enumerator to
  15075. // determine if we should merge the definition with an existing one and
  15076. // skip the body.
  15077. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  15078. forRedeclarationInCurContext());
  15079. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  15080. if (!PrevECD)
  15081. return SkipBodyInfo();
  15082. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  15083. NamedDecl *Hidden;
  15084. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  15085. SkipBodyInfo Skip;
  15086. Skip.Previous = Hidden;
  15087. return Skip;
  15088. }
  15089. return SkipBodyInfo();
  15090. }
  15091. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  15092. SourceLocation IdLoc, IdentifierInfo *Id,
  15093. const ParsedAttributesView &Attrs,
  15094. SourceLocation EqualLoc, Expr *Val) {
  15095. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  15096. EnumConstantDecl *LastEnumConst =
  15097. cast_or_null<EnumConstantDecl>(lastEnumConst);
  15098. // The scope passed in may not be a decl scope. Zip up the scope tree until
  15099. // we find one that is.
  15100. S = getNonFieldDeclScope(S);
  15101. // Verify that there isn't already something declared with this name in this
  15102. // scope.
  15103. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  15104. LookupName(R, S);
  15105. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  15106. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  15107. // Maybe we will complain about the shadowed template parameter.
  15108. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  15109. // Just pretend that we didn't see the previous declaration.
  15110. PrevDecl = nullptr;
  15111. }
  15112. // C++ [class.mem]p15:
  15113. // If T is the name of a class, then each of the following shall have a name
  15114. // different from T:
  15115. // - every enumerator of every member of class T that is an unscoped
  15116. // enumerated type
  15117. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  15118. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  15119. DeclarationNameInfo(Id, IdLoc));
  15120. EnumConstantDecl *New =
  15121. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  15122. if (!New)
  15123. return nullptr;
  15124. if (PrevDecl) {
  15125. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  15126. // Check for other kinds of shadowing not already handled.
  15127. CheckShadow(New, PrevDecl, R);
  15128. }
  15129. // When in C++, we may get a TagDecl with the same name; in this case the
  15130. // enum constant will 'hide' the tag.
  15131. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  15132. "Received TagDecl when not in C++!");
  15133. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  15134. if (isa<EnumConstantDecl>(PrevDecl))
  15135. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  15136. else
  15137. Diag(IdLoc, diag::err_redefinition) << Id;
  15138. notePreviousDefinition(PrevDecl, IdLoc);
  15139. return nullptr;
  15140. }
  15141. }
  15142. // Process attributes.
  15143. ProcessDeclAttributeList(S, New, Attrs);
  15144. AddPragmaAttributes(S, New);
  15145. // Register this decl in the current scope stack.
  15146. New->setAccess(TheEnumDecl->getAccess());
  15147. PushOnScopeChains(New, S);
  15148. ActOnDocumentableDecl(New);
  15149. return New;
  15150. }
  15151. // Returns true when the enum initial expression does not trigger the
  15152. // duplicate enum warning. A few common cases are exempted as follows:
  15153. // Element2 = Element1
  15154. // Element2 = Element1 + 1
  15155. // Element2 = Element1 - 1
  15156. // Where Element2 and Element1 are from the same enum.
  15157. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  15158. Expr *InitExpr = ECD->getInitExpr();
  15159. if (!InitExpr)
  15160. return true;
  15161. InitExpr = InitExpr->IgnoreImpCasts();
  15162. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  15163. if (!BO->isAdditiveOp())
  15164. return true;
  15165. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  15166. if (!IL)
  15167. return true;
  15168. if (IL->getValue() != 1)
  15169. return true;
  15170. InitExpr = BO->getLHS();
  15171. }
  15172. // This checks if the elements are from the same enum.
  15173. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  15174. if (!DRE)
  15175. return true;
  15176. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  15177. if (!EnumConstant)
  15178. return true;
  15179. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  15180. Enum)
  15181. return true;
  15182. return false;
  15183. }
  15184. // Emits a warning when an element is implicitly set a value that
  15185. // a previous element has already been set to.
  15186. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  15187. EnumDecl *Enum, QualType EnumType) {
  15188. // Avoid anonymous enums
  15189. if (!Enum->getIdentifier())
  15190. return;
  15191. // Only check for small enums.
  15192. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  15193. return;
  15194. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  15195. return;
  15196. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  15197. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  15198. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  15199. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  15200. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  15201. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  15202. llvm::APSInt Val = D->getInitVal();
  15203. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  15204. };
  15205. DuplicatesVector DupVector;
  15206. ValueToVectorMap EnumMap;
  15207. // Populate the EnumMap with all values represented by enum constants without
  15208. // an initializer.
  15209. for (auto *Element : Elements) {
  15210. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  15211. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  15212. // this constant. Skip this enum since it may be ill-formed.
  15213. if (!ECD) {
  15214. return;
  15215. }
  15216. // Constants with initalizers are handled in the next loop.
  15217. if (ECD->getInitExpr())
  15218. continue;
  15219. // Duplicate values are handled in the next loop.
  15220. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  15221. }
  15222. if (EnumMap.size() == 0)
  15223. return;
  15224. // Create vectors for any values that has duplicates.
  15225. for (auto *Element : Elements) {
  15226. // The last loop returned if any constant was null.
  15227. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  15228. if (!ValidDuplicateEnum(ECD, Enum))
  15229. continue;
  15230. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  15231. if (Iter == EnumMap.end())
  15232. continue;
  15233. DeclOrVector& Entry = Iter->second;
  15234. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  15235. // Ensure constants are different.
  15236. if (D == ECD)
  15237. continue;
  15238. // Create new vector and push values onto it.
  15239. auto Vec = std::make_unique<ECDVector>();
  15240. Vec->push_back(D);
  15241. Vec->push_back(ECD);
  15242. // Update entry to point to the duplicates vector.
  15243. Entry = Vec.get();
  15244. // Store the vector somewhere we can consult later for quick emission of
  15245. // diagnostics.
  15246. DupVector.emplace_back(std::move(Vec));
  15247. continue;
  15248. }
  15249. ECDVector *Vec = Entry.get<ECDVector*>();
  15250. // Make sure constants are not added more than once.
  15251. if (*Vec->begin() == ECD)
  15252. continue;
  15253. Vec->push_back(ECD);
  15254. }
  15255. // Emit diagnostics.
  15256. for (const auto &Vec : DupVector) {
  15257. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  15258. // Emit warning for one enum constant.
  15259. auto *FirstECD = Vec->front();
  15260. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  15261. << FirstECD << FirstECD->getInitVal().toString(10)
  15262. << FirstECD->getSourceRange();
  15263. // Emit one note for each of the remaining enum constants with
  15264. // the same value.
  15265. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  15266. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  15267. << ECD << ECD->getInitVal().toString(10)
  15268. << ECD->getSourceRange();
  15269. }
  15270. }
  15271. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  15272. bool AllowMask) const {
  15273. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  15274. assert(ED->isCompleteDefinition() && "expected enum definition");
  15275. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  15276. llvm::APInt &FlagBits = R.first->second;
  15277. if (R.second) {
  15278. for (auto *E : ED->enumerators()) {
  15279. const auto &EVal = E->getInitVal();
  15280. // Only single-bit enumerators introduce new flag values.
  15281. if (EVal.isPowerOf2())
  15282. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  15283. }
  15284. }
  15285. // A value is in a flag enum if either its bits are a subset of the enum's
  15286. // flag bits (the first condition) or we are allowing masks and the same is
  15287. // true of its complement (the second condition). When masks are allowed, we
  15288. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  15289. //
  15290. // While it's true that any value could be used as a mask, the assumption is
  15291. // that a mask will have all of the insignificant bits set. Anything else is
  15292. // likely a logic error.
  15293. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  15294. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  15295. }
  15296. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  15297. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  15298. const ParsedAttributesView &Attrs) {
  15299. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  15300. QualType EnumType = Context.getTypeDeclType(Enum);
  15301. ProcessDeclAttributeList(S, Enum, Attrs);
  15302. if (Enum->isDependentType()) {
  15303. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15304. EnumConstantDecl *ECD =
  15305. cast_or_null<EnumConstantDecl>(Elements[i]);
  15306. if (!ECD) continue;
  15307. ECD->setType(EnumType);
  15308. }
  15309. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  15310. return;
  15311. }
  15312. // TODO: If the result value doesn't fit in an int, it must be a long or long
  15313. // long value. ISO C does not support this, but GCC does as an extension,
  15314. // emit a warning.
  15315. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15316. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  15317. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  15318. // Verify that all the values are okay, compute the size of the values, and
  15319. // reverse the list.
  15320. unsigned NumNegativeBits = 0;
  15321. unsigned NumPositiveBits = 0;
  15322. // Keep track of whether all elements have type int.
  15323. bool AllElementsInt = true;
  15324. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15325. EnumConstantDecl *ECD =
  15326. cast_or_null<EnumConstantDecl>(Elements[i]);
  15327. if (!ECD) continue; // Already issued a diagnostic.
  15328. const llvm::APSInt &InitVal = ECD->getInitVal();
  15329. // Keep track of the size of positive and negative values.
  15330. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  15331. NumPositiveBits = std::max(NumPositiveBits,
  15332. (unsigned)InitVal.getActiveBits());
  15333. else
  15334. NumNegativeBits = std::max(NumNegativeBits,
  15335. (unsigned)InitVal.getMinSignedBits());
  15336. // Keep track of whether every enum element has type int (very common).
  15337. if (AllElementsInt)
  15338. AllElementsInt = ECD->getType() == Context.IntTy;
  15339. }
  15340. // Figure out the type that should be used for this enum.
  15341. QualType BestType;
  15342. unsigned BestWidth;
  15343. // C++0x N3000 [conv.prom]p3:
  15344. // An rvalue of an unscoped enumeration type whose underlying
  15345. // type is not fixed can be converted to an rvalue of the first
  15346. // of the following types that can represent all the values of
  15347. // the enumeration: int, unsigned int, long int, unsigned long
  15348. // int, long long int, or unsigned long long int.
  15349. // C99 6.4.4.3p2:
  15350. // An identifier declared as an enumeration constant has type int.
  15351. // The C99 rule is modified by a gcc extension
  15352. QualType BestPromotionType;
  15353. bool Packed = Enum->hasAttr<PackedAttr>();
  15354. // -fshort-enums is the equivalent to specifying the packed attribute on all
  15355. // enum definitions.
  15356. if (LangOpts.ShortEnums)
  15357. Packed = true;
  15358. // If the enum already has a type because it is fixed or dictated by the
  15359. // target, promote that type instead of analyzing the enumerators.
  15360. if (Enum->isComplete()) {
  15361. BestType = Enum->getIntegerType();
  15362. if (BestType->isPromotableIntegerType())
  15363. BestPromotionType = Context.getPromotedIntegerType(BestType);
  15364. else
  15365. BestPromotionType = BestType;
  15366. BestWidth = Context.getIntWidth(BestType);
  15367. }
  15368. else if (NumNegativeBits) {
  15369. // If there is a negative value, figure out the smallest integer type (of
  15370. // int/long/longlong) that fits.
  15371. // If it's packed, check also if it fits a char or a short.
  15372. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  15373. BestType = Context.SignedCharTy;
  15374. BestWidth = CharWidth;
  15375. } else if (Packed && NumNegativeBits <= ShortWidth &&
  15376. NumPositiveBits < ShortWidth) {
  15377. BestType = Context.ShortTy;
  15378. BestWidth = ShortWidth;
  15379. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  15380. BestType = Context.IntTy;
  15381. BestWidth = IntWidth;
  15382. } else {
  15383. BestWidth = Context.getTargetInfo().getLongWidth();
  15384. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  15385. BestType = Context.LongTy;
  15386. } else {
  15387. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15388. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  15389. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  15390. BestType = Context.LongLongTy;
  15391. }
  15392. }
  15393. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  15394. } else {
  15395. // If there is no negative value, figure out the smallest type that fits
  15396. // all of the enumerator values.
  15397. // If it's packed, check also if it fits a char or a short.
  15398. if (Packed && NumPositiveBits <= CharWidth) {
  15399. BestType = Context.UnsignedCharTy;
  15400. BestPromotionType = Context.IntTy;
  15401. BestWidth = CharWidth;
  15402. } else if (Packed && NumPositiveBits <= ShortWidth) {
  15403. BestType = Context.UnsignedShortTy;
  15404. BestPromotionType = Context.IntTy;
  15405. BestWidth = ShortWidth;
  15406. } else if (NumPositiveBits <= IntWidth) {
  15407. BestType = Context.UnsignedIntTy;
  15408. BestWidth = IntWidth;
  15409. BestPromotionType
  15410. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15411. ? Context.UnsignedIntTy : Context.IntTy;
  15412. } else if (NumPositiveBits <=
  15413. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  15414. BestType = Context.UnsignedLongTy;
  15415. BestPromotionType
  15416. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15417. ? Context.UnsignedLongTy : Context.LongTy;
  15418. } else {
  15419. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15420. assert(NumPositiveBits <= BestWidth &&
  15421. "How could an initializer get larger than ULL?");
  15422. BestType = Context.UnsignedLongLongTy;
  15423. BestPromotionType
  15424. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15425. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  15426. }
  15427. }
  15428. // Loop over all of the enumerator constants, changing their types to match
  15429. // the type of the enum if needed.
  15430. for (auto *D : Elements) {
  15431. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  15432. if (!ECD) continue; // Already issued a diagnostic.
  15433. // Standard C says the enumerators have int type, but we allow, as an
  15434. // extension, the enumerators to be larger than int size. If each
  15435. // enumerator value fits in an int, type it as an int, otherwise type it the
  15436. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15437. // that X has type 'int', not 'unsigned'.
  15438. // Determine whether the value fits into an int.
  15439. llvm::APSInt InitVal = ECD->getInitVal();
  15440. // If it fits into an integer type, force it. Otherwise force it to match
  15441. // the enum decl type.
  15442. QualType NewTy;
  15443. unsigned NewWidth;
  15444. bool NewSign;
  15445. if (!getLangOpts().CPlusPlus &&
  15446. !Enum->isFixed() &&
  15447. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15448. NewTy = Context.IntTy;
  15449. NewWidth = IntWidth;
  15450. NewSign = true;
  15451. } else if (ECD->getType() == BestType) {
  15452. // Already the right type!
  15453. if (getLangOpts().CPlusPlus)
  15454. // C++ [dcl.enum]p4: Following the closing brace of an
  15455. // enum-specifier, each enumerator has the type of its
  15456. // enumeration.
  15457. ECD->setType(EnumType);
  15458. continue;
  15459. } else {
  15460. NewTy = BestType;
  15461. NewWidth = BestWidth;
  15462. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15463. }
  15464. // Adjust the APSInt value.
  15465. InitVal = InitVal.extOrTrunc(NewWidth);
  15466. InitVal.setIsSigned(NewSign);
  15467. ECD->setInitVal(InitVal);
  15468. // Adjust the Expr initializer and type.
  15469. if (ECD->getInitExpr() &&
  15470. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15471. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15472. CK_IntegralCast,
  15473. ECD->getInitExpr(),
  15474. /*base paths*/ nullptr,
  15475. VK_RValue));
  15476. if (getLangOpts().CPlusPlus)
  15477. // C++ [dcl.enum]p4: Following the closing brace of an
  15478. // enum-specifier, each enumerator has the type of its
  15479. // enumeration.
  15480. ECD->setType(EnumType);
  15481. else
  15482. ECD->setType(NewTy);
  15483. }
  15484. Enum->completeDefinition(BestType, BestPromotionType,
  15485. NumPositiveBits, NumNegativeBits);
  15486. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15487. if (Enum->isClosedFlag()) {
  15488. for (Decl *D : Elements) {
  15489. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15490. if (!ECD) continue; // Already issued a diagnostic.
  15491. llvm::APSInt InitVal = ECD->getInitVal();
  15492. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15493. !IsValueInFlagEnum(Enum, InitVal, true))
  15494. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15495. << ECD << Enum;
  15496. }
  15497. }
  15498. // Now that the enum type is defined, ensure it's not been underaligned.
  15499. if (Enum->hasAttrs())
  15500. CheckAlignasUnderalignment(Enum);
  15501. }
  15502. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15503. SourceLocation StartLoc,
  15504. SourceLocation EndLoc) {
  15505. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15506. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15507. AsmString, StartLoc,
  15508. EndLoc);
  15509. CurContext->addDecl(New);
  15510. return New;
  15511. }
  15512. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15513. IdentifierInfo* AliasName,
  15514. SourceLocation PragmaLoc,
  15515. SourceLocation NameLoc,
  15516. SourceLocation AliasNameLoc) {
  15517. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15518. LookupOrdinaryName);
  15519. AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
  15520. AttributeCommonInfo::AS_Pragma);
  15521. AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
  15522. Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
  15523. // If a declaration that:
  15524. // 1) declares a function or a variable
  15525. // 2) has external linkage
  15526. // already exists, add a label attribute to it.
  15527. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15528. if (isDeclExternC(PrevDecl))
  15529. PrevDecl->addAttr(Attr);
  15530. else
  15531. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15532. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15533. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15534. } else
  15535. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15536. }
  15537. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15538. SourceLocation PragmaLoc,
  15539. SourceLocation NameLoc) {
  15540. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15541. if (PrevDecl) {
  15542. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
  15543. } else {
  15544. (void)WeakUndeclaredIdentifiers.insert(
  15545. std::pair<IdentifierInfo*,WeakInfo>
  15546. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15547. }
  15548. }
  15549. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15550. IdentifierInfo* AliasName,
  15551. SourceLocation PragmaLoc,
  15552. SourceLocation NameLoc,
  15553. SourceLocation AliasNameLoc) {
  15554. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15555. LookupOrdinaryName);
  15556. WeakInfo W = WeakInfo(Name, NameLoc);
  15557. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15558. if (!PrevDecl->hasAttr<AliasAttr>())
  15559. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15560. DeclApplyPragmaWeak(TUScope, ND, W);
  15561. } else {
  15562. (void)WeakUndeclaredIdentifiers.insert(
  15563. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15564. }
  15565. }
  15566. Decl *Sema::getObjCDeclContext() const {
  15567. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15568. }
  15569. Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
  15570. // Templates are emitted when they're instantiated.
  15571. if (FD->isDependentContext())
  15572. return FunctionEmissionStatus::TemplateDiscarded;
  15573. FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
  15574. if (LangOpts.OpenMPIsDevice) {
  15575. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  15576. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  15577. if (DevTy.hasValue()) {
  15578. if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  15579. OMPES = FunctionEmissionStatus::OMPDiscarded;
  15580. else if (DeviceKnownEmittedFns.count(FD) > 0)
  15581. OMPES = FunctionEmissionStatus::Emitted;
  15582. }
  15583. } else if (LangOpts.OpenMP) {
  15584. // In OpenMP 4.5 all the functions are host functions.
  15585. if (LangOpts.OpenMP <= 45) {
  15586. OMPES = FunctionEmissionStatus::Emitted;
  15587. } else {
  15588. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  15589. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  15590. // In OpenMP 5.0 or above, DevTy may be changed later by
  15591. // #pragma omp declare target to(*) device_type(*). Therefore DevTy
  15592. // having no value does not imply host. The emission status will be
  15593. // checked again at the end of compilation unit.
  15594. if (DevTy.hasValue()) {
  15595. if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  15596. OMPES = FunctionEmissionStatus::OMPDiscarded;
  15597. } else if (DeviceKnownEmittedFns.count(FD) > 0) {
  15598. OMPES = FunctionEmissionStatus::Emitted;
  15599. }
  15600. }
  15601. }
  15602. }
  15603. if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
  15604. (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
  15605. return OMPES;
  15606. if (LangOpts.CUDA) {
  15607. // When compiling for device, host functions are never emitted. Similarly,
  15608. // when compiling for host, device and global functions are never emitted.
  15609. // (Technically, we do emit a host-side stub for global functions, but this
  15610. // doesn't count for our purposes here.)
  15611. Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
  15612. if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
  15613. return FunctionEmissionStatus::CUDADiscarded;
  15614. if (!LangOpts.CUDAIsDevice &&
  15615. (T == Sema::CFT_Device || T == Sema::CFT_Global))
  15616. return FunctionEmissionStatus::CUDADiscarded;
  15617. // Check whether this function is externally visible -- if so, it's
  15618. // known-emitted.
  15619. //
  15620. // We have to check the GVA linkage of the function's *definition* -- if we
  15621. // only have a declaration, we don't know whether or not the function will
  15622. // be emitted, because (say) the definition could include "inline".
  15623. FunctionDecl *Def = FD->getDefinition();
  15624. if (Def &&
  15625. !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
  15626. && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
  15627. return FunctionEmissionStatus::Emitted;
  15628. }
  15629. // Otherwise, the function is known-emitted if it's in our set of
  15630. // known-emitted functions.
  15631. return (DeviceKnownEmittedFns.count(FD) > 0)
  15632. ? FunctionEmissionStatus::Emitted
  15633. : FunctionEmissionStatus::Unknown;
  15634. }
  15635. bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
  15636. // Host-side references to a __global__ function refer to the stub, so the
  15637. // function itself is never emitted and therefore should not be marked.
  15638. // If we have host fn calls kernel fn calls host+device, the HD function
  15639. // does not get instantiated on the host. We model this by omitting at the
  15640. // call to the kernel from the callgraph. This ensures that, when compiling
  15641. // for host, only HD functions actually called from the host get marked as
  15642. // known-emitted.
  15643. return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  15644. IdentifyCUDATarget(Callee) == CFT_Global;
  15645. }