SemaDecl.cpp 677 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428
  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 llvm::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. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1746. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1747. << Context.BuiltinInfo.getName(ID);
  1748. return nullptr;
  1749. }
  1750. if (!ForRedeclaration &&
  1751. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1752. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1753. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1754. << Context.BuiltinInfo.getName(ID) << R;
  1755. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1756. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1757. Diag(Loc, diag::note_include_header_or_declare)
  1758. << Context.BuiltinInfo.getHeaderName(ID)
  1759. << Context.BuiltinInfo.getName(ID);
  1760. }
  1761. if (R.isNull())
  1762. return nullptr;
  1763. DeclContext *Parent = Context.getTranslationUnitDecl();
  1764. if (getLangOpts().CPlusPlus) {
  1765. LinkageSpecDecl *CLinkageDecl =
  1766. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1767. LinkageSpecDecl::lang_c, false);
  1768. CLinkageDecl->setImplicit();
  1769. Parent->addDecl(CLinkageDecl);
  1770. Parent = CLinkageDecl;
  1771. }
  1772. FunctionDecl *New = FunctionDecl::Create(Context,
  1773. Parent,
  1774. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1775. SC_Extern,
  1776. false,
  1777. R->isFunctionProtoType());
  1778. New->setImplicit();
  1779. // Create Decl objects for each parameter, adding them to the
  1780. // FunctionDecl.
  1781. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1782. SmallVector<ParmVarDecl*, 16> Params;
  1783. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1784. ParmVarDecl *parm =
  1785. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1786. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1787. SC_None, nullptr);
  1788. parm->setScopeInfo(0, i);
  1789. Params.push_back(parm);
  1790. }
  1791. New->setParams(Params);
  1792. }
  1793. AddKnownFunctionAttributes(New);
  1794. RegisterLocallyScopedExternCDecl(New, S);
  1795. // TUScope is the translation-unit scope to insert this function into.
  1796. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1797. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1798. // entirely, but we're not there yet.
  1799. DeclContext *SavedContext = CurContext;
  1800. CurContext = Parent;
  1801. PushOnScopeChains(New, TUScope);
  1802. CurContext = SavedContext;
  1803. return New;
  1804. }
  1805. /// Typedef declarations don't have linkage, but they still denote the same
  1806. /// entity if their types are the same.
  1807. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1808. /// isSameEntity.
  1809. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1810. TypedefNameDecl *Decl,
  1811. LookupResult &Previous) {
  1812. // This is only interesting when modules are enabled.
  1813. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1814. return;
  1815. // Empty sets are uninteresting.
  1816. if (Previous.empty())
  1817. return;
  1818. LookupResult::Filter Filter = Previous.makeFilter();
  1819. while (Filter.hasNext()) {
  1820. NamedDecl *Old = Filter.next();
  1821. // Non-hidden declarations are never ignored.
  1822. if (S.isVisible(Old))
  1823. continue;
  1824. // Declarations of the same entity are not ignored, even if they have
  1825. // different linkages.
  1826. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1827. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1828. Decl->getUnderlyingType()))
  1829. continue;
  1830. // If both declarations give a tag declaration a typedef name for linkage
  1831. // purposes, then they declare the same entity.
  1832. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1833. Decl->getAnonDeclWithTypedefName())
  1834. continue;
  1835. }
  1836. Filter.erase();
  1837. }
  1838. Filter.done();
  1839. }
  1840. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1841. QualType OldType;
  1842. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1843. OldType = OldTypedef->getUnderlyingType();
  1844. else
  1845. OldType = Context.getTypeDeclType(Old);
  1846. QualType NewType = New->getUnderlyingType();
  1847. if (NewType->isVariablyModifiedType()) {
  1848. // Must not redefine a typedef with a variably-modified type.
  1849. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1850. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1851. << Kind << NewType;
  1852. if (Old->getLocation().isValid())
  1853. notePreviousDefinition(Old, New->getLocation());
  1854. New->setInvalidDecl();
  1855. return true;
  1856. }
  1857. if (OldType != NewType &&
  1858. !OldType->isDependentType() &&
  1859. !NewType->isDependentType() &&
  1860. !Context.hasSameType(OldType, NewType)) {
  1861. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1862. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1863. << Kind << NewType << OldType;
  1864. if (Old->getLocation().isValid())
  1865. notePreviousDefinition(Old, New->getLocation());
  1866. New->setInvalidDecl();
  1867. return true;
  1868. }
  1869. return false;
  1870. }
  1871. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1872. /// same name and scope as a previous declaration 'Old'. Figure out
  1873. /// how to resolve this situation, merging decls or emitting
  1874. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1875. ///
  1876. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1877. LookupResult &OldDecls) {
  1878. // If the new decl is known invalid already, don't bother doing any
  1879. // merging checks.
  1880. if (New->isInvalidDecl()) return;
  1881. // Allow multiple definitions for ObjC built-in typedefs.
  1882. // FIXME: Verify the underlying types are equivalent!
  1883. if (getLangOpts().ObjC) {
  1884. const IdentifierInfo *TypeID = New->getIdentifier();
  1885. switch (TypeID->getLength()) {
  1886. default: break;
  1887. case 2:
  1888. {
  1889. if (!TypeID->isStr("id"))
  1890. break;
  1891. QualType T = New->getUnderlyingType();
  1892. if (!T->isPointerType())
  1893. break;
  1894. if (!T->isVoidPointerType()) {
  1895. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1896. if (!PT->isStructureType())
  1897. break;
  1898. }
  1899. Context.setObjCIdRedefinitionType(T);
  1900. // Install the built-in type for 'id', ignoring the current definition.
  1901. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1902. return;
  1903. }
  1904. case 5:
  1905. if (!TypeID->isStr("Class"))
  1906. break;
  1907. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1908. // Install the built-in type for 'Class', ignoring the current definition.
  1909. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1910. return;
  1911. case 3:
  1912. if (!TypeID->isStr("SEL"))
  1913. break;
  1914. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1915. // Install the built-in type for 'SEL', ignoring the current definition.
  1916. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1917. return;
  1918. }
  1919. // Fall through - the typedef name was not a builtin type.
  1920. }
  1921. // Verify the old decl was also a type.
  1922. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1923. if (!Old) {
  1924. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1925. << New->getDeclName();
  1926. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1927. if (OldD->getLocation().isValid())
  1928. notePreviousDefinition(OldD, New->getLocation());
  1929. return New->setInvalidDecl();
  1930. }
  1931. // If the old declaration is invalid, just give up here.
  1932. if (Old->isInvalidDecl())
  1933. return New->setInvalidDecl();
  1934. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1935. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1936. auto *NewTag = New->getAnonDeclWithTypedefName();
  1937. NamedDecl *Hidden = nullptr;
  1938. if (OldTag && NewTag &&
  1939. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1940. !hasVisibleDefinition(OldTag, &Hidden)) {
  1941. // There is a definition of this tag, but it is not visible. Use it
  1942. // instead of our tag.
  1943. New->setTypeForDecl(OldTD->getTypeForDecl());
  1944. if (OldTD->isModed())
  1945. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1946. OldTD->getUnderlyingType());
  1947. else
  1948. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1949. // Make the old tag definition visible.
  1950. makeMergedDefinitionVisible(Hidden);
  1951. // If this was an unscoped enumeration, yank all of its enumerators
  1952. // out of the scope.
  1953. if (isa<EnumDecl>(NewTag)) {
  1954. Scope *EnumScope = getNonFieldDeclScope(S);
  1955. for (auto *D : NewTag->decls()) {
  1956. auto *ED = cast<EnumConstantDecl>(D);
  1957. assert(EnumScope->isDeclScope(ED));
  1958. EnumScope->RemoveDecl(ED);
  1959. IdResolver.RemoveDecl(ED);
  1960. ED->getLexicalDeclContext()->removeDecl(ED);
  1961. }
  1962. }
  1963. }
  1964. }
  1965. // If the typedef types are not identical, reject them in all languages and
  1966. // with any extensions enabled.
  1967. if (isIncompatibleTypedef(Old, New))
  1968. return;
  1969. // The types match. Link up the redeclaration chain and merge attributes if
  1970. // the old declaration was a typedef.
  1971. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1972. New->setPreviousDecl(Typedef);
  1973. mergeDeclAttributes(New, Old);
  1974. }
  1975. if (getLangOpts().MicrosoftExt)
  1976. return;
  1977. if (getLangOpts().CPlusPlus) {
  1978. // C++ [dcl.typedef]p2:
  1979. // In a given non-class scope, a typedef specifier can be used to
  1980. // redefine the name of any type declared in that scope to refer
  1981. // to the type to which it already refers.
  1982. if (!isa<CXXRecordDecl>(CurContext))
  1983. return;
  1984. // C++0x [dcl.typedef]p4:
  1985. // In a given class scope, a typedef specifier can be used to redefine
  1986. // any class-name declared in that scope that is not also a typedef-name
  1987. // to refer to the type to which it already refers.
  1988. //
  1989. // This wording came in via DR424, which was a correction to the
  1990. // wording in DR56, which accidentally banned code like:
  1991. //
  1992. // struct S {
  1993. // typedef struct A { } A;
  1994. // };
  1995. //
  1996. // in the C++03 standard. We implement the C++0x semantics, which
  1997. // allow the above but disallow
  1998. //
  1999. // struct S {
  2000. // typedef int I;
  2001. // typedef int I;
  2002. // };
  2003. //
  2004. // since that was the intent of DR56.
  2005. if (!isa<TypedefNameDecl>(Old))
  2006. return;
  2007. Diag(New->getLocation(), diag::err_redefinition)
  2008. << New->getDeclName();
  2009. notePreviousDefinition(Old, New->getLocation());
  2010. return New->setInvalidDecl();
  2011. }
  2012. // Modules always permit redefinition of typedefs, as does C11.
  2013. if (getLangOpts().Modules || getLangOpts().C11)
  2014. return;
  2015. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2016. // is normally mapped to an error, but can be controlled with
  2017. // -Wtypedef-redefinition. If either the original or the redefinition is
  2018. // in a system header, don't emit this for compatibility with GCC.
  2019. if (getDiagnostics().getSuppressSystemWarnings() &&
  2020. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2021. (Old->isImplicit() ||
  2022. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2023. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2024. return;
  2025. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2026. << New->getDeclName();
  2027. notePreviousDefinition(Old, New->getLocation());
  2028. }
  2029. /// DeclhasAttr - returns true if decl Declaration already has the target
  2030. /// attribute.
  2031. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2032. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2033. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2034. for (const auto *i : D->attrs())
  2035. if (i->getKind() == A->getKind()) {
  2036. if (Ann) {
  2037. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2038. return true;
  2039. continue;
  2040. }
  2041. // FIXME: Don't hardcode this check
  2042. if (OA && isa<OwnershipAttr>(i))
  2043. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2044. return true;
  2045. }
  2046. return false;
  2047. }
  2048. static bool isAttributeTargetADefinition(Decl *D) {
  2049. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2050. return VD->isThisDeclarationADefinition();
  2051. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2052. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2053. return true;
  2054. }
  2055. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2056. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2057. ///
  2058. /// \return \c true if any attributes were added to \p New.
  2059. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2060. // Look for alignas attributes on Old, and pick out whichever attribute
  2061. // specifies the strictest alignment requirement.
  2062. AlignedAttr *OldAlignasAttr = nullptr;
  2063. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2064. unsigned OldAlign = 0;
  2065. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2066. // FIXME: We have no way of representing inherited dependent alignments
  2067. // in a case like:
  2068. // template<int A, int B> struct alignas(A) X;
  2069. // template<int A, int B> struct alignas(B) X {};
  2070. // For now, we just ignore any alignas attributes which are not on the
  2071. // definition in such a case.
  2072. if (I->isAlignmentDependent())
  2073. return false;
  2074. if (I->isAlignas())
  2075. OldAlignasAttr = I;
  2076. unsigned Align = I->getAlignment(S.Context);
  2077. if (Align > OldAlign) {
  2078. OldAlign = Align;
  2079. OldStrictestAlignAttr = I;
  2080. }
  2081. }
  2082. // Look for alignas attributes on New.
  2083. AlignedAttr *NewAlignasAttr = nullptr;
  2084. unsigned NewAlign = 0;
  2085. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2086. if (I->isAlignmentDependent())
  2087. return false;
  2088. if (I->isAlignas())
  2089. NewAlignasAttr = I;
  2090. unsigned Align = I->getAlignment(S.Context);
  2091. if (Align > NewAlign)
  2092. NewAlign = Align;
  2093. }
  2094. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2095. // Both declarations have 'alignas' attributes. We require them to match.
  2096. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2097. // fall short. (If two declarations both have alignas, they must both match
  2098. // every definition, and so must match each other if there is a definition.)
  2099. // If either declaration only contains 'alignas(0)' specifiers, then it
  2100. // specifies the natural alignment for the type.
  2101. if (OldAlign == 0 || NewAlign == 0) {
  2102. QualType Ty;
  2103. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2104. Ty = VD->getType();
  2105. else
  2106. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2107. if (OldAlign == 0)
  2108. OldAlign = S.Context.getTypeAlign(Ty);
  2109. if (NewAlign == 0)
  2110. NewAlign = S.Context.getTypeAlign(Ty);
  2111. }
  2112. if (OldAlign != NewAlign) {
  2113. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2114. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2115. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2116. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2117. }
  2118. }
  2119. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2120. // C++11 [dcl.align]p6:
  2121. // if any declaration of an entity has an alignment-specifier,
  2122. // every defining declaration of that entity shall specify an
  2123. // equivalent alignment.
  2124. // C11 6.7.5/7:
  2125. // If the definition of an object does not have an alignment
  2126. // specifier, any other declaration of that object shall also
  2127. // have no alignment specifier.
  2128. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2129. << OldAlignasAttr;
  2130. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2131. << OldAlignasAttr;
  2132. }
  2133. bool AnyAdded = false;
  2134. // Ensure we have an attribute representing the strictest alignment.
  2135. if (OldAlign > NewAlign) {
  2136. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2137. Clone->setInherited(true);
  2138. New->addAttr(Clone);
  2139. AnyAdded = true;
  2140. }
  2141. // Ensure we have an alignas attribute if the old declaration had one.
  2142. if (OldAlignasAttr && !NewAlignasAttr &&
  2143. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2144. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2145. Clone->setInherited(true);
  2146. New->addAttr(Clone);
  2147. AnyAdded = true;
  2148. }
  2149. return AnyAdded;
  2150. }
  2151. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2152. const InheritableAttr *Attr,
  2153. Sema::AvailabilityMergeKind AMK) {
  2154. // This function copies an attribute Attr from a previous declaration to the
  2155. // new declaration D if the new declaration doesn't itself have that attribute
  2156. // yet or if that attribute allows duplicates.
  2157. // If you're adding a new attribute that requires logic different from
  2158. // "use explicit attribute on decl if present, else use attribute from
  2159. // previous decl", for example if the attribute needs to be consistent
  2160. // between redeclarations, you need to call a custom merge function here.
  2161. InheritableAttr *NewAttr = nullptr;
  2162. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2163. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2164. NewAttr = S.mergeAvailabilityAttr(
  2165. D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
  2166. AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
  2167. AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
  2168. AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
  2169. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2170. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2171. AttrSpellingListIndex);
  2172. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2173. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2174. AttrSpellingListIndex);
  2175. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2176. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2177. AttrSpellingListIndex);
  2178. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2179. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2180. AttrSpellingListIndex);
  2181. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2182. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2183. FA->getFormatIdx(), FA->getFirstArg(),
  2184. AttrSpellingListIndex);
  2185. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2186. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2187. AttrSpellingListIndex);
  2188. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2189. NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
  2190. AttrSpellingListIndex);
  2191. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2192. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2193. AttrSpellingListIndex,
  2194. IA->getSemanticSpelling());
  2195. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2196. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2197. &S.Context.Idents.get(AA->getSpelling()),
  2198. AttrSpellingListIndex);
  2199. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2200. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2201. isa<CUDAGlobalAttr>(Attr))) {
  2202. // CUDA target attributes are part of function signature for
  2203. // overloading purposes and must not be merged.
  2204. return false;
  2205. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2206. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2207. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2208. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2209. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2210. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2211. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2212. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2213. else if (isa<AlignedAttr>(Attr))
  2214. // AlignedAttrs are handled separately, because we need to handle all
  2215. // such attributes on a declaration at the same time.
  2216. NewAttr = nullptr;
  2217. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2218. (AMK == Sema::AMK_Override ||
  2219. AMK == Sema::AMK_ProtocolImplementation))
  2220. NewAttr = nullptr;
  2221. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2222. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2223. UA->getGuid());
  2224. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2225. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2226. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2227. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2228. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2229. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2230. if (NewAttr) {
  2231. NewAttr->setInherited(true);
  2232. D->addAttr(NewAttr);
  2233. if (isa<MSInheritanceAttr>(NewAttr))
  2234. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2235. return true;
  2236. }
  2237. return false;
  2238. }
  2239. static const NamedDecl *getDefinition(const Decl *D) {
  2240. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2241. return TD->getDefinition();
  2242. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2243. const VarDecl *Def = VD->getDefinition();
  2244. if (Def)
  2245. return Def;
  2246. return VD->getActingDefinition();
  2247. }
  2248. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2249. return FD->getDefinition();
  2250. return nullptr;
  2251. }
  2252. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2253. for (const auto *Attribute : D->attrs())
  2254. if (Attribute->getKind() == Kind)
  2255. return true;
  2256. return false;
  2257. }
  2258. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2259. /// there are no new attributes in this declaration.
  2260. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2261. if (!New->hasAttrs())
  2262. return;
  2263. const NamedDecl *Def = getDefinition(Old);
  2264. if (!Def || Def == New)
  2265. return;
  2266. AttrVec &NewAttributes = New->getAttrs();
  2267. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2268. const Attr *NewAttribute = NewAttributes[I];
  2269. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2270. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2271. Sema::SkipBodyInfo SkipBody;
  2272. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2273. // If we're skipping this definition, drop the "alias" attribute.
  2274. if (SkipBody.ShouldSkip) {
  2275. NewAttributes.erase(NewAttributes.begin() + I);
  2276. --E;
  2277. continue;
  2278. }
  2279. } else {
  2280. VarDecl *VD = cast<VarDecl>(New);
  2281. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2282. VarDecl::TentativeDefinition
  2283. ? diag::err_alias_after_tentative
  2284. : diag::err_redefinition;
  2285. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2286. if (Diag == diag::err_redefinition)
  2287. S.notePreviousDefinition(Def, VD->getLocation());
  2288. else
  2289. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2290. VD->setInvalidDecl();
  2291. }
  2292. ++I;
  2293. continue;
  2294. }
  2295. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2296. // Tentative definitions are only interesting for the alias check above.
  2297. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2298. ++I;
  2299. continue;
  2300. }
  2301. }
  2302. if (hasAttribute(Def, NewAttribute->getKind())) {
  2303. ++I;
  2304. continue; // regular attr merging will take care of validating this.
  2305. }
  2306. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2307. // C's _Noreturn is allowed to be added to a function after it is defined.
  2308. ++I;
  2309. continue;
  2310. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2311. if (AA->isAlignas()) {
  2312. // C++11 [dcl.align]p6:
  2313. // if any declaration of an entity has an alignment-specifier,
  2314. // every defining declaration of that entity shall specify an
  2315. // equivalent alignment.
  2316. // C11 6.7.5/7:
  2317. // If the definition of an object does not have an alignment
  2318. // specifier, any other declaration of that object shall also
  2319. // have no alignment specifier.
  2320. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2321. << AA;
  2322. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2323. << AA;
  2324. NewAttributes.erase(NewAttributes.begin() + I);
  2325. --E;
  2326. continue;
  2327. }
  2328. }
  2329. S.Diag(NewAttribute->getLocation(),
  2330. diag::warn_attribute_precede_definition);
  2331. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2332. NewAttributes.erase(NewAttributes.begin() + I);
  2333. --E;
  2334. }
  2335. }
  2336. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2337. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2338. AvailabilityMergeKind AMK) {
  2339. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2340. UsedAttr *NewAttr = OldAttr->clone(Context);
  2341. NewAttr->setInherited(true);
  2342. New->addAttr(NewAttr);
  2343. }
  2344. if (!Old->hasAttrs() && !New->hasAttrs())
  2345. return;
  2346. // Attributes declared post-definition are currently ignored.
  2347. checkNewAttributesAfterDef(*this, New, Old);
  2348. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2349. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2350. if (OldA->getLabel() != NewA->getLabel()) {
  2351. // This redeclaration changes __asm__ label.
  2352. Diag(New->getLocation(), diag::err_different_asm_label);
  2353. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2354. }
  2355. } else if (Old->isUsed()) {
  2356. // This redeclaration adds an __asm__ label to a declaration that has
  2357. // already been ODR-used.
  2358. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2359. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2360. }
  2361. }
  2362. // Re-declaration cannot add abi_tag's.
  2363. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2364. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2365. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2366. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2367. NewTag) == OldAbiTagAttr->tags_end()) {
  2368. Diag(NewAbiTagAttr->getLocation(),
  2369. diag::err_new_abi_tag_on_redeclaration)
  2370. << NewTag;
  2371. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2372. }
  2373. }
  2374. } else {
  2375. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2376. Diag(Old->getLocation(), diag::note_previous_declaration);
  2377. }
  2378. }
  2379. // This redeclaration adds a section attribute.
  2380. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2381. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2382. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2383. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2384. Diag(Old->getLocation(), diag::note_previous_declaration);
  2385. }
  2386. }
  2387. }
  2388. // Redeclaration adds code-seg attribute.
  2389. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2390. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2391. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2392. Diag(New->getLocation(), diag::warn_mismatched_section)
  2393. << 0 /*codeseg*/;
  2394. Diag(Old->getLocation(), diag::note_previous_declaration);
  2395. }
  2396. if (!Old->hasAttrs())
  2397. return;
  2398. bool foundAny = New->hasAttrs();
  2399. // Ensure that any moving of objects within the allocated map is done before
  2400. // we process them.
  2401. if (!foundAny) New->setAttrs(AttrVec());
  2402. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2403. // Ignore deprecated/unavailable/availability attributes if requested.
  2404. AvailabilityMergeKind LocalAMK = AMK_None;
  2405. if (isa<DeprecatedAttr>(I) ||
  2406. isa<UnavailableAttr>(I) ||
  2407. isa<AvailabilityAttr>(I)) {
  2408. switch (AMK) {
  2409. case AMK_None:
  2410. continue;
  2411. case AMK_Redeclaration:
  2412. case AMK_Override:
  2413. case AMK_ProtocolImplementation:
  2414. LocalAMK = AMK;
  2415. break;
  2416. }
  2417. }
  2418. // Already handled.
  2419. if (isa<UsedAttr>(I))
  2420. continue;
  2421. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2422. foundAny = true;
  2423. }
  2424. if (mergeAlignedAttrs(*this, New, Old))
  2425. foundAny = true;
  2426. if (!foundAny) New->dropAttrs();
  2427. }
  2428. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2429. /// to the new one.
  2430. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2431. const ParmVarDecl *oldDecl,
  2432. Sema &S) {
  2433. // C++11 [dcl.attr.depend]p2:
  2434. // The first declaration of a function shall specify the
  2435. // carries_dependency attribute for its declarator-id if any declaration
  2436. // of the function specifies the carries_dependency attribute.
  2437. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2438. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2439. S.Diag(CDA->getLocation(),
  2440. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2441. // Find the first declaration of the parameter.
  2442. // FIXME: Should we build redeclaration chains for function parameters?
  2443. const FunctionDecl *FirstFD =
  2444. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2445. const ParmVarDecl *FirstVD =
  2446. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2447. S.Diag(FirstVD->getLocation(),
  2448. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2449. }
  2450. if (!oldDecl->hasAttrs())
  2451. return;
  2452. bool foundAny = newDecl->hasAttrs();
  2453. // Ensure that any moving of objects within the allocated map is
  2454. // done before we process them.
  2455. if (!foundAny) newDecl->setAttrs(AttrVec());
  2456. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2457. if (!DeclHasAttr(newDecl, I)) {
  2458. InheritableAttr *newAttr =
  2459. cast<InheritableParamAttr>(I->clone(S.Context));
  2460. newAttr->setInherited(true);
  2461. newDecl->addAttr(newAttr);
  2462. foundAny = true;
  2463. }
  2464. }
  2465. if (!foundAny) newDecl->dropAttrs();
  2466. }
  2467. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2468. const ParmVarDecl *OldParam,
  2469. Sema &S) {
  2470. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2471. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2472. if (*Oldnullability != *Newnullability) {
  2473. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2474. << DiagNullabilityKind(
  2475. *Newnullability,
  2476. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2477. != 0))
  2478. << DiagNullabilityKind(
  2479. *Oldnullability,
  2480. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2481. != 0));
  2482. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2483. }
  2484. } else {
  2485. QualType NewT = NewParam->getType();
  2486. NewT = S.Context.getAttributedType(
  2487. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2488. NewT, NewT);
  2489. NewParam->setType(NewT);
  2490. }
  2491. }
  2492. }
  2493. namespace {
  2494. /// Used in MergeFunctionDecl to keep track of function parameters in
  2495. /// C.
  2496. struct GNUCompatibleParamWarning {
  2497. ParmVarDecl *OldParm;
  2498. ParmVarDecl *NewParm;
  2499. QualType PromotedType;
  2500. };
  2501. } // end anonymous namespace
  2502. /// getSpecialMember - get the special member enum for a method.
  2503. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2504. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2505. if (Ctor->isDefaultConstructor())
  2506. return Sema::CXXDefaultConstructor;
  2507. if (Ctor->isCopyConstructor())
  2508. return Sema::CXXCopyConstructor;
  2509. if (Ctor->isMoveConstructor())
  2510. return Sema::CXXMoveConstructor;
  2511. } else if (isa<CXXDestructorDecl>(MD)) {
  2512. return Sema::CXXDestructor;
  2513. } else if (MD->isCopyAssignmentOperator()) {
  2514. return Sema::CXXCopyAssignment;
  2515. } else if (MD->isMoveAssignmentOperator()) {
  2516. return Sema::CXXMoveAssignment;
  2517. }
  2518. return Sema::CXXInvalid;
  2519. }
  2520. // Determine whether the previous declaration was a definition, implicit
  2521. // declaration, or a declaration.
  2522. template <typename T>
  2523. static std::pair<diag::kind, SourceLocation>
  2524. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2525. diag::kind PrevDiag;
  2526. SourceLocation OldLocation = Old->getLocation();
  2527. if (Old->isThisDeclarationADefinition())
  2528. PrevDiag = diag::note_previous_definition;
  2529. else if (Old->isImplicit()) {
  2530. PrevDiag = diag::note_previous_implicit_declaration;
  2531. if (OldLocation.isInvalid())
  2532. OldLocation = New->getLocation();
  2533. } else
  2534. PrevDiag = diag::note_previous_declaration;
  2535. return std::make_pair(PrevDiag, OldLocation);
  2536. }
  2537. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2538. /// only extern inline functions can be redefined, and even then only in
  2539. /// GNU89 mode.
  2540. static bool canRedefineFunction(const FunctionDecl *FD,
  2541. const LangOptions& LangOpts) {
  2542. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2543. !LangOpts.CPlusPlus &&
  2544. FD->isInlineSpecified() &&
  2545. FD->getStorageClass() == SC_Extern);
  2546. }
  2547. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2548. const AttributedType *AT = T->getAs<AttributedType>();
  2549. while (AT && !AT->isCallingConv())
  2550. AT = AT->getModifiedType()->getAs<AttributedType>();
  2551. return AT;
  2552. }
  2553. template <typename T>
  2554. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2555. const DeclContext *DC = Old->getDeclContext();
  2556. if (DC->isRecord())
  2557. return false;
  2558. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2559. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2560. return true;
  2561. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2562. return true;
  2563. return false;
  2564. }
  2565. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2566. static bool isExternC(VarTemplateDecl *) { return false; }
  2567. /// Check whether a redeclaration of an entity introduced by a
  2568. /// using-declaration is valid, given that we know it's not an overload
  2569. /// (nor a hidden tag declaration).
  2570. template<typename ExpectedDecl>
  2571. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2572. ExpectedDecl *New) {
  2573. // C++11 [basic.scope.declarative]p4:
  2574. // Given a set of declarations in a single declarative region, each of
  2575. // which specifies the same unqualified name,
  2576. // -- they shall all refer to the same entity, or all refer to functions
  2577. // and function templates; or
  2578. // -- exactly one declaration shall declare a class name or enumeration
  2579. // name that is not a typedef name and the other declarations shall all
  2580. // refer to the same variable or enumerator, or all refer to functions
  2581. // and function templates; in this case the class name or enumeration
  2582. // name is hidden (3.3.10).
  2583. // C++11 [namespace.udecl]p14:
  2584. // If a function declaration in namespace scope or block scope has the
  2585. // same name and the same parameter-type-list as a function introduced
  2586. // by a using-declaration, and the declarations do not declare the same
  2587. // function, the program is ill-formed.
  2588. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2589. if (Old &&
  2590. !Old->getDeclContext()->getRedeclContext()->Equals(
  2591. New->getDeclContext()->getRedeclContext()) &&
  2592. !(isExternC(Old) && isExternC(New)))
  2593. Old = nullptr;
  2594. if (!Old) {
  2595. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2596. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2597. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2598. return true;
  2599. }
  2600. return false;
  2601. }
  2602. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2603. const FunctionDecl *B) {
  2604. assert(A->getNumParams() == B->getNumParams());
  2605. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2606. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2607. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2608. if (AttrA == AttrB)
  2609. return true;
  2610. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2611. AttrA->isDynamic() == AttrB->isDynamic();
  2612. };
  2613. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2614. }
  2615. /// If necessary, adjust the semantic declaration context for a qualified
  2616. /// declaration to name the correct inline namespace within the qualifier.
  2617. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2618. DeclaratorDecl *OldD) {
  2619. // The only case where we need to update the DeclContext is when
  2620. // redeclaration lookup for a qualified name finds a declaration
  2621. // in an inline namespace within the context named by the qualifier:
  2622. //
  2623. // inline namespace N { int f(); }
  2624. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2625. //
  2626. // For unqualified declarations, the semantic context *can* change
  2627. // along the redeclaration chain (for local extern declarations,
  2628. // extern "C" declarations, and friend declarations in particular).
  2629. if (!NewD->getQualifier())
  2630. return;
  2631. // NewD is probably already in the right context.
  2632. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2633. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2634. if (NamedDC->Equals(SemaDC))
  2635. return;
  2636. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2637. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2638. "unexpected context for redeclaration");
  2639. auto *LexDC = NewD->getLexicalDeclContext();
  2640. auto FixSemaDC = [=](NamedDecl *D) {
  2641. if (!D)
  2642. return;
  2643. D->setDeclContext(SemaDC);
  2644. D->setLexicalDeclContext(LexDC);
  2645. };
  2646. FixSemaDC(NewD);
  2647. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2648. FixSemaDC(FD->getDescribedFunctionTemplate());
  2649. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2650. FixSemaDC(VD->getDescribedVarTemplate());
  2651. }
  2652. /// MergeFunctionDecl - We just parsed a function 'New' from
  2653. /// declarator D which has the same name and scope as a previous
  2654. /// declaration 'Old'. Figure out how to resolve this situation,
  2655. /// merging decls or emitting diagnostics as appropriate.
  2656. ///
  2657. /// In C++, New and Old must be declarations that are not
  2658. /// overloaded. Use IsOverload to determine whether New and Old are
  2659. /// overloaded, and to select the Old declaration that New should be
  2660. /// merged with.
  2661. ///
  2662. /// Returns true if there was an error, false otherwise.
  2663. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2664. Scope *S, bool MergeTypeWithOld) {
  2665. // Verify the old decl was also a function.
  2666. FunctionDecl *Old = OldD->getAsFunction();
  2667. if (!Old) {
  2668. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2669. if (New->getFriendObjectKind()) {
  2670. Diag(New->getLocation(), diag::err_using_decl_friend);
  2671. Diag(Shadow->getTargetDecl()->getLocation(),
  2672. diag::note_using_decl_target);
  2673. Diag(Shadow->getUsingDecl()->getLocation(),
  2674. diag::note_using_decl) << 0;
  2675. return true;
  2676. }
  2677. // Check whether the two declarations might declare the same function.
  2678. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2679. return true;
  2680. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2681. } else {
  2682. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2683. << New->getDeclName();
  2684. notePreviousDefinition(OldD, New->getLocation());
  2685. return true;
  2686. }
  2687. }
  2688. // If the old declaration is invalid, just give up here.
  2689. if (Old->isInvalidDecl())
  2690. return true;
  2691. // Disallow redeclaration of some builtins.
  2692. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2693. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2694. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2695. << Old << Old->getType();
  2696. return true;
  2697. }
  2698. diag::kind PrevDiag;
  2699. SourceLocation OldLocation;
  2700. std::tie(PrevDiag, OldLocation) =
  2701. getNoteDiagForInvalidRedeclaration(Old, New);
  2702. // Don't complain about this if we're in GNU89 mode and the old function
  2703. // is an extern inline function.
  2704. // Don't complain about specializations. They are not supposed to have
  2705. // storage classes.
  2706. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2707. New->getStorageClass() == SC_Static &&
  2708. Old->hasExternalFormalLinkage() &&
  2709. !New->getTemplateSpecializationInfo() &&
  2710. !canRedefineFunction(Old, getLangOpts())) {
  2711. if (getLangOpts().MicrosoftExt) {
  2712. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2713. Diag(OldLocation, PrevDiag);
  2714. } else {
  2715. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2716. Diag(OldLocation, PrevDiag);
  2717. return true;
  2718. }
  2719. }
  2720. if (New->hasAttr<InternalLinkageAttr>() &&
  2721. !Old->hasAttr<InternalLinkageAttr>()) {
  2722. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2723. << New->getDeclName();
  2724. notePreviousDefinition(Old, New->getLocation());
  2725. New->dropAttr<InternalLinkageAttr>();
  2726. }
  2727. if (CheckRedeclarationModuleOwnership(New, Old))
  2728. return true;
  2729. if (!getLangOpts().CPlusPlus) {
  2730. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2731. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2732. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2733. << New << OldOvl;
  2734. // Try our best to find a decl that actually has the overloadable
  2735. // attribute for the note. In most cases (e.g. programs with only one
  2736. // broken declaration/definition), this won't matter.
  2737. //
  2738. // FIXME: We could do this if we juggled some extra state in
  2739. // OverloadableAttr, rather than just removing it.
  2740. const Decl *DiagOld = Old;
  2741. if (OldOvl) {
  2742. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2743. const auto *A = D->getAttr<OverloadableAttr>();
  2744. return A && !A->isImplicit();
  2745. });
  2746. // If we've implicitly added *all* of the overloadable attrs to this
  2747. // chain, emitting a "previous redecl" note is pointless.
  2748. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2749. }
  2750. if (DiagOld)
  2751. Diag(DiagOld->getLocation(),
  2752. diag::note_attribute_overloadable_prev_overload)
  2753. << OldOvl;
  2754. if (OldOvl)
  2755. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2756. else
  2757. New->dropAttr<OverloadableAttr>();
  2758. }
  2759. }
  2760. // If a function is first declared with a calling convention, but is later
  2761. // declared or defined without one, all following decls assume the calling
  2762. // convention of the first.
  2763. //
  2764. // It's OK if a function is first declared without a calling convention,
  2765. // but is later declared or defined with the default calling convention.
  2766. //
  2767. // To test if either decl has an explicit calling convention, we look for
  2768. // AttributedType sugar nodes on the type as written. If they are missing or
  2769. // were canonicalized away, we assume the calling convention was implicit.
  2770. //
  2771. // Note also that we DO NOT return at this point, because we still have
  2772. // other tests to run.
  2773. QualType OldQType = Context.getCanonicalType(Old->getType());
  2774. QualType NewQType = Context.getCanonicalType(New->getType());
  2775. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2776. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2777. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2778. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2779. bool RequiresAdjustment = false;
  2780. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2781. FunctionDecl *First = Old->getFirstDecl();
  2782. const FunctionType *FT =
  2783. First->getType().getCanonicalType()->castAs<FunctionType>();
  2784. FunctionType::ExtInfo FI = FT->getExtInfo();
  2785. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2786. if (!NewCCExplicit) {
  2787. // Inherit the CC from the previous declaration if it was specified
  2788. // there but not here.
  2789. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2790. RequiresAdjustment = true;
  2791. } else if (New->getBuiltinID()) {
  2792. // Calling Conventions on a Builtin aren't really useful and setting a
  2793. // default calling convention and cdecl'ing some builtin redeclarations is
  2794. // common, so warn and ignore the calling convention on the redeclaration.
  2795. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  2796. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2797. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2798. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2799. RequiresAdjustment = true;
  2800. } else {
  2801. // Calling conventions aren't compatible, so complain.
  2802. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2803. Diag(New->getLocation(), diag::err_cconv_change)
  2804. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2805. << !FirstCCExplicit
  2806. << (!FirstCCExplicit ? "" :
  2807. FunctionType::getNameForCallConv(FI.getCC()));
  2808. // Put the note on the first decl, since it is the one that matters.
  2809. Diag(First->getLocation(), diag::note_previous_declaration);
  2810. return true;
  2811. }
  2812. }
  2813. // FIXME: diagnose the other way around?
  2814. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2815. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2816. RequiresAdjustment = true;
  2817. }
  2818. // Merge regparm attribute.
  2819. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2820. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2821. if (NewTypeInfo.getHasRegParm()) {
  2822. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2823. << NewType->getRegParmType()
  2824. << OldType->getRegParmType();
  2825. Diag(OldLocation, diag::note_previous_declaration);
  2826. return true;
  2827. }
  2828. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2829. RequiresAdjustment = true;
  2830. }
  2831. // Merge ns_returns_retained attribute.
  2832. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2833. if (NewTypeInfo.getProducesResult()) {
  2834. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2835. << "'ns_returns_retained'";
  2836. Diag(OldLocation, diag::note_previous_declaration);
  2837. return true;
  2838. }
  2839. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2840. RequiresAdjustment = true;
  2841. }
  2842. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2843. NewTypeInfo.getNoCallerSavedRegs()) {
  2844. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2845. AnyX86NoCallerSavedRegistersAttr *Attr =
  2846. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2847. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2848. Diag(OldLocation, diag::note_previous_declaration);
  2849. return true;
  2850. }
  2851. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2852. RequiresAdjustment = true;
  2853. }
  2854. if (RequiresAdjustment) {
  2855. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2856. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2857. New->setType(QualType(AdjustedType, 0));
  2858. NewQType = Context.getCanonicalType(New->getType());
  2859. }
  2860. // If this redeclaration makes the function inline, we may need to add it to
  2861. // UndefinedButUsed.
  2862. if (!Old->isInlined() && New->isInlined() &&
  2863. !New->hasAttr<GNUInlineAttr>() &&
  2864. !getLangOpts().GNUInline &&
  2865. Old->isUsed(false) &&
  2866. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2867. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2868. SourceLocation()));
  2869. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2870. // about it.
  2871. if (New->hasAttr<GNUInlineAttr>() &&
  2872. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2873. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2874. }
  2875. // If pass_object_size params don't match up perfectly, this isn't a valid
  2876. // redeclaration.
  2877. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2878. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2879. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2880. << New->getDeclName();
  2881. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2882. return true;
  2883. }
  2884. if (getLangOpts().CPlusPlus) {
  2885. // C++1z [over.load]p2
  2886. // Certain function declarations cannot be overloaded:
  2887. // -- Function declarations that differ only in the return type,
  2888. // the exception specification, or both cannot be overloaded.
  2889. // Check the exception specifications match. This may recompute the type of
  2890. // both Old and New if it resolved exception specifications, so grab the
  2891. // types again after this. Because this updates the type, we do this before
  2892. // any of the other checks below, which may update the "de facto" NewQType
  2893. // but do not necessarily update the type of New.
  2894. if (CheckEquivalentExceptionSpec(Old, New))
  2895. return true;
  2896. OldQType = Context.getCanonicalType(Old->getType());
  2897. NewQType = Context.getCanonicalType(New->getType());
  2898. // Go back to the type source info to compare the declared return types,
  2899. // per C++1y [dcl.type.auto]p13:
  2900. // Redeclarations or specializations of a function or function template
  2901. // with a declared return type that uses a placeholder type shall also
  2902. // use that placeholder, not a deduced type.
  2903. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  2904. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  2905. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2906. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  2907. OldDeclaredReturnType)) {
  2908. QualType ResQT;
  2909. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2910. OldDeclaredReturnType->isObjCObjectPointerType())
  2911. // FIXME: This does the wrong thing for a deduced return type.
  2912. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2913. if (ResQT.isNull()) {
  2914. if (New->isCXXClassMember() && New->isOutOfLine())
  2915. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2916. << New << New->getReturnTypeSourceRange();
  2917. else
  2918. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2919. << New->getReturnTypeSourceRange();
  2920. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2921. << Old->getReturnTypeSourceRange();
  2922. return true;
  2923. }
  2924. else
  2925. NewQType = ResQT;
  2926. }
  2927. QualType OldReturnType = OldType->getReturnType();
  2928. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2929. if (OldReturnType != NewReturnType) {
  2930. // If this function has a deduced return type and has already been
  2931. // defined, copy the deduced value from the old declaration.
  2932. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2933. if (OldAT && OldAT->isDeduced()) {
  2934. New->setType(
  2935. SubstAutoType(New->getType(),
  2936. OldAT->isDependentType() ? Context.DependentTy
  2937. : OldAT->getDeducedType()));
  2938. NewQType = Context.getCanonicalType(
  2939. SubstAutoType(NewQType,
  2940. OldAT->isDependentType() ? Context.DependentTy
  2941. : OldAT->getDeducedType()));
  2942. }
  2943. }
  2944. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2945. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2946. if (OldMethod && NewMethod) {
  2947. // Preserve triviality.
  2948. NewMethod->setTrivial(OldMethod->isTrivial());
  2949. // MSVC allows explicit template specialization at class scope:
  2950. // 2 CXXMethodDecls referring to the same function will be injected.
  2951. // We don't want a redeclaration error.
  2952. bool IsClassScopeExplicitSpecialization =
  2953. OldMethod->isFunctionTemplateSpecialization() &&
  2954. NewMethod->isFunctionTemplateSpecialization();
  2955. bool isFriend = NewMethod->getFriendObjectKind();
  2956. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2957. !IsClassScopeExplicitSpecialization) {
  2958. // -- Member function declarations with the same name and the
  2959. // same parameter types cannot be overloaded if any of them
  2960. // is a static member function declaration.
  2961. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2962. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2963. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2964. return true;
  2965. }
  2966. // C++ [class.mem]p1:
  2967. // [...] A member shall not be declared twice in the
  2968. // member-specification, except that a nested class or member
  2969. // class template can be declared and then later defined.
  2970. if (!inTemplateInstantiation()) {
  2971. unsigned NewDiag;
  2972. if (isa<CXXConstructorDecl>(OldMethod))
  2973. NewDiag = diag::err_constructor_redeclared;
  2974. else if (isa<CXXDestructorDecl>(NewMethod))
  2975. NewDiag = diag::err_destructor_redeclared;
  2976. else if (isa<CXXConversionDecl>(NewMethod))
  2977. NewDiag = diag::err_conv_function_redeclared;
  2978. else
  2979. NewDiag = diag::err_member_redeclared;
  2980. Diag(New->getLocation(), NewDiag);
  2981. } else {
  2982. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2983. << New << New->getType();
  2984. }
  2985. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2986. return true;
  2987. // Complain if this is an explicit declaration of a special
  2988. // member that was initially declared implicitly.
  2989. //
  2990. // As an exception, it's okay to befriend such methods in order
  2991. // to permit the implicit constructor/destructor/operator calls.
  2992. } else if (OldMethod->isImplicit()) {
  2993. if (isFriend) {
  2994. NewMethod->setImplicit();
  2995. } else {
  2996. Diag(NewMethod->getLocation(),
  2997. diag::err_definition_of_implicitly_declared_member)
  2998. << New << getSpecialMember(OldMethod);
  2999. return true;
  3000. }
  3001. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3002. Diag(NewMethod->getLocation(),
  3003. diag::err_definition_of_explicitly_defaulted_member)
  3004. << getSpecialMember(OldMethod);
  3005. return true;
  3006. }
  3007. }
  3008. // C++11 [dcl.attr.noreturn]p1:
  3009. // The first declaration of a function shall specify the noreturn
  3010. // attribute if any declaration of that function specifies the noreturn
  3011. // attribute.
  3012. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3013. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3014. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3015. Diag(Old->getFirstDecl()->getLocation(),
  3016. diag::note_noreturn_missing_first_decl);
  3017. }
  3018. // C++11 [dcl.attr.depend]p2:
  3019. // The first declaration of a function shall specify the
  3020. // carries_dependency attribute for its declarator-id if any declaration
  3021. // of the function specifies the carries_dependency attribute.
  3022. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3023. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3024. Diag(CDA->getLocation(),
  3025. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3026. Diag(Old->getFirstDecl()->getLocation(),
  3027. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3028. }
  3029. // (C++98 8.3.5p3):
  3030. // All declarations for a function shall agree exactly in both the
  3031. // return type and the parameter-type-list.
  3032. // We also want to respect all the extended bits except noreturn.
  3033. // noreturn should now match unless the old type info didn't have it.
  3034. QualType OldQTypeForComparison = OldQType;
  3035. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3036. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3037. const FunctionType *OldTypeForComparison
  3038. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3039. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3040. assert(OldQTypeForComparison.isCanonical());
  3041. }
  3042. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3043. // As a special case, retain the language linkage from previous
  3044. // declarations of a friend function as an extension.
  3045. //
  3046. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3047. // and is useful because there's otherwise no way to specify language
  3048. // linkage within class scope.
  3049. //
  3050. // Check cautiously as the friend object kind isn't yet complete.
  3051. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3052. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3053. Diag(OldLocation, PrevDiag);
  3054. } else {
  3055. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3056. Diag(OldLocation, PrevDiag);
  3057. return true;
  3058. }
  3059. }
  3060. if (OldQTypeForComparison == NewQType)
  3061. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3062. // If the types are imprecise (due to dependent constructs in friends or
  3063. // local extern declarations), it's OK if they differ. We'll check again
  3064. // during instantiation.
  3065. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3066. return false;
  3067. // Fall through for conflicting redeclarations and redefinitions.
  3068. }
  3069. // C: Function types need to be compatible, not identical. This handles
  3070. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3071. if (!getLangOpts().CPlusPlus &&
  3072. Context.typesAreCompatible(OldQType, NewQType)) {
  3073. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3074. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3075. const FunctionProtoType *OldProto = nullptr;
  3076. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3077. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3078. // The old declaration provided a function prototype, but the
  3079. // new declaration does not. Merge in the prototype.
  3080. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3081. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3082. NewQType =
  3083. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3084. OldProto->getExtProtoInfo());
  3085. New->setType(NewQType);
  3086. New->setHasInheritedPrototype();
  3087. // Synthesize parameters with the same types.
  3088. SmallVector<ParmVarDecl*, 16> Params;
  3089. for (const auto &ParamType : OldProto->param_types()) {
  3090. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3091. SourceLocation(), nullptr,
  3092. ParamType, /*TInfo=*/nullptr,
  3093. SC_None, nullptr);
  3094. Param->setScopeInfo(0, Params.size());
  3095. Param->setImplicit();
  3096. Params.push_back(Param);
  3097. }
  3098. New->setParams(Params);
  3099. }
  3100. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3101. }
  3102. // GNU C permits a K&R definition to follow a prototype declaration
  3103. // if the declared types of the parameters in the K&R definition
  3104. // match the types in the prototype declaration, even when the
  3105. // promoted types of the parameters from the K&R definition differ
  3106. // from the types in the prototype. GCC then keeps the types from
  3107. // the prototype.
  3108. //
  3109. // If a variadic prototype is followed by a non-variadic K&R definition,
  3110. // the K&R definition becomes variadic. This is sort of an edge case, but
  3111. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3112. // C99 6.9.1p8.
  3113. if (!getLangOpts().CPlusPlus &&
  3114. Old->hasPrototype() && !New->hasPrototype() &&
  3115. New->getType()->getAs<FunctionProtoType>() &&
  3116. Old->getNumParams() == New->getNumParams()) {
  3117. SmallVector<QualType, 16> ArgTypes;
  3118. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3119. const FunctionProtoType *OldProto
  3120. = Old->getType()->getAs<FunctionProtoType>();
  3121. const FunctionProtoType *NewProto
  3122. = New->getType()->getAs<FunctionProtoType>();
  3123. // Determine whether this is the GNU C extension.
  3124. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3125. NewProto->getReturnType());
  3126. bool LooseCompatible = !MergedReturn.isNull();
  3127. for (unsigned Idx = 0, End = Old->getNumParams();
  3128. LooseCompatible && Idx != End; ++Idx) {
  3129. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3130. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3131. if (Context.typesAreCompatible(OldParm->getType(),
  3132. NewProto->getParamType(Idx))) {
  3133. ArgTypes.push_back(NewParm->getType());
  3134. } else if (Context.typesAreCompatible(OldParm->getType(),
  3135. NewParm->getType(),
  3136. /*CompareUnqualified=*/true)) {
  3137. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3138. NewProto->getParamType(Idx) };
  3139. Warnings.push_back(Warn);
  3140. ArgTypes.push_back(NewParm->getType());
  3141. } else
  3142. LooseCompatible = false;
  3143. }
  3144. if (LooseCompatible) {
  3145. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3146. Diag(Warnings[Warn].NewParm->getLocation(),
  3147. diag::ext_param_promoted_not_compatible_with_prototype)
  3148. << Warnings[Warn].PromotedType
  3149. << Warnings[Warn].OldParm->getType();
  3150. if (Warnings[Warn].OldParm->getLocation().isValid())
  3151. Diag(Warnings[Warn].OldParm->getLocation(),
  3152. diag::note_previous_declaration);
  3153. }
  3154. if (MergeTypeWithOld)
  3155. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3156. OldProto->getExtProtoInfo()));
  3157. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3158. }
  3159. // Fall through to diagnose conflicting types.
  3160. }
  3161. // A function that has already been declared has been redeclared or
  3162. // defined with a different type; show an appropriate diagnostic.
  3163. // If the previous declaration was an implicitly-generated builtin
  3164. // declaration, then at the very least we should use a specialized note.
  3165. unsigned BuiltinID;
  3166. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3167. // If it's actually a library-defined builtin function like 'malloc'
  3168. // or 'printf', just warn about the incompatible redeclaration.
  3169. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3170. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3171. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3172. << Old << Old->getType();
  3173. // If this is a global redeclaration, just forget hereafter
  3174. // about the "builtin-ness" of the function.
  3175. //
  3176. // Doing this for local extern declarations is problematic. If
  3177. // the builtin declaration remains visible, a second invalid
  3178. // local declaration will produce a hard error; if it doesn't
  3179. // remain visible, a single bogus local redeclaration (which is
  3180. // actually only a warning) could break all the downstream code.
  3181. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3182. New->getIdentifier()->revertBuiltin();
  3183. return false;
  3184. }
  3185. PrevDiag = diag::note_previous_builtin_declaration;
  3186. }
  3187. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3188. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3189. return true;
  3190. }
  3191. /// Completes the merge of two function declarations that are
  3192. /// known to be compatible.
  3193. ///
  3194. /// This routine handles the merging of attributes and other
  3195. /// properties of function declarations from the old declaration to
  3196. /// the new declaration, once we know that New is in fact a
  3197. /// redeclaration of Old.
  3198. ///
  3199. /// \returns false
  3200. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3201. Scope *S, bool MergeTypeWithOld) {
  3202. // Merge the attributes
  3203. mergeDeclAttributes(New, Old);
  3204. // Merge "pure" flag.
  3205. if (Old->isPure())
  3206. New->setPure();
  3207. // Merge "used" flag.
  3208. if (Old->getMostRecentDecl()->isUsed(false))
  3209. New->setIsUsed();
  3210. // Merge attributes from the parameters. These can mismatch with K&R
  3211. // declarations.
  3212. if (New->getNumParams() == Old->getNumParams())
  3213. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3214. ParmVarDecl *NewParam = New->getParamDecl(i);
  3215. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3216. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3217. mergeParamDeclTypes(NewParam, OldParam, *this);
  3218. }
  3219. if (getLangOpts().CPlusPlus)
  3220. return MergeCXXFunctionDecl(New, Old, S);
  3221. // Merge the function types so the we get the composite types for the return
  3222. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3223. // was visible.
  3224. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3225. if (!Merged.isNull() && MergeTypeWithOld)
  3226. New->setType(Merged);
  3227. return false;
  3228. }
  3229. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3230. ObjCMethodDecl *oldMethod) {
  3231. // Merge the attributes, including deprecated/unavailable
  3232. AvailabilityMergeKind MergeKind =
  3233. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3234. ? AMK_ProtocolImplementation
  3235. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3236. : AMK_Override;
  3237. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3238. // Merge attributes from the parameters.
  3239. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3240. oe = oldMethod->param_end();
  3241. for (ObjCMethodDecl::param_iterator
  3242. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3243. ni != ne && oi != oe; ++ni, ++oi)
  3244. mergeParamDeclAttributes(*ni, *oi, *this);
  3245. CheckObjCMethodOverride(newMethod, oldMethod);
  3246. }
  3247. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3248. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3249. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3250. ? diag::err_redefinition_different_type
  3251. : diag::err_redeclaration_different_type)
  3252. << New->getDeclName() << New->getType() << Old->getType();
  3253. diag::kind PrevDiag;
  3254. SourceLocation OldLocation;
  3255. std::tie(PrevDiag, OldLocation)
  3256. = getNoteDiagForInvalidRedeclaration(Old, New);
  3257. S.Diag(OldLocation, PrevDiag);
  3258. New->setInvalidDecl();
  3259. }
  3260. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3261. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3262. /// emitting diagnostics as appropriate.
  3263. ///
  3264. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3265. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3266. /// is attached.
  3267. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3268. bool MergeTypeWithOld) {
  3269. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3270. return;
  3271. QualType MergedT;
  3272. if (getLangOpts().CPlusPlus) {
  3273. if (New->getType()->isUndeducedType()) {
  3274. // We don't know what the new type is until the initializer is attached.
  3275. return;
  3276. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3277. // These could still be something that needs exception specs checked.
  3278. return MergeVarDeclExceptionSpecs(New, Old);
  3279. }
  3280. // C++ [basic.link]p10:
  3281. // [...] the types specified by all declarations referring to a given
  3282. // object or function shall be identical, except that declarations for an
  3283. // array object can specify array types that differ by the presence or
  3284. // absence of a major array bound (8.3.4).
  3285. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3286. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3287. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3288. // We are merging a variable declaration New into Old. If it has an array
  3289. // bound, and that bound differs from Old's bound, we should diagnose the
  3290. // mismatch.
  3291. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3292. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3293. PrevVD = PrevVD->getPreviousDecl()) {
  3294. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3295. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3296. continue;
  3297. if (!Context.hasSameType(NewArray, PrevVDTy))
  3298. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3299. }
  3300. }
  3301. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3302. if (Context.hasSameType(OldArray->getElementType(),
  3303. NewArray->getElementType()))
  3304. MergedT = New->getType();
  3305. }
  3306. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3307. // has no array bound, it should not inherit one from Old, if Old is not
  3308. // visible.
  3309. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3310. if (Context.hasSameType(OldArray->getElementType(),
  3311. NewArray->getElementType()))
  3312. MergedT = Old->getType();
  3313. }
  3314. }
  3315. else if (New->getType()->isObjCObjectPointerType() &&
  3316. Old->getType()->isObjCObjectPointerType()) {
  3317. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3318. Old->getType());
  3319. }
  3320. } else {
  3321. // C 6.2.7p2:
  3322. // All declarations that refer to the same object or function shall have
  3323. // compatible type.
  3324. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3325. }
  3326. if (MergedT.isNull()) {
  3327. // It's OK if we couldn't merge types if either type is dependent, for a
  3328. // block-scope variable. In other cases (static data members of class
  3329. // templates, variable templates, ...), we require the types to be
  3330. // equivalent.
  3331. // FIXME: The C++ standard doesn't say anything about this.
  3332. if ((New->getType()->isDependentType() ||
  3333. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3334. // If the old type was dependent, we can't merge with it, so the new type
  3335. // becomes dependent for now. We'll reproduce the original type when we
  3336. // instantiate the TypeSourceInfo for the variable.
  3337. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3338. New->setType(Context.DependentTy);
  3339. return;
  3340. }
  3341. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3342. }
  3343. // Don't actually update the type on the new declaration if the old
  3344. // declaration was an extern declaration in a different scope.
  3345. if (MergeTypeWithOld)
  3346. New->setType(MergedT);
  3347. }
  3348. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3349. LookupResult &Previous) {
  3350. // C11 6.2.7p4:
  3351. // For an identifier with internal or external linkage declared
  3352. // in a scope in which a prior declaration of that identifier is
  3353. // visible, if the prior declaration specifies internal or
  3354. // external linkage, the type of the identifier at the later
  3355. // declaration becomes the composite type.
  3356. //
  3357. // If the variable isn't visible, we do not merge with its type.
  3358. if (Previous.isShadowed())
  3359. return false;
  3360. if (S.getLangOpts().CPlusPlus) {
  3361. // C++11 [dcl.array]p3:
  3362. // If there is a preceding declaration of the entity in the same
  3363. // scope in which the bound was specified, an omitted array bound
  3364. // is taken to be the same as in that earlier declaration.
  3365. return NewVD->isPreviousDeclInSameBlockScope() ||
  3366. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3367. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3368. } else {
  3369. // If the old declaration was function-local, don't merge with its
  3370. // type unless we're in the same function.
  3371. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3372. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3373. }
  3374. }
  3375. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3376. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3377. /// situation, merging decls or emitting diagnostics as appropriate.
  3378. ///
  3379. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3380. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3381. /// definitions here, since the initializer hasn't been attached.
  3382. ///
  3383. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3384. // If the new decl is already invalid, don't do any other checking.
  3385. if (New->isInvalidDecl())
  3386. return;
  3387. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3388. return;
  3389. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3390. // Verify the old decl was also a variable or variable template.
  3391. VarDecl *Old = nullptr;
  3392. VarTemplateDecl *OldTemplate = nullptr;
  3393. if (Previous.isSingleResult()) {
  3394. if (NewTemplate) {
  3395. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3396. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3397. if (auto *Shadow =
  3398. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3399. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3400. return New->setInvalidDecl();
  3401. } else {
  3402. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3403. if (auto *Shadow =
  3404. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3405. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3406. return New->setInvalidDecl();
  3407. }
  3408. }
  3409. if (!Old) {
  3410. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3411. << New->getDeclName();
  3412. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3413. New->getLocation());
  3414. return New->setInvalidDecl();
  3415. }
  3416. // Ensure the template parameters are compatible.
  3417. if (NewTemplate &&
  3418. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3419. OldTemplate->getTemplateParameters(),
  3420. /*Complain=*/true, TPL_TemplateMatch))
  3421. return New->setInvalidDecl();
  3422. // C++ [class.mem]p1:
  3423. // A member shall not be declared twice in the member-specification [...]
  3424. //
  3425. // Here, we need only consider static data members.
  3426. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3427. Diag(New->getLocation(), diag::err_duplicate_member)
  3428. << New->getIdentifier();
  3429. Diag(Old->getLocation(), diag::note_previous_declaration);
  3430. New->setInvalidDecl();
  3431. }
  3432. mergeDeclAttributes(New, Old);
  3433. // Warn if an already-declared variable is made a weak_import in a subsequent
  3434. // declaration
  3435. if (New->hasAttr<WeakImportAttr>() &&
  3436. Old->getStorageClass() == SC_None &&
  3437. !Old->hasAttr<WeakImportAttr>()) {
  3438. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3439. notePreviousDefinition(Old, New->getLocation());
  3440. // Remove weak_import attribute on new declaration.
  3441. New->dropAttr<WeakImportAttr>();
  3442. }
  3443. if (New->hasAttr<InternalLinkageAttr>() &&
  3444. !Old->hasAttr<InternalLinkageAttr>()) {
  3445. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3446. << New->getDeclName();
  3447. notePreviousDefinition(Old, New->getLocation());
  3448. New->dropAttr<InternalLinkageAttr>();
  3449. }
  3450. // Merge the types.
  3451. VarDecl *MostRecent = Old->getMostRecentDecl();
  3452. if (MostRecent != Old) {
  3453. MergeVarDeclTypes(New, MostRecent,
  3454. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3455. if (New->isInvalidDecl())
  3456. return;
  3457. }
  3458. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3459. if (New->isInvalidDecl())
  3460. return;
  3461. diag::kind PrevDiag;
  3462. SourceLocation OldLocation;
  3463. std::tie(PrevDiag, OldLocation) =
  3464. getNoteDiagForInvalidRedeclaration(Old, New);
  3465. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3466. if (New->getStorageClass() == SC_Static &&
  3467. !New->isStaticDataMember() &&
  3468. Old->hasExternalFormalLinkage()) {
  3469. if (getLangOpts().MicrosoftExt) {
  3470. Diag(New->getLocation(), diag::ext_static_non_static)
  3471. << New->getDeclName();
  3472. Diag(OldLocation, PrevDiag);
  3473. } else {
  3474. Diag(New->getLocation(), diag::err_static_non_static)
  3475. << New->getDeclName();
  3476. Diag(OldLocation, PrevDiag);
  3477. return New->setInvalidDecl();
  3478. }
  3479. }
  3480. // C99 6.2.2p4:
  3481. // For an identifier declared with the storage-class specifier
  3482. // extern in a scope in which a prior declaration of that
  3483. // identifier is visible,23) if the prior declaration specifies
  3484. // internal or external linkage, the linkage of the identifier at
  3485. // the later declaration is the same as the linkage specified at
  3486. // the prior declaration. If no prior declaration is visible, or
  3487. // if the prior declaration specifies no linkage, then the
  3488. // identifier has external linkage.
  3489. if (New->hasExternalStorage() && Old->hasLinkage())
  3490. /* Okay */;
  3491. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3492. !New->isStaticDataMember() &&
  3493. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3494. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3495. Diag(OldLocation, PrevDiag);
  3496. return New->setInvalidDecl();
  3497. }
  3498. // Check if extern is followed by non-extern and vice-versa.
  3499. if (New->hasExternalStorage() &&
  3500. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3501. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3502. Diag(OldLocation, PrevDiag);
  3503. return New->setInvalidDecl();
  3504. }
  3505. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3506. !New->hasExternalStorage()) {
  3507. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3508. Diag(OldLocation, PrevDiag);
  3509. return New->setInvalidDecl();
  3510. }
  3511. if (CheckRedeclarationModuleOwnership(New, Old))
  3512. return;
  3513. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3514. // FIXME: The test for external storage here seems wrong? We still
  3515. // need to check for mismatches.
  3516. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3517. // Don't complain about out-of-line definitions of static members.
  3518. !(Old->getLexicalDeclContext()->isRecord() &&
  3519. !New->getLexicalDeclContext()->isRecord())) {
  3520. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3521. Diag(OldLocation, PrevDiag);
  3522. return New->setInvalidDecl();
  3523. }
  3524. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3525. if (VarDecl *Def = Old->getDefinition()) {
  3526. // C++1z [dcl.fcn.spec]p4:
  3527. // If the definition of a variable appears in a translation unit before
  3528. // its first declaration as inline, the program is ill-formed.
  3529. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3530. Diag(Def->getLocation(), diag::note_previous_definition);
  3531. }
  3532. }
  3533. // If this redeclaration makes the variable inline, we may need to add it to
  3534. // UndefinedButUsed.
  3535. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3536. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3537. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3538. SourceLocation()));
  3539. if (New->getTLSKind() != Old->getTLSKind()) {
  3540. if (!Old->getTLSKind()) {
  3541. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3542. Diag(OldLocation, PrevDiag);
  3543. } else if (!New->getTLSKind()) {
  3544. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3545. Diag(OldLocation, PrevDiag);
  3546. } else {
  3547. // Do not allow redeclaration to change the variable between requiring
  3548. // static and dynamic initialization.
  3549. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3550. // declaration to determine the kind. Do we need to be compatible here?
  3551. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3552. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3553. Diag(OldLocation, PrevDiag);
  3554. }
  3555. }
  3556. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3557. if (getLangOpts().CPlusPlus &&
  3558. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3559. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3560. Old->getCanonicalDecl()->isConstexpr()) {
  3561. // This definition won't be a definition any more once it's been merged.
  3562. Diag(New->getLocation(),
  3563. diag::warn_deprecated_redundant_constexpr_static_def);
  3564. } else if (VarDecl *Def = Old->getDefinition()) {
  3565. if (checkVarDeclRedefinition(Def, New))
  3566. return;
  3567. }
  3568. }
  3569. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3570. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3571. Diag(OldLocation, PrevDiag);
  3572. New->setInvalidDecl();
  3573. return;
  3574. }
  3575. // Merge "used" flag.
  3576. if (Old->getMostRecentDecl()->isUsed(false))
  3577. New->setIsUsed();
  3578. // Keep a chain of previous declarations.
  3579. New->setPreviousDecl(Old);
  3580. if (NewTemplate)
  3581. NewTemplate->setPreviousDecl(OldTemplate);
  3582. adjustDeclContextForDeclaratorDecl(New, Old);
  3583. // Inherit access appropriately.
  3584. New->setAccess(Old->getAccess());
  3585. if (NewTemplate)
  3586. NewTemplate->setAccess(New->getAccess());
  3587. if (Old->isInline())
  3588. New->setImplicitlyInline();
  3589. }
  3590. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3591. SourceManager &SrcMgr = getSourceManager();
  3592. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3593. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3594. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3595. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3596. auto &HSI = PP.getHeaderSearchInfo();
  3597. StringRef HdrFilename =
  3598. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3599. auto noteFromModuleOrInclude = [&](Module *Mod,
  3600. SourceLocation IncLoc) -> bool {
  3601. // Redefinition errors with modules are common with non modular mapped
  3602. // headers, example: a non-modular header H in module A that also gets
  3603. // included directly in a TU. Pointing twice to the same header/definition
  3604. // is confusing, try to get better diagnostics when modules is on.
  3605. if (IncLoc.isValid()) {
  3606. if (Mod) {
  3607. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3608. << HdrFilename.str() << Mod->getFullModuleName();
  3609. if (!Mod->DefinitionLoc.isInvalid())
  3610. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3611. << Mod->getFullModuleName();
  3612. } else {
  3613. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3614. << HdrFilename.str();
  3615. }
  3616. return true;
  3617. }
  3618. return false;
  3619. };
  3620. // Is it the same file and same offset? Provide more information on why
  3621. // this leads to a redefinition error.
  3622. bool EmittedDiag = false;
  3623. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3624. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3625. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3626. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3627. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3628. // If the header has no guards, emit a note suggesting one.
  3629. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3630. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3631. if (EmittedDiag)
  3632. return;
  3633. }
  3634. // Redefinition coming from different files or couldn't do better above.
  3635. if (Old->getLocation().isValid())
  3636. Diag(Old->getLocation(), diag::note_previous_definition);
  3637. }
  3638. /// We've just determined that \p Old and \p New both appear to be definitions
  3639. /// of the same variable. Either diagnose or fix the problem.
  3640. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3641. if (!hasVisibleDefinition(Old) &&
  3642. (New->getFormalLinkage() == InternalLinkage ||
  3643. New->isInline() ||
  3644. New->getDescribedVarTemplate() ||
  3645. New->getNumTemplateParameterLists() ||
  3646. New->getDeclContext()->isDependentContext())) {
  3647. // The previous definition is hidden, and multiple definitions are
  3648. // permitted (in separate TUs). Demote this to a declaration.
  3649. New->demoteThisDefinitionToDeclaration();
  3650. // Make the canonical definition visible.
  3651. if (auto *OldTD = Old->getDescribedVarTemplate())
  3652. makeMergedDefinitionVisible(OldTD);
  3653. makeMergedDefinitionVisible(Old);
  3654. return false;
  3655. } else {
  3656. Diag(New->getLocation(), diag::err_redefinition) << New;
  3657. notePreviousDefinition(Old, New->getLocation());
  3658. New->setInvalidDecl();
  3659. return true;
  3660. }
  3661. }
  3662. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3663. /// no declarator (e.g. "struct foo;") is parsed.
  3664. Decl *
  3665. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3666. RecordDecl *&AnonRecord) {
  3667. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3668. AnonRecord);
  3669. }
  3670. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3671. // disambiguate entities defined in different scopes.
  3672. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3673. // compatibility.
  3674. // We will pick our mangling number depending on which version of MSVC is being
  3675. // targeted.
  3676. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3677. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3678. ? S->getMSCurManglingNumber()
  3679. : S->getMSLastManglingNumber();
  3680. }
  3681. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3682. if (!Context.getLangOpts().CPlusPlus)
  3683. return;
  3684. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3685. // If this tag is the direct child of a class, number it if
  3686. // it is anonymous.
  3687. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3688. return;
  3689. MangleNumberingContext &MCtx =
  3690. Context.getManglingNumberContext(Tag->getParent());
  3691. Context.setManglingNumber(
  3692. Tag, MCtx.getManglingNumber(
  3693. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3694. return;
  3695. }
  3696. // If this tag isn't a direct child of a class, number it if it is local.
  3697. Decl *ManglingContextDecl;
  3698. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3699. Tag->getDeclContext(), ManglingContextDecl)) {
  3700. Context.setManglingNumber(
  3701. Tag, MCtx->getManglingNumber(
  3702. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3703. }
  3704. }
  3705. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3706. TypedefNameDecl *NewTD) {
  3707. if (TagFromDeclSpec->isInvalidDecl())
  3708. return;
  3709. // Do nothing if the tag already has a name for linkage purposes.
  3710. if (TagFromDeclSpec->hasNameForLinkage())
  3711. return;
  3712. // A well-formed anonymous tag must always be a TUK_Definition.
  3713. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3714. // The type must match the tag exactly; no qualifiers allowed.
  3715. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3716. Context.getTagDeclType(TagFromDeclSpec))) {
  3717. if (getLangOpts().CPlusPlus)
  3718. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3719. return;
  3720. }
  3721. // If we've already computed linkage for the anonymous tag, then
  3722. // adding a typedef name for the anonymous decl can change that
  3723. // linkage, which might be a serious problem. Diagnose this as
  3724. // unsupported and ignore the typedef name. TODO: we should
  3725. // pursue this as a language defect and establish a formal rule
  3726. // for how to handle it.
  3727. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3728. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3729. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3730. tagLoc = getLocForEndOfToken(tagLoc);
  3731. llvm::SmallString<40> textToInsert;
  3732. textToInsert += ' ';
  3733. textToInsert += NewTD->getIdentifier()->getName();
  3734. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3735. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3736. return;
  3737. }
  3738. // Otherwise, set this is the anon-decl typedef for the tag.
  3739. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3740. }
  3741. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3742. switch (T) {
  3743. case DeclSpec::TST_class:
  3744. return 0;
  3745. case DeclSpec::TST_struct:
  3746. return 1;
  3747. case DeclSpec::TST_interface:
  3748. return 2;
  3749. case DeclSpec::TST_union:
  3750. return 3;
  3751. case DeclSpec::TST_enum:
  3752. return 4;
  3753. default:
  3754. llvm_unreachable("unexpected type specifier");
  3755. }
  3756. }
  3757. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3758. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3759. /// parameters to cope with template friend declarations.
  3760. Decl *
  3761. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3762. MultiTemplateParamsArg TemplateParams,
  3763. bool IsExplicitInstantiation,
  3764. RecordDecl *&AnonRecord) {
  3765. Decl *TagD = nullptr;
  3766. TagDecl *Tag = nullptr;
  3767. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3768. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3769. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3770. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3771. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3772. TagD = DS.getRepAsDecl();
  3773. if (!TagD) // We probably had an error
  3774. return nullptr;
  3775. // Note that the above type specs guarantee that the
  3776. // type rep is a Decl, whereas in many of the others
  3777. // it's a Type.
  3778. if (isa<TagDecl>(TagD))
  3779. Tag = cast<TagDecl>(TagD);
  3780. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3781. Tag = CTD->getTemplatedDecl();
  3782. }
  3783. if (Tag) {
  3784. handleTagNumbering(Tag, S);
  3785. Tag->setFreeStanding();
  3786. if (Tag->isInvalidDecl())
  3787. return Tag;
  3788. }
  3789. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3790. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3791. // or incomplete types shall not be restrict-qualified."
  3792. if (TypeQuals & DeclSpec::TQ_restrict)
  3793. Diag(DS.getRestrictSpecLoc(),
  3794. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3795. << DS.getSourceRange();
  3796. }
  3797. if (DS.isInlineSpecified())
  3798. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3799. << getLangOpts().CPlusPlus17;
  3800. if (DS.hasConstexprSpecifier()) {
  3801. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3802. // and definitions of functions and variables.
  3803. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  3804. // the declaration of a function or function template
  3805. bool IsConsteval = DS.getConstexprSpecifier() == CSK_consteval;
  3806. if (Tag)
  3807. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3808. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << IsConsteval;
  3809. else
  3810. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  3811. << IsConsteval;
  3812. // Don't emit warnings after this error.
  3813. return TagD;
  3814. }
  3815. DiagnoseFunctionSpecifiers(DS);
  3816. if (DS.isFriendSpecified()) {
  3817. // If we're dealing with a decl but not a TagDecl, assume that
  3818. // whatever routines created it handled the friendship aspect.
  3819. if (TagD && !Tag)
  3820. return nullptr;
  3821. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3822. }
  3823. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3824. bool IsExplicitSpecialization =
  3825. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3826. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3827. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3828. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3829. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3830. // nested-name-specifier unless it is an explicit instantiation
  3831. // or an explicit specialization.
  3832. //
  3833. // FIXME: We allow class template partial specializations here too, per the
  3834. // obvious intent of DR1819.
  3835. //
  3836. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3837. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3838. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3839. return nullptr;
  3840. }
  3841. // Track whether this decl-specifier declares anything.
  3842. bool DeclaresAnything = true;
  3843. // Handle anonymous struct definitions.
  3844. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3845. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3846. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3847. if (getLangOpts().CPlusPlus ||
  3848. Record->getDeclContext()->isRecord()) {
  3849. // If CurContext is a DeclContext that can contain statements,
  3850. // RecursiveASTVisitor won't visit the decls that
  3851. // BuildAnonymousStructOrUnion() will put into CurContext.
  3852. // Also store them here so that they can be part of the
  3853. // DeclStmt that gets created in this case.
  3854. // FIXME: Also return the IndirectFieldDecls created by
  3855. // BuildAnonymousStructOr union, for the same reason?
  3856. if (CurContext->isFunctionOrMethod())
  3857. AnonRecord = Record;
  3858. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3859. Context.getPrintingPolicy());
  3860. }
  3861. DeclaresAnything = false;
  3862. }
  3863. }
  3864. // C11 6.7.2.1p2:
  3865. // A struct-declaration that does not declare an anonymous structure or
  3866. // anonymous union shall contain a struct-declarator-list.
  3867. //
  3868. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3869. // did not permit a struct-declaration without a struct-declarator-list.
  3870. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3871. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3872. // Check for Microsoft C extension: anonymous struct/union member.
  3873. // Handle 2 kinds of anonymous struct/union:
  3874. // struct STRUCT;
  3875. // union UNION;
  3876. // and
  3877. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3878. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3879. if ((Tag && Tag->getDeclName()) ||
  3880. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3881. RecordDecl *Record = nullptr;
  3882. if (Tag)
  3883. Record = dyn_cast<RecordDecl>(Tag);
  3884. else if (const RecordType *RT =
  3885. DS.getRepAsType().get()->getAsStructureType())
  3886. Record = RT->getDecl();
  3887. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3888. Record = UT->getDecl();
  3889. if (Record && getLangOpts().MicrosoftExt) {
  3890. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3891. << Record->isUnion() << DS.getSourceRange();
  3892. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3893. }
  3894. DeclaresAnything = false;
  3895. }
  3896. }
  3897. // Skip all the checks below if we have a type error.
  3898. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3899. (TagD && TagD->isInvalidDecl()))
  3900. return TagD;
  3901. if (getLangOpts().CPlusPlus &&
  3902. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3903. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3904. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3905. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3906. DeclaresAnything = false;
  3907. if (!DS.isMissingDeclaratorOk()) {
  3908. // Customize diagnostic for a typedef missing a name.
  3909. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3910. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  3911. << DS.getSourceRange();
  3912. else
  3913. DeclaresAnything = false;
  3914. }
  3915. if (DS.isModulePrivateSpecified() &&
  3916. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3917. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3918. << Tag->getTagKind()
  3919. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3920. ActOnDocumentableDecl(TagD);
  3921. // C 6.7/2:
  3922. // A declaration [...] shall declare at least a declarator [...], a tag,
  3923. // or the members of an enumeration.
  3924. // C++ [dcl.dcl]p3:
  3925. // [If there are no declarators], and except for the declaration of an
  3926. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3927. // names into the program, or shall redeclare a name introduced by a
  3928. // previous declaration.
  3929. if (!DeclaresAnything) {
  3930. // In C, we allow this as a (popular) extension / bug. Don't bother
  3931. // producing further diagnostics for redundant qualifiers after this.
  3932. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  3933. return TagD;
  3934. }
  3935. // C++ [dcl.stc]p1:
  3936. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3937. // init-declarator-list of the declaration shall not be empty.
  3938. // C++ [dcl.fct.spec]p1:
  3939. // If a cv-qualifier appears in a decl-specifier-seq, the
  3940. // init-declarator-list of the declaration shall not be empty.
  3941. //
  3942. // Spurious qualifiers here appear to be valid in C.
  3943. unsigned DiagID = diag::warn_standalone_specifier;
  3944. if (getLangOpts().CPlusPlus)
  3945. DiagID = diag::ext_standalone_specifier;
  3946. // Note that a linkage-specification sets a storage class, but
  3947. // 'extern "C" struct foo;' is actually valid and not theoretically
  3948. // useless.
  3949. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3950. if (SCS == DeclSpec::SCS_mutable)
  3951. // Since mutable is not a viable storage class specifier in C, there is
  3952. // no reason to treat it as an extension. Instead, diagnose as an error.
  3953. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3954. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3955. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3956. << DeclSpec::getSpecifierName(SCS);
  3957. }
  3958. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3959. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3960. << DeclSpec::getSpecifierName(TSCS);
  3961. if (DS.getTypeQualifiers()) {
  3962. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3963. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3964. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3965. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3966. // Restrict is covered above.
  3967. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3968. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3969. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3970. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3971. }
  3972. // Warn about ignored type attributes, for example:
  3973. // __attribute__((aligned)) struct A;
  3974. // Attributes should be placed after tag to apply to type declaration.
  3975. if (!DS.getAttributes().empty()) {
  3976. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3977. if (TypeSpecType == DeclSpec::TST_class ||
  3978. TypeSpecType == DeclSpec::TST_struct ||
  3979. TypeSpecType == DeclSpec::TST_interface ||
  3980. TypeSpecType == DeclSpec::TST_union ||
  3981. TypeSpecType == DeclSpec::TST_enum) {
  3982. for (const ParsedAttr &AL : DS.getAttributes())
  3983. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  3984. << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3985. }
  3986. }
  3987. return TagD;
  3988. }
  3989. /// We are trying to inject an anonymous member into the given scope;
  3990. /// check if there's an existing declaration that can't be overloaded.
  3991. ///
  3992. /// \return true if this is a forbidden redeclaration
  3993. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3994. Scope *S,
  3995. DeclContext *Owner,
  3996. DeclarationName Name,
  3997. SourceLocation NameLoc,
  3998. bool IsUnion) {
  3999. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4000. Sema::ForVisibleRedeclaration);
  4001. if (!SemaRef.LookupName(R, S)) return false;
  4002. // Pick a representative declaration.
  4003. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4004. assert(PrevDecl && "Expected a non-null Decl");
  4005. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4006. return false;
  4007. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4008. << IsUnion << Name;
  4009. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4010. return true;
  4011. }
  4012. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4013. /// anonymous struct or union AnonRecord into the owning context Owner
  4014. /// and scope S. This routine will be invoked just after we realize
  4015. /// that an unnamed union or struct is actually an anonymous union or
  4016. /// struct, e.g.,
  4017. ///
  4018. /// @code
  4019. /// union {
  4020. /// int i;
  4021. /// float f;
  4022. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4023. /// // f into the surrounding scope.x
  4024. /// @endcode
  4025. ///
  4026. /// This routine is recursive, injecting the names of nested anonymous
  4027. /// structs/unions into the owning context and scope as well.
  4028. static bool
  4029. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4030. RecordDecl *AnonRecord, AccessSpecifier AS,
  4031. SmallVectorImpl<NamedDecl *> &Chaining) {
  4032. bool Invalid = false;
  4033. // Look every FieldDecl and IndirectFieldDecl with a name.
  4034. for (auto *D : AnonRecord->decls()) {
  4035. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4036. cast<NamedDecl>(D)->getDeclName()) {
  4037. ValueDecl *VD = cast<ValueDecl>(D);
  4038. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4039. VD->getLocation(),
  4040. AnonRecord->isUnion())) {
  4041. // C++ [class.union]p2:
  4042. // The names of the members of an anonymous union shall be
  4043. // distinct from the names of any other entity in the
  4044. // scope in which the anonymous union is declared.
  4045. Invalid = true;
  4046. } else {
  4047. // C++ [class.union]p2:
  4048. // For the purpose of name lookup, after the anonymous union
  4049. // definition, the members of the anonymous union are
  4050. // considered to have been defined in the scope in which the
  4051. // anonymous union is declared.
  4052. unsigned OldChainingSize = Chaining.size();
  4053. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4054. Chaining.append(IF->chain_begin(), IF->chain_end());
  4055. else
  4056. Chaining.push_back(VD);
  4057. assert(Chaining.size() >= 2);
  4058. NamedDecl **NamedChain =
  4059. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4060. for (unsigned i = 0; i < Chaining.size(); i++)
  4061. NamedChain[i] = Chaining[i];
  4062. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4063. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4064. VD->getType(), {NamedChain, Chaining.size()});
  4065. for (const auto *Attr : VD->attrs())
  4066. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4067. IndirectField->setAccess(AS);
  4068. IndirectField->setImplicit();
  4069. SemaRef.PushOnScopeChains(IndirectField, S);
  4070. // That includes picking up the appropriate access specifier.
  4071. if (AS != AS_none) IndirectField->setAccess(AS);
  4072. Chaining.resize(OldChainingSize);
  4073. }
  4074. }
  4075. }
  4076. return Invalid;
  4077. }
  4078. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4079. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4080. /// illegal input values are mapped to SC_None.
  4081. static StorageClass
  4082. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4083. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4084. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4085. "Parser allowed 'typedef' as storage class VarDecl.");
  4086. switch (StorageClassSpec) {
  4087. case DeclSpec::SCS_unspecified: return SC_None;
  4088. case DeclSpec::SCS_extern:
  4089. if (DS.isExternInLinkageSpec())
  4090. return SC_None;
  4091. return SC_Extern;
  4092. case DeclSpec::SCS_static: return SC_Static;
  4093. case DeclSpec::SCS_auto: return SC_Auto;
  4094. case DeclSpec::SCS_register: return SC_Register;
  4095. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4096. // Illegal SCSs map to None: error reporting is up to the caller.
  4097. case DeclSpec::SCS_mutable: // Fall through.
  4098. case DeclSpec::SCS_typedef: return SC_None;
  4099. }
  4100. llvm_unreachable("unknown storage class specifier");
  4101. }
  4102. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4103. assert(Record->hasInClassInitializer());
  4104. for (const auto *I : Record->decls()) {
  4105. const auto *FD = dyn_cast<FieldDecl>(I);
  4106. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4107. FD = IFD->getAnonField();
  4108. if (FD && FD->hasInClassInitializer())
  4109. return FD->getLocation();
  4110. }
  4111. llvm_unreachable("couldn't find in-class initializer");
  4112. }
  4113. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4114. SourceLocation DefaultInitLoc) {
  4115. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4116. return;
  4117. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4118. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4119. }
  4120. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4121. CXXRecordDecl *AnonUnion) {
  4122. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4123. return;
  4124. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4125. }
  4126. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4127. /// anonymous structure or union. Anonymous unions are a C++ feature
  4128. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4129. /// are a C11 feature and GNU C++ extension.
  4130. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4131. AccessSpecifier AS,
  4132. RecordDecl *Record,
  4133. const PrintingPolicy &Policy) {
  4134. DeclContext *Owner = Record->getDeclContext();
  4135. // Diagnose whether this anonymous struct/union is an extension.
  4136. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4137. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4138. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4139. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4140. else if (!Record->isUnion() && !getLangOpts().C11)
  4141. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4142. // C and C++ require different kinds of checks for anonymous
  4143. // structs/unions.
  4144. bool Invalid = false;
  4145. if (getLangOpts().CPlusPlus) {
  4146. const char *PrevSpec = nullptr;
  4147. unsigned DiagID;
  4148. if (Record->isUnion()) {
  4149. // C++ [class.union]p6:
  4150. // C++17 [class.union.anon]p2:
  4151. // Anonymous unions declared in a named namespace or in the
  4152. // global namespace shall be declared static.
  4153. DeclContext *OwnerScope = Owner->getRedeclContext();
  4154. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4155. (OwnerScope->isTranslationUnit() ||
  4156. (OwnerScope->isNamespace() &&
  4157. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4158. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4159. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4160. // Recover by adding 'static'.
  4161. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4162. PrevSpec, DiagID, Policy);
  4163. }
  4164. // C++ [class.union]p6:
  4165. // A storage class is not allowed in a declaration of an
  4166. // anonymous union in a class scope.
  4167. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4168. isa<RecordDecl>(Owner)) {
  4169. Diag(DS.getStorageClassSpecLoc(),
  4170. diag::err_anonymous_union_with_storage_spec)
  4171. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4172. // Recover by removing the storage specifier.
  4173. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4174. SourceLocation(),
  4175. PrevSpec, DiagID, Context.getPrintingPolicy());
  4176. }
  4177. }
  4178. // Ignore const/volatile/restrict qualifiers.
  4179. if (DS.getTypeQualifiers()) {
  4180. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4181. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4182. << Record->isUnion() << "const"
  4183. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4184. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4185. Diag(DS.getVolatileSpecLoc(),
  4186. diag::ext_anonymous_struct_union_qualified)
  4187. << Record->isUnion() << "volatile"
  4188. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4189. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4190. Diag(DS.getRestrictSpecLoc(),
  4191. diag::ext_anonymous_struct_union_qualified)
  4192. << Record->isUnion() << "restrict"
  4193. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4194. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4195. Diag(DS.getAtomicSpecLoc(),
  4196. diag::ext_anonymous_struct_union_qualified)
  4197. << Record->isUnion() << "_Atomic"
  4198. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4199. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4200. Diag(DS.getUnalignedSpecLoc(),
  4201. diag::ext_anonymous_struct_union_qualified)
  4202. << Record->isUnion() << "__unaligned"
  4203. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4204. DS.ClearTypeQualifiers();
  4205. }
  4206. // C++ [class.union]p2:
  4207. // The member-specification of an anonymous union shall only
  4208. // define non-static data members. [Note: nested types and
  4209. // functions cannot be declared within an anonymous union. ]
  4210. for (auto *Mem : Record->decls()) {
  4211. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4212. // C++ [class.union]p3:
  4213. // An anonymous union shall not have private or protected
  4214. // members (clause 11).
  4215. assert(FD->getAccess() != AS_none);
  4216. if (FD->getAccess() != AS_public) {
  4217. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4218. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4219. Invalid = true;
  4220. }
  4221. // C++ [class.union]p1
  4222. // An object of a class with a non-trivial constructor, a non-trivial
  4223. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4224. // assignment operator cannot be a member of a union, nor can an
  4225. // array of such objects.
  4226. if (CheckNontrivialField(FD))
  4227. Invalid = true;
  4228. } else if (Mem->isImplicit()) {
  4229. // Any implicit members are fine.
  4230. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4231. // This is a type that showed up in an
  4232. // elaborated-type-specifier inside the anonymous struct or
  4233. // union, but which actually declares a type outside of the
  4234. // anonymous struct or union. It's okay.
  4235. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4236. if (!MemRecord->isAnonymousStructOrUnion() &&
  4237. MemRecord->getDeclName()) {
  4238. // Visual C++ allows type definition in anonymous struct or union.
  4239. if (getLangOpts().MicrosoftExt)
  4240. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4241. << Record->isUnion();
  4242. else {
  4243. // This is a nested type declaration.
  4244. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4245. << Record->isUnion();
  4246. Invalid = true;
  4247. }
  4248. } else {
  4249. // This is an anonymous type definition within another anonymous type.
  4250. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4251. // not part of standard C++.
  4252. Diag(MemRecord->getLocation(),
  4253. diag::ext_anonymous_record_with_anonymous_type)
  4254. << Record->isUnion();
  4255. }
  4256. } else if (isa<AccessSpecDecl>(Mem)) {
  4257. // Any access specifier is fine.
  4258. } else if (isa<StaticAssertDecl>(Mem)) {
  4259. // In C++1z, static_assert declarations are also fine.
  4260. } else {
  4261. // We have something that isn't a non-static data
  4262. // member. Complain about it.
  4263. unsigned DK = diag::err_anonymous_record_bad_member;
  4264. if (isa<TypeDecl>(Mem))
  4265. DK = diag::err_anonymous_record_with_type;
  4266. else if (isa<FunctionDecl>(Mem))
  4267. DK = diag::err_anonymous_record_with_function;
  4268. else if (isa<VarDecl>(Mem))
  4269. DK = diag::err_anonymous_record_with_static;
  4270. // Visual C++ allows type definition in anonymous struct or union.
  4271. if (getLangOpts().MicrosoftExt &&
  4272. DK == diag::err_anonymous_record_with_type)
  4273. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4274. << Record->isUnion();
  4275. else {
  4276. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4277. Invalid = true;
  4278. }
  4279. }
  4280. }
  4281. // C++11 [class.union]p8 (DR1460):
  4282. // At most one variant member of a union may have a
  4283. // brace-or-equal-initializer.
  4284. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4285. Owner->isRecord())
  4286. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4287. cast<CXXRecordDecl>(Record));
  4288. }
  4289. if (!Record->isUnion() && !Owner->isRecord()) {
  4290. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4291. << getLangOpts().CPlusPlus;
  4292. Invalid = true;
  4293. }
  4294. // C++ [dcl.dcl]p3:
  4295. // [If there are no declarators], and except for the declaration of an
  4296. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4297. // names into the program
  4298. // C++ [class.mem]p2:
  4299. // each such member-declaration shall either declare at least one member
  4300. // name of the class or declare at least one unnamed bit-field
  4301. //
  4302. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4303. if (getLangOpts().CPlusPlus && Record->field_empty())
  4304. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4305. // Mock up a declarator.
  4306. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4307. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4308. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4309. // Create a declaration for this anonymous struct/union.
  4310. NamedDecl *Anon = nullptr;
  4311. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4312. Anon = FieldDecl::Create(
  4313. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4314. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4315. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4316. /*InitStyle=*/ICIS_NoInit);
  4317. Anon->setAccess(AS);
  4318. if (getLangOpts().CPlusPlus)
  4319. FieldCollector->Add(cast<FieldDecl>(Anon));
  4320. } else {
  4321. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4322. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4323. if (SCSpec == DeclSpec::SCS_mutable) {
  4324. // mutable can only appear on non-static class members, so it's always
  4325. // an error here
  4326. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4327. Invalid = true;
  4328. SC = SC_None;
  4329. }
  4330. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4331. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4332. Context.getTypeDeclType(Record), TInfo, SC);
  4333. // Default-initialize the implicit variable. This initialization will be
  4334. // trivial in almost all cases, except if a union member has an in-class
  4335. // initializer:
  4336. // union { int n = 0; };
  4337. ActOnUninitializedDecl(Anon);
  4338. }
  4339. Anon->setImplicit();
  4340. // Mark this as an anonymous struct/union type.
  4341. Record->setAnonymousStructOrUnion(true);
  4342. // Add the anonymous struct/union object to the current
  4343. // context. We'll be referencing this object when we refer to one of
  4344. // its members.
  4345. Owner->addDecl(Anon);
  4346. // Inject the members of the anonymous struct/union into the owning
  4347. // context and into the identifier resolver chain for name lookup
  4348. // purposes.
  4349. SmallVector<NamedDecl*, 2> Chain;
  4350. Chain.push_back(Anon);
  4351. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4352. Invalid = true;
  4353. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4354. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4355. Decl *ManglingContextDecl;
  4356. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4357. NewVD->getDeclContext(), ManglingContextDecl)) {
  4358. Context.setManglingNumber(
  4359. NewVD, MCtx->getManglingNumber(
  4360. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4361. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4362. }
  4363. }
  4364. }
  4365. if (Invalid)
  4366. Anon->setInvalidDecl();
  4367. return Anon;
  4368. }
  4369. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4370. /// Microsoft C anonymous structure.
  4371. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4372. /// Example:
  4373. ///
  4374. /// struct A { int a; };
  4375. /// struct B { struct A; int b; };
  4376. ///
  4377. /// void foo() {
  4378. /// B var;
  4379. /// var.a = 3;
  4380. /// }
  4381. ///
  4382. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4383. RecordDecl *Record) {
  4384. assert(Record && "expected a record!");
  4385. // Mock up a declarator.
  4386. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4387. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4388. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4389. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4390. QualType RecTy = Context.getTypeDeclType(Record);
  4391. // Create a declaration for this anonymous struct.
  4392. NamedDecl *Anon =
  4393. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4394. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4395. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4396. /*InitStyle=*/ICIS_NoInit);
  4397. Anon->setImplicit();
  4398. // Add the anonymous struct object to the current context.
  4399. CurContext->addDecl(Anon);
  4400. // Inject the members of the anonymous struct into the current
  4401. // context and into the identifier resolver chain for name lookup
  4402. // purposes.
  4403. SmallVector<NamedDecl*, 2> Chain;
  4404. Chain.push_back(Anon);
  4405. RecordDecl *RecordDef = Record->getDefinition();
  4406. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4407. diag::err_field_incomplete) ||
  4408. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4409. AS_none, Chain)) {
  4410. Anon->setInvalidDecl();
  4411. ParentDecl->setInvalidDecl();
  4412. }
  4413. return Anon;
  4414. }
  4415. /// GetNameForDeclarator - Determine the full declaration name for the
  4416. /// given Declarator.
  4417. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4418. return GetNameFromUnqualifiedId(D.getName());
  4419. }
  4420. /// Retrieves the declaration name from a parsed unqualified-id.
  4421. DeclarationNameInfo
  4422. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4423. DeclarationNameInfo NameInfo;
  4424. NameInfo.setLoc(Name.StartLocation);
  4425. switch (Name.getKind()) {
  4426. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4427. case UnqualifiedIdKind::IK_Identifier:
  4428. NameInfo.setName(Name.Identifier);
  4429. return NameInfo;
  4430. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4431. // C++ [temp.deduct.guide]p3:
  4432. // The simple-template-id shall name a class template specialization.
  4433. // The template-name shall be the same identifier as the template-name
  4434. // of the simple-template-id.
  4435. // These together intend to imply that the template-name shall name a
  4436. // class template.
  4437. // FIXME: template<typename T> struct X {};
  4438. // template<typename T> using Y = X<T>;
  4439. // Y(int) -> Y<int>;
  4440. // satisfies these rules but does not name a class template.
  4441. TemplateName TN = Name.TemplateName.get().get();
  4442. auto *Template = TN.getAsTemplateDecl();
  4443. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4444. Diag(Name.StartLocation,
  4445. diag::err_deduction_guide_name_not_class_template)
  4446. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4447. if (Template)
  4448. Diag(Template->getLocation(), diag::note_template_decl_here);
  4449. return DeclarationNameInfo();
  4450. }
  4451. NameInfo.setName(
  4452. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4453. return NameInfo;
  4454. }
  4455. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4456. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4457. Name.OperatorFunctionId.Operator));
  4458. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4459. = Name.OperatorFunctionId.SymbolLocations[0];
  4460. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4461. = Name.EndLocation.getRawEncoding();
  4462. return NameInfo;
  4463. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4464. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4465. Name.Identifier));
  4466. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4467. return NameInfo;
  4468. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4469. TypeSourceInfo *TInfo;
  4470. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4471. if (Ty.isNull())
  4472. return DeclarationNameInfo();
  4473. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4474. Context.getCanonicalType(Ty)));
  4475. NameInfo.setNamedTypeInfo(TInfo);
  4476. return NameInfo;
  4477. }
  4478. case UnqualifiedIdKind::IK_ConstructorName: {
  4479. TypeSourceInfo *TInfo;
  4480. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4481. if (Ty.isNull())
  4482. return DeclarationNameInfo();
  4483. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4484. Context.getCanonicalType(Ty)));
  4485. NameInfo.setNamedTypeInfo(TInfo);
  4486. return NameInfo;
  4487. }
  4488. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4489. // In well-formed code, we can only have a constructor
  4490. // template-id that refers to the current context, so go there
  4491. // to find the actual type being constructed.
  4492. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4493. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4494. return DeclarationNameInfo();
  4495. // Determine the type of the class being constructed.
  4496. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4497. // FIXME: Check two things: that the template-id names the same type as
  4498. // CurClassType, and that the template-id does not occur when the name
  4499. // was qualified.
  4500. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4501. Context.getCanonicalType(CurClassType)));
  4502. // FIXME: should we retrieve TypeSourceInfo?
  4503. NameInfo.setNamedTypeInfo(nullptr);
  4504. return NameInfo;
  4505. }
  4506. case UnqualifiedIdKind::IK_DestructorName: {
  4507. TypeSourceInfo *TInfo;
  4508. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4509. if (Ty.isNull())
  4510. return DeclarationNameInfo();
  4511. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4512. Context.getCanonicalType(Ty)));
  4513. NameInfo.setNamedTypeInfo(TInfo);
  4514. return NameInfo;
  4515. }
  4516. case UnqualifiedIdKind::IK_TemplateId: {
  4517. TemplateName TName = Name.TemplateId->Template.get();
  4518. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4519. return Context.getNameForTemplate(TName, TNameLoc);
  4520. }
  4521. } // switch (Name.getKind())
  4522. llvm_unreachable("Unknown name kind");
  4523. }
  4524. static QualType getCoreType(QualType Ty) {
  4525. do {
  4526. if (Ty->isPointerType() || Ty->isReferenceType())
  4527. Ty = Ty->getPointeeType();
  4528. else if (Ty->isArrayType())
  4529. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4530. else
  4531. return Ty.withoutLocalFastQualifiers();
  4532. } while (true);
  4533. }
  4534. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4535. /// and Definition have "nearly" matching parameters. This heuristic is
  4536. /// used to improve diagnostics in the case where an out-of-line function
  4537. /// definition doesn't match any declaration within the class or namespace.
  4538. /// Also sets Params to the list of indices to the parameters that differ
  4539. /// between the declaration and the definition. If hasSimilarParameters
  4540. /// returns true and Params is empty, then all of the parameters match.
  4541. static bool hasSimilarParameters(ASTContext &Context,
  4542. FunctionDecl *Declaration,
  4543. FunctionDecl *Definition,
  4544. SmallVectorImpl<unsigned> &Params) {
  4545. Params.clear();
  4546. if (Declaration->param_size() != Definition->param_size())
  4547. return false;
  4548. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4549. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4550. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4551. // The parameter types are identical
  4552. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4553. continue;
  4554. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4555. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4556. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4557. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4558. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4559. (DeclTyName && DeclTyName == DefTyName))
  4560. Params.push_back(Idx);
  4561. else // The two parameters aren't even close
  4562. return false;
  4563. }
  4564. return true;
  4565. }
  4566. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4567. /// declarator needs to be rebuilt in the current instantiation.
  4568. /// Any bits of declarator which appear before the name are valid for
  4569. /// consideration here. That's specifically the type in the decl spec
  4570. /// and the base type in any member-pointer chunks.
  4571. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4572. DeclarationName Name) {
  4573. // The types we specifically need to rebuild are:
  4574. // - typenames, typeofs, and decltypes
  4575. // - types which will become injected class names
  4576. // Of course, we also need to rebuild any type referencing such a
  4577. // type. It's safest to just say "dependent", but we call out a
  4578. // few cases here.
  4579. DeclSpec &DS = D.getMutableDeclSpec();
  4580. switch (DS.getTypeSpecType()) {
  4581. case DeclSpec::TST_typename:
  4582. case DeclSpec::TST_typeofType:
  4583. case DeclSpec::TST_underlyingType:
  4584. case DeclSpec::TST_atomic: {
  4585. // Grab the type from the parser.
  4586. TypeSourceInfo *TSI = nullptr;
  4587. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4588. if (T.isNull() || !T->isDependentType()) break;
  4589. // Make sure there's a type source info. This isn't really much
  4590. // of a waste; most dependent types should have type source info
  4591. // attached already.
  4592. if (!TSI)
  4593. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4594. // Rebuild the type in the current instantiation.
  4595. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4596. if (!TSI) return true;
  4597. // Store the new type back in the decl spec.
  4598. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4599. DS.UpdateTypeRep(LocType);
  4600. break;
  4601. }
  4602. case DeclSpec::TST_decltype:
  4603. case DeclSpec::TST_typeofExpr: {
  4604. Expr *E = DS.getRepAsExpr();
  4605. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4606. if (Result.isInvalid()) return true;
  4607. DS.UpdateExprRep(Result.get());
  4608. break;
  4609. }
  4610. default:
  4611. // Nothing to do for these decl specs.
  4612. break;
  4613. }
  4614. // It doesn't matter what order we do this in.
  4615. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4616. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4617. // The only type information in the declarator which can come
  4618. // before the declaration name is the base type of a member
  4619. // pointer.
  4620. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4621. continue;
  4622. // Rebuild the scope specifier in-place.
  4623. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4624. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4625. return true;
  4626. }
  4627. return false;
  4628. }
  4629. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4630. D.setFunctionDefinitionKind(FDK_Declaration);
  4631. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4632. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4633. Dcl && Dcl->getDeclContext()->isFileContext())
  4634. Dcl->setTopLevelDeclInObjCContainer();
  4635. if (getLangOpts().OpenCL)
  4636. setCurrentOpenCLExtensionForDecl(Dcl);
  4637. return Dcl;
  4638. }
  4639. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4640. /// If T is the name of a class, then each of the following shall have a
  4641. /// name different from T:
  4642. /// - every static data member of class T;
  4643. /// - every member function of class T
  4644. /// - every member of class T that is itself a type;
  4645. /// \returns true if the declaration name violates these rules.
  4646. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4647. DeclarationNameInfo NameInfo) {
  4648. DeclarationName Name = NameInfo.getName();
  4649. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4650. while (Record && Record->isAnonymousStructOrUnion())
  4651. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4652. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4653. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4654. return true;
  4655. }
  4656. return false;
  4657. }
  4658. /// Diagnose a declaration whose declarator-id has the given
  4659. /// nested-name-specifier.
  4660. ///
  4661. /// \param SS The nested-name-specifier of the declarator-id.
  4662. ///
  4663. /// \param DC The declaration context to which the nested-name-specifier
  4664. /// resolves.
  4665. ///
  4666. /// \param Name The name of the entity being declared.
  4667. ///
  4668. /// \param Loc The location of the name of the entity being declared.
  4669. ///
  4670. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4671. /// we're declaring an explicit / partial specialization / instantiation.
  4672. ///
  4673. /// \returns true if we cannot safely recover from this error, false otherwise.
  4674. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4675. DeclarationName Name,
  4676. SourceLocation Loc, bool IsTemplateId) {
  4677. DeclContext *Cur = CurContext;
  4678. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4679. Cur = Cur->getParent();
  4680. // If the user provided a superfluous scope specifier that refers back to the
  4681. // class in which the entity is already declared, diagnose and ignore it.
  4682. //
  4683. // class X {
  4684. // void X::f();
  4685. // };
  4686. //
  4687. // Note, it was once ill-formed to give redundant qualification in all
  4688. // contexts, but that rule was removed by DR482.
  4689. if (Cur->Equals(DC)) {
  4690. if (Cur->isRecord()) {
  4691. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4692. : diag::err_member_extra_qualification)
  4693. << Name << FixItHint::CreateRemoval(SS.getRange());
  4694. SS.clear();
  4695. } else {
  4696. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4697. }
  4698. return false;
  4699. }
  4700. // Check whether the qualifying scope encloses the scope of the original
  4701. // declaration. For a template-id, we perform the checks in
  4702. // CheckTemplateSpecializationScope.
  4703. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4704. if (Cur->isRecord())
  4705. Diag(Loc, diag::err_member_qualification)
  4706. << Name << SS.getRange();
  4707. else if (isa<TranslationUnitDecl>(DC))
  4708. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4709. << Name << SS.getRange();
  4710. else if (isa<FunctionDecl>(Cur))
  4711. Diag(Loc, diag::err_invalid_declarator_in_function)
  4712. << Name << SS.getRange();
  4713. else if (isa<BlockDecl>(Cur))
  4714. Diag(Loc, diag::err_invalid_declarator_in_block)
  4715. << Name << SS.getRange();
  4716. else
  4717. Diag(Loc, diag::err_invalid_declarator_scope)
  4718. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4719. return true;
  4720. }
  4721. if (Cur->isRecord()) {
  4722. // Cannot qualify members within a class.
  4723. Diag(Loc, diag::err_member_qualification)
  4724. << Name << SS.getRange();
  4725. SS.clear();
  4726. // C++ constructors and destructors with incorrect scopes can break
  4727. // our AST invariants by having the wrong underlying types. If
  4728. // that's the case, then drop this declaration entirely.
  4729. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4730. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4731. !Context.hasSameType(Name.getCXXNameType(),
  4732. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4733. return true;
  4734. return false;
  4735. }
  4736. // C++11 [dcl.meaning]p1:
  4737. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4738. // not begin with a decltype-specifer"
  4739. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4740. while (SpecLoc.getPrefix())
  4741. SpecLoc = SpecLoc.getPrefix();
  4742. if (dyn_cast_or_null<DecltypeType>(
  4743. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4744. Diag(Loc, diag::err_decltype_in_declarator)
  4745. << SpecLoc.getTypeLoc().getSourceRange();
  4746. return false;
  4747. }
  4748. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4749. MultiTemplateParamsArg TemplateParamLists) {
  4750. // TODO: consider using NameInfo for diagnostic.
  4751. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4752. DeclarationName Name = NameInfo.getName();
  4753. // All of these full declarators require an identifier. If it doesn't have
  4754. // one, the ParsedFreeStandingDeclSpec action should be used.
  4755. if (D.isDecompositionDeclarator()) {
  4756. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4757. } else if (!Name) {
  4758. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4759. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4760. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4761. return nullptr;
  4762. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4763. return nullptr;
  4764. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4765. // we find one that is.
  4766. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4767. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4768. S = S->getParent();
  4769. DeclContext *DC = CurContext;
  4770. if (D.getCXXScopeSpec().isInvalid())
  4771. D.setInvalidType();
  4772. else if (D.getCXXScopeSpec().isSet()) {
  4773. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4774. UPPC_DeclarationQualifier))
  4775. return nullptr;
  4776. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4777. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4778. if (!DC || isa<EnumDecl>(DC)) {
  4779. // If we could not compute the declaration context, it's because the
  4780. // declaration context is dependent but does not refer to a class,
  4781. // class template, or class template partial specialization. Complain
  4782. // and return early, to avoid the coming semantic disaster.
  4783. Diag(D.getIdentifierLoc(),
  4784. diag::err_template_qualified_declarator_no_match)
  4785. << D.getCXXScopeSpec().getScopeRep()
  4786. << D.getCXXScopeSpec().getRange();
  4787. return nullptr;
  4788. }
  4789. bool IsDependentContext = DC->isDependentContext();
  4790. if (!IsDependentContext &&
  4791. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4792. return nullptr;
  4793. // If a class is incomplete, do not parse entities inside it.
  4794. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4795. Diag(D.getIdentifierLoc(),
  4796. diag::err_member_def_undefined_record)
  4797. << Name << DC << D.getCXXScopeSpec().getRange();
  4798. return nullptr;
  4799. }
  4800. if (!D.getDeclSpec().isFriendSpecified()) {
  4801. if (diagnoseQualifiedDeclaration(
  4802. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4803. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4804. if (DC->isRecord())
  4805. return nullptr;
  4806. D.setInvalidType();
  4807. }
  4808. }
  4809. // Check whether we need to rebuild the type of the given
  4810. // declaration in the current instantiation.
  4811. if (EnteringContext && IsDependentContext &&
  4812. TemplateParamLists.size() != 0) {
  4813. ContextRAII SavedContext(*this, DC);
  4814. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4815. D.setInvalidType();
  4816. }
  4817. }
  4818. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4819. QualType R = TInfo->getType();
  4820. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4821. UPPC_DeclarationType))
  4822. D.setInvalidType();
  4823. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4824. forRedeclarationInCurContext());
  4825. // See if this is a redefinition of a variable in the same scope.
  4826. if (!D.getCXXScopeSpec().isSet()) {
  4827. bool IsLinkageLookup = false;
  4828. bool CreateBuiltins = false;
  4829. // If the declaration we're planning to build will be a function
  4830. // or object with linkage, then look for another declaration with
  4831. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4832. //
  4833. // If the declaration we're planning to build will be declared with
  4834. // external linkage in the translation unit, create any builtin with
  4835. // the same name.
  4836. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4837. /* Do nothing*/;
  4838. else if (CurContext->isFunctionOrMethod() &&
  4839. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4840. R->isFunctionType())) {
  4841. IsLinkageLookup = true;
  4842. CreateBuiltins =
  4843. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4844. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4845. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4846. CreateBuiltins = true;
  4847. if (IsLinkageLookup) {
  4848. Previous.clear(LookupRedeclarationWithLinkage);
  4849. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4850. }
  4851. LookupName(Previous, S, CreateBuiltins);
  4852. } else { // Something like "int foo::x;"
  4853. LookupQualifiedName(Previous, DC);
  4854. // C++ [dcl.meaning]p1:
  4855. // When the declarator-id is qualified, the declaration shall refer to a
  4856. // previously declared member of the class or namespace to which the
  4857. // qualifier refers (or, in the case of a namespace, of an element of the
  4858. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4859. // thereof; [...]
  4860. //
  4861. // Note that we already checked the context above, and that we do not have
  4862. // enough information to make sure that Previous contains the declaration
  4863. // we want to match. For example, given:
  4864. //
  4865. // class X {
  4866. // void f();
  4867. // void f(float);
  4868. // };
  4869. //
  4870. // void X::f(int) { } // ill-formed
  4871. //
  4872. // In this case, Previous will point to the overload set
  4873. // containing the two f's declared in X, but neither of them
  4874. // matches.
  4875. // C++ [dcl.meaning]p1:
  4876. // [...] the member shall not merely have been introduced by a
  4877. // using-declaration in the scope of the class or namespace nominated by
  4878. // the nested-name-specifier of the declarator-id.
  4879. RemoveUsingDecls(Previous);
  4880. }
  4881. if (Previous.isSingleResult() &&
  4882. Previous.getFoundDecl()->isTemplateParameter()) {
  4883. // Maybe we will complain about the shadowed template parameter.
  4884. if (!D.isInvalidType())
  4885. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4886. Previous.getFoundDecl());
  4887. // Just pretend that we didn't see the previous declaration.
  4888. Previous.clear();
  4889. }
  4890. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4891. // Forget that the previous declaration is the injected-class-name.
  4892. Previous.clear();
  4893. // In C++, the previous declaration we find might be a tag type
  4894. // (class or enum). In this case, the new declaration will hide the
  4895. // tag type. Note that this applies to functions, function templates, and
  4896. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4897. if (Previous.isSingleTagDecl() &&
  4898. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4899. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4900. Previous.clear();
  4901. // Check that there are no default arguments other than in the parameters
  4902. // of a function declaration (C++ only).
  4903. if (getLangOpts().CPlusPlus)
  4904. CheckExtraCXXDefaultArguments(D);
  4905. NamedDecl *New;
  4906. bool AddToScope = true;
  4907. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4908. if (TemplateParamLists.size()) {
  4909. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4910. return nullptr;
  4911. }
  4912. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4913. } else if (R->isFunctionType()) {
  4914. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4915. TemplateParamLists,
  4916. AddToScope);
  4917. } else {
  4918. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4919. AddToScope);
  4920. }
  4921. if (!New)
  4922. return nullptr;
  4923. // If this has an identifier and is not a function template specialization,
  4924. // add it to the scope stack.
  4925. if (New->getDeclName() && AddToScope)
  4926. PushOnScopeChains(New, S);
  4927. if (isInOpenMPDeclareTargetContext())
  4928. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4929. return New;
  4930. }
  4931. /// Helper method to turn variable array types into constant array
  4932. /// types in certain situations which would otherwise be errors (for
  4933. /// GCC compatibility).
  4934. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4935. ASTContext &Context,
  4936. bool &SizeIsNegative,
  4937. llvm::APSInt &Oversized) {
  4938. // This method tries to turn a variable array into a constant
  4939. // array even when the size isn't an ICE. This is necessary
  4940. // for compatibility with code that depends on gcc's buggy
  4941. // constant expression folding, like struct {char x[(int)(char*)2];}
  4942. SizeIsNegative = false;
  4943. Oversized = 0;
  4944. if (T->isDependentType())
  4945. return QualType();
  4946. QualifierCollector Qs;
  4947. const Type *Ty = Qs.strip(T);
  4948. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4949. QualType Pointee = PTy->getPointeeType();
  4950. QualType FixedType =
  4951. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4952. Oversized);
  4953. if (FixedType.isNull()) return FixedType;
  4954. FixedType = Context.getPointerType(FixedType);
  4955. return Qs.apply(Context, FixedType);
  4956. }
  4957. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4958. QualType Inner = PTy->getInnerType();
  4959. QualType FixedType =
  4960. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4961. Oversized);
  4962. if (FixedType.isNull()) return FixedType;
  4963. FixedType = Context.getParenType(FixedType);
  4964. return Qs.apply(Context, FixedType);
  4965. }
  4966. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4967. if (!VLATy)
  4968. return QualType();
  4969. // FIXME: We should probably handle this case
  4970. if (VLATy->getElementType()->isVariablyModifiedType())
  4971. return QualType();
  4972. Expr::EvalResult Result;
  4973. if (!VLATy->getSizeExpr() ||
  4974. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  4975. return QualType();
  4976. llvm::APSInt Res = Result.Val.getInt();
  4977. // Check whether the array size is negative.
  4978. if (Res.isSigned() && Res.isNegative()) {
  4979. SizeIsNegative = true;
  4980. return QualType();
  4981. }
  4982. // Check whether the array is too large to be addressed.
  4983. unsigned ActiveSizeBits
  4984. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4985. Res);
  4986. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4987. Oversized = Res;
  4988. return QualType();
  4989. }
  4990. return Context.getConstantArrayType(VLATy->getElementType(),
  4991. Res, ArrayType::Normal, 0);
  4992. }
  4993. static void
  4994. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4995. SrcTL = SrcTL.getUnqualifiedLoc();
  4996. DstTL = DstTL.getUnqualifiedLoc();
  4997. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4998. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4999. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5000. DstPTL.getPointeeLoc());
  5001. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5002. return;
  5003. }
  5004. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5005. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5006. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5007. DstPTL.getInnerLoc());
  5008. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5009. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5010. return;
  5011. }
  5012. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5013. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5014. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5015. TypeLoc DstElemTL = DstATL.getElementLoc();
  5016. DstElemTL.initializeFullCopy(SrcElemTL);
  5017. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5018. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5019. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5020. }
  5021. /// Helper method to turn variable array types into constant array
  5022. /// types in certain situations which would otherwise be errors (for
  5023. /// GCC compatibility).
  5024. static TypeSourceInfo*
  5025. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5026. ASTContext &Context,
  5027. bool &SizeIsNegative,
  5028. llvm::APSInt &Oversized) {
  5029. QualType FixedTy
  5030. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5031. SizeIsNegative, Oversized);
  5032. if (FixedTy.isNull())
  5033. return nullptr;
  5034. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5035. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5036. FixedTInfo->getTypeLoc());
  5037. return FixedTInfo;
  5038. }
  5039. /// Register the given locally-scoped extern "C" declaration so
  5040. /// that it can be found later for redeclarations. We include any extern "C"
  5041. /// declaration that is not visible in the translation unit here, not just
  5042. /// function-scope declarations.
  5043. void
  5044. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5045. if (!getLangOpts().CPlusPlus &&
  5046. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5047. // Don't need to track declarations in the TU in C.
  5048. return;
  5049. // Note that we have a locally-scoped external with this name.
  5050. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5051. }
  5052. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5053. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5054. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5055. return Result.empty() ? nullptr : *Result.begin();
  5056. }
  5057. /// Diagnose function specifiers on a declaration of an identifier that
  5058. /// does not identify a function.
  5059. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5060. // FIXME: We should probably indicate the identifier in question to avoid
  5061. // confusion for constructs like "virtual int a(), b;"
  5062. if (DS.isVirtualSpecified())
  5063. Diag(DS.getVirtualSpecLoc(),
  5064. diag::err_virtual_non_function);
  5065. if (DS.hasExplicitSpecifier())
  5066. Diag(DS.getExplicitSpecLoc(),
  5067. diag::err_explicit_non_function);
  5068. if (DS.isNoreturnSpecified())
  5069. Diag(DS.getNoreturnSpecLoc(),
  5070. diag::err_noreturn_non_function);
  5071. }
  5072. NamedDecl*
  5073. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5074. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5075. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5076. if (D.getCXXScopeSpec().isSet()) {
  5077. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5078. << D.getCXXScopeSpec().getRange();
  5079. D.setInvalidType();
  5080. // Pretend we didn't see the scope specifier.
  5081. DC = CurContext;
  5082. Previous.clear();
  5083. }
  5084. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5085. if (D.getDeclSpec().isInlineSpecified())
  5086. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5087. << getLangOpts().CPlusPlus17;
  5088. if (D.getDeclSpec().hasConstexprSpecifier())
  5089. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5090. << 1 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
  5091. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5092. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5093. Diag(D.getName().StartLocation,
  5094. diag::err_deduction_guide_invalid_specifier)
  5095. << "typedef";
  5096. else
  5097. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5098. << D.getName().getSourceRange();
  5099. return nullptr;
  5100. }
  5101. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5102. if (!NewTD) return nullptr;
  5103. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5104. ProcessDeclAttributes(S, NewTD, D);
  5105. CheckTypedefForVariablyModifiedType(S, NewTD);
  5106. bool Redeclaration = D.isRedeclaration();
  5107. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5108. D.setRedeclaration(Redeclaration);
  5109. return ND;
  5110. }
  5111. void
  5112. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5113. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5114. // then it shall have block scope.
  5115. // Note that variably modified types must be fixed before merging the decl so
  5116. // that redeclarations will match.
  5117. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5118. QualType T = TInfo->getType();
  5119. if (T->isVariablyModifiedType()) {
  5120. setFunctionHasBranchProtectedScope();
  5121. if (S->getFnParent() == nullptr) {
  5122. bool SizeIsNegative;
  5123. llvm::APSInt Oversized;
  5124. TypeSourceInfo *FixedTInfo =
  5125. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5126. SizeIsNegative,
  5127. Oversized);
  5128. if (FixedTInfo) {
  5129. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5130. NewTD->setTypeSourceInfo(FixedTInfo);
  5131. } else {
  5132. if (SizeIsNegative)
  5133. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5134. else if (T->isVariableArrayType())
  5135. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5136. else if (Oversized.getBoolValue())
  5137. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5138. << Oversized.toString(10);
  5139. else
  5140. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5141. NewTD->setInvalidDecl();
  5142. }
  5143. }
  5144. }
  5145. }
  5146. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5147. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5148. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5149. NamedDecl*
  5150. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5151. LookupResult &Previous, bool &Redeclaration) {
  5152. // Find the shadowed declaration before filtering for scope.
  5153. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5154. // Merge the decl with the existing one if appropriate. If the decl is
  5155. // in an outer scope, it isn't the same thing.
  5156. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5157. /*AllowInlineNamespace*/false);
  5158. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5159. if (!Previous.empty()) {
  5160. Redeclaration = true;
  5161. MergeTypedefNameDecl(S, NewTD, Previous);
  5162. }
  5163. if (ShadowedDecl && !Redeclaration)
  5164. CheckShadow(NewTD, ShadowedDecl, Previous);
  5165. // If this is the C FILE type, notify the AST context.
  5166. if (IdentifierInfo *II = NewTD->getIdentifier())
  5167. if (!NewTD->isInvalidDecl() &&
  5168. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5169. if (II->isStr("FILE"))
  5170. Context.setFILEDecl(NewTD);
  5171. else if (II->isStr("jmp_buf"))
  5172. Context.setjmp_bufDecl(NewTD);
  5173. else if (II->isStr("sigjmp_buf"))
  5174. Context.setsigjmp_bufDecl(NewTD);
  5175. else if (II->isStr("ucontext_t"))
  5176. Context.setucontext_tDecl(NewTD);
  5177. }
  5178. return NewTD;
  5179. }
  5180. /// Determines whether the given declaration is an out-of-scope
  5181. /// previous declaration.
  5182. ///
  5183. /// This routine should be invoked when name lookup has found a
  5184. /// previous declaration (PrevDecl) that is not in the scope where a
  5185. /// new declaration by the same name is being introduced. If the new
  5186. /// declaration occurs in a local scope, previous declarations with
  5187. /// linkage may still be considered previous declarations (C99
  5188. /// 6.2.2p4-5, C++ [basic.link]p6).
  5189. ///
  5190. /// \param PrevDecl the previous declaration found by name
  5191. /// lookup
  5192. ///
  5193. /// \param DC the context in which the new declaration is being
  5194. /// declared.
  5195. ///
  5196. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5197. /// for a new delcaration with the same name.
  5198. static bool
  5199. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5200. ASTContext &Context) {
  5201. if (!PrevDecl)
  5202. return false;
  5203. if (!PrevDecl->hasLinkage())
  5204. return false;
  5205. if (Context.getLangOpts().CPlusPlus) {
  5206. // C++ [basic.link]p6:
  5207. // If there is a visible declaration of an entity with linkage
  5208. // having the same name and type, ignoring entities declared
  5209. // outside the innermost enclosing namespace scope, the block
  5210. // scope declaration declares that same entity and receives the
  5211. // linkage of the previous declaration.
  5212. DeclContext *OuterContext = DC->getRedeclContext();
  5213. if (!OuterContext->isFunctionOrMethod())
  5214. // This rule only applies to block-scope declarations.
  5215. return false;
  5216. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5217. if (PrevOuterContext->isRecord())
  5218. // We found a member function: ignore it.
  5219. return false;
  5220. // Find the innermost enclosing namespace for the new and
  5221. // previous declarations.
  5222. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5223. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5224. // The previous declaration is in a different namespace, so it
  5225. // isn't the same function.
  5226. if (!OuterContext->Equals(PrevOuterContext))
  5227. return false;
  5228. }
  5229. return true;
  5230. }
  5231. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5232. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5233. if (!SS.isSet()) return;
  5234. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5235. }
  5236. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5237. QualType type = decl->getType();
  5238. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5239. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5240. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5241. unsigned kind = -1U;
  5242. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5243. if (var->hasAttr<BlocksAttr>())
  5244. kind = 0; // __block
  5245. else if (!var->hasLocalStorage())
  5246. kind = 1; // global
  5247. } else if (isa<ObjCIvarDecl>(decl)) {
  5248. kind = 3; // ivar
  5249. } else if (isa<FieldDecl>(decl)) {
  5250. kind = 2; // field
  5251. }
  5252. if (kind != -1U) {
  5253. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5254. << kind;
  5255. }
  5256. } else if (lifetime == Qualifiers::OCL_None) {
  5257. // Try to infer lifetime.
  5258. if (!type->isObjCLifetimeType())
  5259. return false;
  5260. lifetime = type->getObjCARCImplicitLifetime();
  5261. type = Context.getLifetimeQualifiedType(type, lifetime);
  5262. decl->setType(type);
  5263. }
  5264. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5265. // Thread-local variables cannot have lifetime.
  5266. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5267. var->getTLSKind()) {
  5268. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5269. << var->getType();
  5270. return true;
  5271. }
  5272. }
  5273. return false;
  5274. }
  5275. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5276. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5277. // the wrong linkage.
  5278. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5279. // 'weak' only applies to declarations with external linkage.
  5280. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5281. if (!ND.isExternallyVisible()) {
  5282. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5283. ND.dropAttr<WeakAttr>();
  5284. }
  5285. }
  5286. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5287. if (ND.isExternallyVisible()) {
  5288. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5289. ND.dropAttr<WeakRefAttr>();
  5290. ND.dropAttr<AliasAttr>();
  5291. }
  5292. }
  5293. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5294. if (VD->hasInit()) {
  5295. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5296. assert(VD->isThisDeclarationADefinition() &&
  5297. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5298. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5299. VD->dropAttr<AliasAttr>();
  5300. }
  5301. }
  5302. }
  5303. // 'selectany' only applies to externally visible variable declarations.
  5304. // It does not apply to functions.
  5305. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5306. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5307. S.Diag(Attr->getLocation(),
  5308. diag::err_attribute_selectany_non_extern_data);
  5309. ND.dropAttr<SelectAnyAttr>();
  5310. }
  5311. }
  5312. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5313. auto *VD = dyn_cast<VarDecl>(&ND);
  5314. bool IsAnonymousNS = false;
  5315. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5316. if (VD) {
  5317. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5318. while (NS && !IsAnonymousNS) {
  5319. IsAnonymousNS = NS->isAnonymousNamespace();
  5320. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5321. }
  5322. }
  5323. // dll attributes require external linkage. Static locals may have external
  5324. // linkage but still cannot be explicitly imported or exported.
  5325. // In Microsoft mode, a variable defined in anonymous namespace must have
  5326. // external linkage in order to be exported.
  5327. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5328. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5329. (!AnonNSInMicrosoftMode &&
  5330. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5331. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5332. << &ND << Attr;
  5333. ND.setInvalidDecl();
  5334. }
  5335. }
  5336. // Virtual functions cannot be marked as 'notail'.
  5337. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5338. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5339. if (MD->isVirtual()) {
  5340. S.Diag(ND.getLocation(),
  5341. diag::err_invalid_attribute_on_virtual_function)
  5342. << Attr;
  5343. ND.dropAttr<NotTailCalledAttr>();
  5344. }
  5345. // Check the attributes on the function type, if any.
  5346. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5347. // Don't declare this variable in the second operand of the for-statement;
  5348. // GCC miscompiles that by ending its lifetime before evaluating the
  5349. // third operand. See gcc.gnu.org/PR86769.
  5350. AttributedTypeLoc ATL;
  5351. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5352. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5353. TL = ATL.getModifiedLoc()) {
  5354. // The [[lifetimebound]] attribute can be applied to the implicit object
  5355. // parameter of a non-static member function (other than a ctor or dtor)
  5356. // by applying it to the function type.
  5357. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5358. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5359. if (!MD || MD->isStatic()) {
  5360. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5361. << !MD << A->getRange();
  5362. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5363. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5364. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5365. }
  5366. }
  5367. }
  5368. }
  5369. }
  5370. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5371. NamedDecl *NewDecl,
  5372. bool IsSpecialization,
  5373. bool IsDefinition) {
  5374. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5375. return;
  5376. bool IsTemplate = false;
  5377. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5378. OldDecl = OldTD->getTemplatedDecl();
  5379. IsTemplate = true;
  5380. if (!IsSpecialization)
  5381. IsDefinition = false;
  5382. }
  5383. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5384. NewDecl = NewTD->getTemplatedDecl();
  5385. IsTemplate = true;
  5386. }
  5387. if (!OldDecl || !NewDecl)
  5388. return;
  5389. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5390. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5391. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5392. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5393. // dllimport and dllexport are inheritable attributes so we have to exclude
  5394. // inherited attribute instances.
  5395. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5396. (NewExportAttr && !NewExportAttr->isInherited());
  5397. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5398. // the only exception being explicit specializations.
  5399. // Implicitly generated declarations are also excluded for now because there
  5400. // is no other way to switch these to use dllimport or dllexport.
  5401. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5402. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5403. // Allow with a warning for free functions and global variables.
  5404. bool JustWarn = false;
  5405. if (!OldDecl->isCXXClassMember()) {
  5406. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5407. if (VD && !VD->getDescribedVarTemplate())
  5408. JustWarn = true;
  5409. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5410. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5411. JustWarn = true;
  5412. }
  5413. // We cannot change a declaration that's been used because IR has already
  5414. // been emitted. Dllimported functions will still work though (modulo
  5415. // address equality) as they can use the thunk.
  5416. if (OldDecl->isUsed())
  5417. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5418. JustWarn = false;
  5419. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5420. : diag::err_attribute_dll_redeclaration;
  5421. S.Diag(NewDecl->getLocation(), DiagID)
  5422. << NewDecl
  5423. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5424. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5425. if (!JustWarn) {
  5426. NewDecl->setInvalidDecl();
  5427. return;
  5428. }
  5429. }
  5430. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5431. // exceptions being inline function definitions (except for function
  5432. // templates), local extern declarations, qualified friend declarations or
  5433. // special MSVC extension: in the last case, the declaration is treated as if
  5434. // it were marked dllexport.
  5435. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5436. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5437. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5438. // Ignore static data because out-of-line definitions are diagnosed
  5439. // separately.
  5440. IsStaticDataMember = VD->isStaticDataMember();
  5441. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5442. VarDecl::DeclarationOnly;
  5443. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5444. IsInline = FD->isInlined();
  5445. IsQualifiedFriend = FD->getQualifier() &&
  5446. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5447. }
  5448. if (OldImportAttr && !HasNewAttr &&
  5449. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5450. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5451. if (IsMicrosoft && IsDefinition) {
  5452. S.Diag(NewDecl->getLocation(),
  5453. diag::warn_redeclaration_without_import_attribute)
  5454. << NewDecl;
  5455. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5456. NewDecl->dropAttr<DLLImportAttr>();
  5457. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5458. NewImportAttr->getRange(), S.Context,
  5459. NewImportAttr->getSpellingListIndex()));
  5460. } else {
  5461. S.Diag(NewDecl->getLocation(),
  5462. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5463. << NewDecl << OldImportAttr;
  5464. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5465. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5466. OldDecl->dropAttr<DLLImportAttr>();
  5467. NewDecl->dropAttr<DLLImportAttr>();
  5468. }
  5469. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5470. // In MinGW, seeing a function declared inline drops the dllimport
  5471. // attribute.
  5472. OldDecl->dropAttr<DLLImportAttr>();
  5473. NewDecl->dropAttr<DLLImportAttr>();
  5474. S.Diag(NewDecl->getLocation(),
  5475. diag::warn_dllimport_dropped_from_inline_function)
  5476. << NewDecl << OldImportAttr;
  5477. }
  5478. // A specialization of a class template member function is processed here
  5479. // since it's a redeclaration. If the parent class is dllexport, the
  5480. // specialization inherits that attribute. This doesn't happen automatically
  5481. // since the parent class isn't instantiated until later.
  5482. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5483. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5484. !NewImportAttr && !NewExportAttr) {
  5485. if (const DLLExportAttr *ParentExportAttr =
  5486. MD->getParent()->getAttr<DLLExportAttr>()) {
  5487. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5488. NewAttr->setInherited(true);
  5489. NewDecl->addAttr(NewAttr);
  5490. }
  5491. }
  5492. }
  5493. }
  5494. /// Given that we are within the definition of the given function,
  5495. /// will that definition behave like C99's 'inline', where the
  5496. /// definition is discarded except for optimization purposes?
  5497. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5498. // Try to avoid calling GetGVALinkageForFunction.
  5499. // All cases of this require the 'inline' keyword.
  5500. if (!FD->isInlined()) return false;
  5501. // This is only possible in C++ with the gnu_inline attribute.
  5502. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5503. return false;
  5504. // Okay, go ahead and call the relatively-more-expensive function.
  5505. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5506. }
  5507. /// Determine whether a variable is extern "C" prior to attaching
  5508. /// an initializer. We can't just call isExternC() here, because that
  5509. /// will also compute and cache whether the declaration is externally
  5510. /// visible, which might change when we attach the initializer.
  5511. ///
  5512. /// This can only be used if the declaration is known to not be a
  5513. /// redeclaration of an internal linkage declaration.
  5514. ///
  5515. /// For instance:
  5516. ///
  5517. /// auto x = []{};
  5518. ///
  5519. /// Attaching the initializer here makes this declaration not externally
  5520. /// visible, because its type has internal linkage.
  5521. ///
  5522. /// FIXME: This is a hack.
  5523. template<typename T>
  5524. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5525. if (S.getLangOpts().CPlusPlus) {
  5526. // In C++, the overloadable attribute negates the effects of extern "C".
  5527. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5528. return false;
  5529. // So do CUDA's host/device attributes.
  5530. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5531. D->template hasAttr<CUDAHostAttr>()))
  5532. return false;
  5533. }
  5534. return D->isExternC();
  5535. }
  5536. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5537. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5538. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5539. isa<OMPDeclareMapperDecl>(DC))
  5540. return VD->hasExternalStorage();
  5541. if (DC->isFileContext())
  5542. return true;
  5543. if (DC->isRecord())
  5544. return false;
  5545. llvm_unreachable("Unexpected context");
  5546. }
  5547. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5548. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5549. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5550. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5551. return true;
  5552. if (DC->isRecord())
  5553. return false;
  5554. llvm_unreachable("Unexpected context");
  5555. }
  5556. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5557. ParsedAttr::Kind Kind) {
  5558. // Check decl attributes on the DeclSpec.
  5559. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5560. return true;
  5561. // Walk the declarator structure, checking decl attributes that were in a type
  5562. // position to the decl itself.
  5563. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5564. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5565. return true;
  5566. }
  5567. // Finally, check attributes on the decl itself.
  5568. return PD.getAttributes().hasAttribute(Kind);
  5569. }
  5570. /// Adjust the \c DeclContext for a function or variable that might be a
  5571. /// function-local external declaration.
  5572. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5573. if (!DC->isFunctionOrMethod())
  5574. return false;
  5575. // If this is a local extern function or variable declared within a function
  5576. // template, don't add it into the enclosing namespace scope until it is
  5577. // instantiated; it might have a dependent type right now.
  5578. if (DC->isDependentContext())
  5579. return true;
  5580. // C++11 [basic.link]p7:
  5581. // When a block scope declaration of an entity with linkage is not found to
  5582. // refer to some other declaration, then that entity is a member of the
  5583. // innermost enclosing namespace.
  5584. //
  5585. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5586. // semantically-enclosing namespace, not a lexically-enclosing one.
  5587. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5588. DC = DC->getParent();
  5589. return true;
  5590. }
  5591. /// Returns true if given declaration has external C language linkage.
  5592. static bool isDeclExternC(const Decl *D) {
  5593. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5594. return FD->isExternC();
  5595. if (const auto *VD = dyn_cast<VarDecl>(D))
  5596. return VD->isExternC();
  5597. llvm_unreachable("Unknown type of decl!");
  5598. }
  5599. NamedDecl *Sema::ActOnVariableDeclarator(
  5600. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5601. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5602. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5603. QualType R = TInfo->getType();
  5604. DeclarationName Name = GetNameForDeclarator(D).getName();
  5605. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5606. if (D.isDecompositionDeclarator()) {
  5607. // Take the name of the first declarator as our name for diagnostic
  5608. // purposes.
  5609. auto &Decomp = D.getDecompositionDeclarator();
  5610. if (!Decomp.bindings().empty()) {
  5611. II = Decomp.bindings()[0].Name;
  5612. Name = II;
  5613. }
  5614. } else if (!II) {
  5615. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5616. return nullptr;
  5617. }
  5618. if (getLangOpts().OpenCL) {
  5619. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5620. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5621. // argument.
  5622. if (R->isImageType() || R->isPipeType()) {
  5623. Diag(D.getIdentifierLoc(),
  5624. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5625. << R;
  5626. D.setInvalidType();
  5627. return nullptr;
  5628. }
  5629. // OpenCL v1.2 s6.9.r:
  5630. // The event type cannot be used to declare a program scope variable.
  5631. // OpenCL v2.0 s6.9.q:
  5632. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5633. if (NULL == S->getParent()) {
  5634. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5635. Diag(D.getIdentifierLoc(),
  5636. diag::err_invalid_type_for_program_scope_var) << R;
  5637. D.setInvalidType();
  5638. return nullptr;
  5639. }
  5640. }
  5641. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5642. QualType NR = R;
  5643. while (NR->isPointerType()) {
  5644. if (NR->isFunctionPointerType()) {
  5645. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5646. D.setInvalidType();
  5647. break;
  5648. }
  5649. NR = NR->getPointeeType();
  5650. }
  5651. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5652. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5653. // half array type (unless the cl_khr_fp16 extension is enabled).
  5654. if (Context.getBaseElementType(R)->isHalfType()) {
  5655. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5656. D.setInvalidType();
  5657. }
  5658. }
  5659. if (R->isSamplerT()) {
  5660. // OpenCL v1.2 s6.9.b p4:
  5661. // The sampler type cannot be used with the __local and __global address
  5662. // space qualifiers.
  5663. if (R.getAddressSpace() == LangAS::opencl_local ||
  5664. R.getAddressSpace() == LangAS::opencl_global) {
  5665. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5666. }
  5667. // OpenCL v1.2 s6.12.14.1:
  5668. // A global sampler must be declared with either the constant address
  5669. // space qualifier or with the const qualifier.
  5670. if (DC->isTranslationUnit() &&
  5671. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5672. R.isConstQualified())) {
  5673. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5674. D.setInvalidType();
  5675. }
  5676. }
  5677. // OpenCL v1.2 s6.9.r:
  5678. // The event type cannot be used with the __local, __constant and __global
  5679. // address space qualifiers.
  5680. if (R->isEventT()) {
  5681. if (R.getAddressSpace() != LangAS::opencl_private) {
  5682. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5683. D.setInvalidType();
  5684. }
  5685. }
  5686. // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
  5687. // supported. OpenCL C does not support thread_local either, and
  5688. // also reject all other thread storage class specifiers.
  5689. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5690. if (TSC != TSCS_unspecified) {
  5691. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5692. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5693. diag::err_opencl_unknown_type_specifier)
  5694. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5695. << DeclSpec::getSpecifierName(TSC) << 1;
  5696. D.setInvalidType();
  5697. return nullptr;
  5698. }
  5699. }
  5700. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5701. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5702. // dllimport globals without explicit storage class are treated as extern. We
  5703. // have to change the storage class this early to get the right DeclContext.
  5704. if (SC == SC_None && !DC->isRecord() &&
  5705. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5706. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5707. SC = SC_Extern;
  5708. DeclContext *OriginalDC = DC;
  5709. bool IsLocalExternDecl = SC == SC_Extern &&
  5710. adjustContextForLocalExternDecl(DC);
  5711. if (SCSpec == DeclSpec::SCS_mutable) {
  5712. // mutable can only appear on non-static class members, so it's always
  5713. // an error here
  5714. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5715. D.setInvalidType();
  5716. SC = SC_None;
  5717. }
  5718. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5719. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5720. D.getDeclSpec().getStorageClassSpecLoc())) {
  5721. // In C++11, the 'register' storage class specifier is deprecated.
  5722. // Suppress the warning in system macros, it's used in macros in some
  5723. // popular C system headers, such as in glibc's htonl() macro.
  5724. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5725. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5726. : diag::warn_deprecated_register)
  5727. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5728. }
  5729. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5730. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5731. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5732. // appear in the declaration specifiers in an external declaration.
  5733. // Global Register+Asm is a GNU extension we support.
  5734. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5735. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5736. D.setInvalidType();
  5737. }
  5738. }
  5739. bool IsMemberSpecialization = false;
  5740. bool IsVariableTemplateSpecialization = false;
  5741. bool IsPartialSpecialization = false;
  5742. bool IsVariableTemplate = false;
  5743. VarDecl *NewVD = nullptr;
  5744. VarTemplateDecl *NewTemplate = nullptr;
  5745. TemplateParameterList *TemplateParams = nullptr;
  5746. if (!getLangOpts().CPlusPlus) {
  5747. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5748. II, R, TInfo, SC);
  5749. if (R->getContainedDeducedType())
  5750. ParsingInitForAutoVars.insert(NewVD);
  5751. if (D.isInvalidType())
  5752. NewVD->setInvalidDecl();
  5753. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  5754. NewVD->hasLocalStorage())
  5755. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  5756. NTCUC_AutoVar, NTCUK_Destruct);
  5757. } else {
  5758. bool Invalid = false;
  5759. if (DC->isRecord() && !CurContext->isRecord()) {
  5760. // This is an out-of-line definition of a static data member.
  5761. switch (SC) {
  5762. case SC_None:
  5763. break;
  5764. case SC_Static:
  5765. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5766. diag::err_static_out_of_line)
  5767. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5768. break;
  5769. case SC_Auto:
  5770. case SC_Register:
  5771. case SC_Extern:
  5772. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5773. // to names of variables declared in a block or to function parameters.
  5774. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5775. // of class members
  5776. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5777. diag::err_storage_class_for_static_member)
  5778. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5779. break;
  5780. case SC_PrivateExtern:
  5781. llvm_unreachable("C storage class in c++!");
  5782. }
  5783. }
  5784. if (SC == SC_Static && CurContext->isRecord()) {
  5785. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5786. if (RD->isLocalClass())
  5787. Diag(D.getIdentifierLoc(),
  5788. diag::err_static_data_member_not_allowed_in_local_class)
  5789. << Name << RD->getDeclName();
  5790. // C++98 [class.union]p1: If a union contains a static data member,
  5791. // the program is ill-formed. C++11 drops this restriction.
  5792. if (RD->isUnion())
  5793. Diag(D.getIdentifierLoc(),
  5794. getLangOpts().CPlusPlus11
  5795. ? diag::warn_cxx98_compat_static_data_member_in_union
  5796. : diag::ext_static_data_member_in_union) << Name;
  5797. // We conservatively disallow static data members in anonymous structs.
  5798. else if (!RD->getDeclName())
  5799. Diag(D.getIdentifierLoc(),
  5800. diag::err_static_data_member_not_allowed_in_anon_struct)
  5801. << Name << RD->isUnion();
  5802. }
  5803. }
  5804. // Match up the template parameter lists with the scope specifier, then
  5805. // determine whether we have a template or a template specialization.
  5806. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5807. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5808. D.getCXXScopeSpec(),
  5809. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5810. ? D.getName().TemplateId
  5811. : nullptr,
  5812. TemplateParamLists,
  5813. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5814. if (TemplateParams) {
  5815. if (!TemplateParams->size() &&
  5816. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5817. // There is an extraneous 'template<>' for this variable. Complain
  5818. // about it, but allow the declaration of the variable.
  5819. Diag(TemplateParams->getTemplateLoc(),
  5820. diag::err_template_variable_noparams)
  5821. << II
  5822. << SourceRange(TemplateParams->getTemplateLoc(),
  5823. TemplateParams->getRAngleLoc());
  5824. TemplateParams = nullptr;
  5825. } else {
  5826. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5827. // This is an explicit specialization or a partial specialization.
  5828. // FIXME: Check that we can declare a specialization here.
  5829. IsVariableTemplateSpecialization = true;
  5830. IsPartialSpecialization = TemplateParams->size() > 0;
  5831. } else { // if (TemplateParams->size() > 0)
  5832. // This is a template declaration.
  5833. IsVariableTemplate = true;
  5834. // Check that we can declare a template here.
  5835. if (CheckTemplateDeclScope(S, TemplateParams))
  5836. return nullptr;
  5837. // Only C++1y supports variable templates (N3651).
  5838. Diag(D.getIdentifierLoc(),
  5839. getLangOpts().CPlusPlus14
  5840. ? diag::warn_cxx11_compat_variable_template
  5841. : diag::ext_variable_template);
  5842. }
  5843. }
  5844. } else {
  5845. assert((Invalid ||
  5846. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5847. "should have a 'template<>' for this decl");
  5848. }
  5849. if (IsVariableTemplateSpecialization) {
  5850. SourceLocation TemplateKWLoc =
  5851. TemplateParamLists.size() > 0
  5852. ? TemplateParamLists[0]->getTemplateLoc()
  5853. : SourceLocation();
  5854. DeclResult Res = ActOnVarTemplateSpecialization(
  5855. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5856. IsPartialSpecialization);
  5857. if (Res.isInvalid())
  5858. return nullptr;
  5859. NewVD = cast<VarDecl>(Res.get());
  5860. AddToScope = false;
  5861. } else if (D.isDecompositionDeclarator()) {
  5862. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5863. D.getIdentifierLoc(), R, TInfo, SC,
  5864. Bindings);
  5865. } else
  5866. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5867. D.getIdentifierLoc(), II, R, TInfo, SC);
  5868. // If this is supposed to be a variable template, create it as such.
  5869. if (IsVariableTemplate) {
  5870. NewTemplate =
  5871. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5872. TemplateParams, NewVD);
  5873. NewVD->setDescribedVarTemplate(NewTemplate);
  5874. }
  5875. // If this decl has an auto type in need of deduction, make a note of the
  5876. // Decl so we can diagnose uses of it in its own initializer.
  5877. if (R->getContainedDeducedType())
  5878. ParsingInitForAutoVars.insert(NewVD);
  5879. if (D.isInvalidType() || Invalid) {
  5880. NewVD->setInvalidDecl();
  5881. if (NewTemplate)
  5882. NewTemplate->setInvalidDecl();
  5883. }
  5884. SetNestedNameSpecifier(*this, NewVD, D);
  5885. // If we have any template parameter lists that don't directly belong to
  5886. // the variable (matching the scope specifier), store them.
  5887. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5888. if (TemplateParamLists.size() > VDTemplateParamLists)
  5889. NewVD->setTemplateParameterListsInfo(
  5890. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5891. if (D.getDeclSpec().hasConstexprSpecifier()) {
  5892. NewVD->setConstexpr(true);
  5893. // C++1z [dcl.spec.constexpr]p1:
  5894. // A static data member declared with the constexpr specifier is
  5895. // implicitly an inline variable.
  5896. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  5897. NewVD->setImplicitlyInline();
  5898. if (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval)
  5899. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  5900. diag::err_constexpr_wrong_decl_kind)
  5901. << /*consteval*/ 1;
  5902. }
  5903. }
  5904. if (D.getDeclSpec().isInlineSpecified()) {
  5905. if (!getLangOpts().CPlusPlus) {
  5906. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5907. << 0;
  5908. } else if (CurContext->isFunctionOrMethod()) {
  5909. // 'inline' is not allowed on block scope variable declaration.
  5910. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5911. diag::err_inline_declaration_block_scope) << Name
  5912. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5913. } else {
  5914. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5915. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5916. : diag::ext_inline_variable);
  5917. NewVD->setInlineSpecified();
  5918. }
  5919. }
  5920. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5921. // lexical context will be different from the semantic context.
  5922. NewVD->setLexicalDeclContext(CurContext);
  5923. if (NewTemplate)
  5924. NewTemplate->setLexicalDeclContext(CurContext);
  5925. if (IsLocalExternDecl) {
  5926. if (D.isDecompositionDeclarator())
  5927. for (auto *B : Bindings)
  5928. B->setLocalExternDecl();
  5929. else
  5930. NewVD->setLocalExternDecl();
  5931. }
  5932. bool EmitTLSUnsupportedError = false;
  5933. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5934. // C++11 [dcl.stc]p4:
  5935. // When thread_local is applied to a variable of block scope the
  5936. // storage-class-specifier static is implied if it does not appear
  5937. // explicitly.
  5938. // Core issue: 'static' is not implied if the variable is declared
  5939. // 'extern'.
  5940. if (NewVD->hasLocalStorage() &&
  5941. (SCSpec != DeclSpec::SCS_unspecified ||
  5942. TSCS != DeclSpec::TSCS_thread_local ||
  5943. !DC->isFunctionOrMethod()))
  5944. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5945. diag::err_thread_non_global)
  5946. << DeclSpec::getSpecifierName(TSCS);
  5947. else if (!Context.getTargetInfo().isTLSSupported()) {
  5948. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5949. // Postpone error emission until we've collected attributes required to
  5950. // figure out whether it's a host or device variable and whether the
  5951. // error should be ignored.
  5952. EmitTLSUnsupportedError = true;
  5953. // We still need to mark the variable as TLS so it shows up in AST with
  5954. // proper storage class for other tools to use even if we're not going
  5955. // to emit any code for it.
  5956. NewVD->setTSCSpec(TSCS);
  5957. } else
  5958. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5959. diag::err_thread_unsupported);
  5960. } else
  5961. NewVD->setTSCSpec(TSCS);
  5962. }
  5963. // C99 6.7.4p3
  5964. // An inline definition of a function with external linkage shall
  5965. // not contain a definition of a modifiable object with static or
  5966. // thread storage duration...
  5967. // We only apply this when the function is required to be defined
  5968. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5969. // that a local variable with thread storage duration still has to
  5970. // be marked 'static'. Also note that it's possible to get these
  5971. // semantics in C++ using __attribute__((gnu_inline)).
  5972. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5973. !NewVD->getType().isConstQualified()) {
  5974. FunctionDecl *CurFD = getCurFunctionDecl();
  5975. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5976. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5977. diag::warn_static_local_in_extern_inline);
  5978. MaybeSuggestAddingStaticToDecl(CurFD);
  5979. }
  5980. }
  5981. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5982. if (IsVariableTemplateSpecialization)
  5983. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5984. << (IsPartialSpecialization ? 1 : 0)
  5985. << FixItHint::CreateRemoval(
  5986. D.getDeclSpec().getModulePrivateSpecLoc());
  5987. else if (IsMemberSpecialization)
  5988. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5989. << 2
  5990. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5991. else if (NewVD->hasLocalStorage())
  5992. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5993. << 0 << NewVD->getDeclName()
  5994. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5995. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5996. else {
  5997. NewVD->setModulePrivate();
  5998. if (NewTemplate)
  5999. NewTemplate->setModulePrivate();
  6000. for (auto *B : Bindings)
  6001. B->setModulePrivate();
  6002. }
  6003. }
  6004. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6005. ProcessDeclAttributes(S, NewVD, D);
  6006. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6007. if (EmitTLSUnsupportedError &&
  6008. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6009. (getLangOpts().OpenMPIsDevice &&
  6010. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  6011. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6012. diag::err_thread_unsupported);
  6013. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6014. // storage [duration]."
  6015. if (SC == SC_None && S->getFnParent() != nullptr &&
  6016. (NewVD->hasAttr<CUDASharedAttr>() ||
  6017. NewVD->hasAttr<CUDAConstantAttr>())) {
  6018. NewVD->setStorageClass(SC_Static);
  6019. }
  6020. }
  6021. // Ensure that dllimport globals without explicit storage class are treated as
  6022. // extern. The storage class is set above using parsed attributes. Now we can
  6023. // check the VarDecl itself.
  6024. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6025. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6026. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6027. // In auto-retain/release, infer strong retension for variables of
  6028. // retainable type.
  6029. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6030. NewVD->setInvalidDecl();
  6031. // Handle GNU asm-label extension (encoded as an attribute).
  6032. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6033. // The parser guarantees this is a string.
  6034. StringLiteral *SE = cast<StringLiteral>(E);
  6035. StringRef Label = SE->getString();
  6036. if (S->getFnParent() != nullptr) {
  6037. switch (SC) {
  6038. case SC_None:
  6039. case SC_Auto:
  6040. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6041. break;
  6042. case SC_Register:
  6043. // Local Named register
  6044. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6045. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6046. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6047. break;
  6048. case SC_Static:
  6049. case SC_Extern:
  6050. case SC_PrivateExtern:
  6051. break;
  6052. }
  6053. } else if (SC == SC_Register) {
  6054. // Global Named register
  6055. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6056. const auto &TI = Context.getTargetInfo();
  6057. bool HasSizeMismatch;
  6058. if (!TI.isValidGCCRegisterName(Label))
  6059. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6060. else if (!TI.validateGlobalRegisterVariable(Label,
  6061. Context.getTypeSize(R),
  6062. HasSizeMismatch))
  6063. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6064. else if (HasSizeMismatch)
  6065. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6066. }
  6067. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6068. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6069. NewVD->setInvalidDecl(true);
  6070. }
  6071. }
  6072. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6073. Context, Label, 0));
  6074. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6075. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6076. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6077. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6078. if (isDeclExternC(NewVD)) {
  6079. NewVD->addAttr(I->second);
  6080. ExtnameUndeclaredIdentifiers.erase(I);
  6081. } else
  6082. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6083. << /*Variable*/1 << NewVD;
  6084. }
  6085. }
  6086. // Find the shadowed declaration before filtering for scope.
  6087. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6088. ? getShadowedDeclaration(NewVD, Previous)
  6089. : nullptr;
  6090. // Don't consider existing declarations that are in a different
  6091. // scope and are out-of-semantic-context declarations (if the new
  6092. // declaration has linkage).
  6093. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6094. D.getCXXScopeSpec().isNotEmpty() ||
  6095. IsMemberSpecialization ||
  6096. IsVariableTemplateSpecialization);
  6097. // Check whether the previous declaration is in the same block scope. This
  6098. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6099. if (getLangOpts().CPlusPlus &&
  6100. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6101. NewVD->setPreviousDeclInSameBlockScope(
  6102. Previous.isSingleResult() && !Previous.isShadowed() &&
  6103. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6104. if (!getLangOpts().CPlusPlus) {
  6105. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6106. } else {
  6107. // If this is an explicit specialization of a static data member, check it.
  6108. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6109. CheckMemberSpecialization(NewVD, Previous))
  6110. NewVD->setInvalidDecl();
  6111. // Merge the decl with the existing one if appropriate.
  6112. if (!Previous.empty()) {
  6113. if (Previous.isSingleResult() &&
  6114. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6115. D.getCXXScopeSpec().isSet()) {
  6116. // The user tried to define a non-static data member
  6117. // out-of-line (C++ [dcl.meaning]p1).
  6118. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6119. << D.getCXXScopeSpec().getRange();
  6120. Previous.clear();
  6121. NewVD->setInvalidDecl();
  6122. }
  6123. } else if (D.getCXXScopeSpec().isSet()) {
  6124. // No previous declaration in the qualifying scope.
  6125. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6126. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6127. << D.getCXXScopeSpec().getRange();
  6128. NewVD->setInvalidDecl();
  6129. }
  6130. if (!IsVariableTemplateSpecialization)
  6131. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6132. if (NewTemplate) {
  6133. VarTemplateDecl *PrevVarTemplate =
  6134. NewVD->getPreviousDecl()
  6135. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6136. : nullptr;
  6137. // Check the template parameter list of this declaration, possibly
  6138. // merging in the template parameter list from the previous variable
  6139. // template declaration.
  6140. if (CheckTemplateParameterList(
  6141. TemplateParams,
  6142. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6143. : nullptr,
  6144. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6145. DC->isDependentContext())
  6146. ? TPC_ClassTemplateMember
  6147. : TPC_VarTemplate))
  6148. NewVD->setInvalidDecl();
  6149. // If we are providing an explicit specialization of a static variable
  6150. // template, make a note of that.
  6151. if (PrevVarTemplate &&
  6152. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6153. PrevVarTemplate->setMemberSpecialization();
  6154. }
  6155. }
  6156. // Diagnose shadowed variables iff this isn't a redeclaration.
  6157. if (ShadowedDecl && !D.isRedeclaration())
  6158. CheckShadow(NewVD, ShadowedDecl, Previous);
  6159. ProcessPragmaWeak(S, NewVD);
  6160. // If this is the first declaration of an extern C variable, update
  6161. // the map of such variables.
  6162. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6163. isIncompleteDeclExternC(*this, NewVD))
  6164. RegisterLocallyScopedExternCDecl(NewVD, S);
  6165. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6166. Decl *ManglingContextDecl;
  6167. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6168. NewVD->getDeclContext(), ManglingContextDecl)) {
  6169. Context.setManglingNumber(
  6170. NewVD, MCtx->getManglingNumber(
  6171. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6172. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6173. }
  6174. }
  6175. // Special handling of variable named 'main'.
  6176. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6177. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6178. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6179. // C++ [basic.start.main]p3
  6180. // A program that declares a variable main at global scope is ill-formed.
  6181. if (getLangOpts().CPlusPlus)
  6182. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6183. // In C, and external-linkage variable named main results in undefined
  6184. // behavior.
  6185. else if (NewVD->hasExternalFormalLinkage())
  6186. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6187. }
  6188. if (D.isRedeclaration() && !Previous.empty()) {
  6189. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6190. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6191. D.isFunctionDefinition());
  6192. }
  6193. if (NewTemplate) {
  6194. if (NewVD->isInvalidDecl())
  6195. NewTemplate->setInvalidDecl();
  6196. ActOnDocumentableDecl(NewTemplate);
  6197. return NewTemplate;
  6198. }
  6199. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6200. CompleteMemberSpecialization(NewVD, Previous);
  6201. return NewVD;
  6202. }
  6203. /// Enum describing the %select options in diag::warn_decl_shadow.
  6204. enum ShadowedDeclKind {
  6205. SDK_Local,
  6206. SDK_Global,
  6207. SDK_StaticMember,
  6208. SDK_Field,
  6209. SDK_Typedef,
  6210. SDK_Using
  6211. };
  6212. /// Determine what kind of declaration we're shadowing.
  6213. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6214. const DeclContext *OldDC) {
  6215. if (isa<TypeAliasDecl>(ShadowedDecl))
  6216. return SDK_Using;
  6217. else if (isa<TypedefDecl>(ShadowedDecl))
  6218. return SDK_Typedef;
  6219. else if (isa<RecordDecl>(OldDC))
  6220. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6221. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6222. }
  6223. /// Return the location of the capture if the given lambda captures the given
  6224. /// variable \p VD, or an invalid source location otherwise.
  6225. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6226. const VarDecl *VD) {
  6227. for (const Capture &Capture : LSI->Captures) {
  6228. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6229. return Capture.getLocation();
  6230. }
  6231. return SourceLocation();
  6232. }
  6233. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6234. const LookupResult &R) {
  6235. // Only diagnose if we're shadowing an unambiguous field or variable.
  6236. if (R.getResultKind() != LookupResult::Found)
  6237. return false;
  6238. // Return false if warning is ignored.
  6239. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6240. }
  6241. /// Return the declaration shadowed by the given variable \p D, or null
  6242. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6243. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6244. const LookupResult &R) {
  6245. if (!shouldWarnIfShadowedDecl(Diags, R))
  6246. return nullptr;
  6247. // Don't diagnose declarations at file scope.
  6248. if (D->hasGlobalStorage())
  6249. return nullptr;
  6250. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6251. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6252. ? ShadowedDecl
  6253. : nullptr;
  6254. }
  6255. /// Return the declaration shadowed by the given typedef \p D, or null
  6256. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6257. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6258. const LookupResult &R) {
  6259. // Don't warn if typedef declaration is part of a class
  6260. if (D->getDeclContext()->isRecord())
  6261. return nullptr;
  6262. if (!shouldWarnIfShadowedDecl(Diags, R))
  6263. return nullptr;
  6264. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6265. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6266. }
  6267. /// Diagnose variable or built-in function shadowing. Implements
  6268. /// -Wshadow.
  6269. ///
  6270. /// This method is called whenever a VarDecl is added to a "useful"
  6271. /// scope.
  6272. ///
  6273. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6274. /// \param R the lookup of the name
  6275. ///
  6276. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6277. const LookupResult &R) {
  6278. DeclContext *NewDC = D->getDeclContext();
  6279. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6280. // Fields are not shadowed by variables in C++ static methods.
  6281. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6282. if (MD->isStatic())
  6283. return;
  6284. // Fields shadowed by constructor parameters are a special case. Usually
  6285. // the constructor initializes the field with the parameter.
  6286. if (isa<CXXConstructorDecl>(NewDC))
  6287. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6288. // Remember that this was shadowed so we can either warn about its
  6289. // modification or its existence depending on warning settings.
  6290. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6291. return;
  6292. }
  6293. }
  6294. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6295. if (shadowedVar->isExternC()) {
  6296. // For shadowing external vars, make sure that we point to the global
  6297. // declaration, not a locally scoped extern declaration.
  6298. for (auto I : shadowedVar->redecls())
  6299. if (I->isFileVarDecl()) {
  6300. ShadowedDecl = I;
  6301. break;
  6302. }
  6303. }
  6304. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6305. unsigned WarningDiag = diag::warn_decl_shadow;
  6306. SourceLocation CaptureLoc;
  6307. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6308. isa<CXXMethodDecl>(NewDC)) {
  6309. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6310. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6311. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6312. // Try to avoid warnings for lambdas with an explicit capture list.
  6313. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6314. // Warn only when the lambda captures the shadowed decl explicitly.
  6315. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6316. if (CaptureLoc.isInvalid())
  6317. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6318. } else {
  6319. // Remember that this was shadowed so we can avoid the warning if the
  6320. // shadowed decl isn't captured and the warning settings allow it.
  6321. cast<LambdaScopeInfo>(getCurFunction())
  6322. ->ShadowingDecls.push_back(
  6323. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6324. return;
  6325. }
  6326. }
  6327. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6328. // A variable can't shadow a local variable in an enclosing scope, if
  6329. // they are separated by a non-capturing declaration context.
  6330. for (DeclContext *ParentDC = NewDC;
  6331. ParentDC && !ParentDC->Equals(OldDC);
  6332. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6333. // Only block literals, captured statements, and lambda expressions
  6334. // can capture; other scopes don't.
  6335. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6336. !isLambdaCallOperator(ParentDC)) {
  6337. return;
  6338. }
  6339. }
  6340. }
  6341. }
  6342. }
  6343. // Only warn about certain kinds of shadowing for class members.
  6344. if (NewDC && NewDC->isRecord()) {
  6345. // In particular, don't warn about shadowing non-class members.
  6346. if (!OldDC->isRecord())
  6347. return;
  6348. // TODO: should we warn about static data members shadowing
  6349. // static data members from base classes?
  6350. // TODO: don't diagnose for inaccessible shadowed members.
  6351. // This is hard to do perfectly because we might friend the
  6352. // shadowing context, but that's just a false negative.
  6353. }
  6354. DeclarationName Name = R.getLookupName();
  6355. // Emit warning and note.
  6356. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6357. return;
  6358. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6359. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6360. if (!CaptureLoc.isInvalid())
  6361. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6362. << Name << /*explicitly*/ 1;
  6363. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6364. }
  6365. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6366. /// when these variables are captured by the lambda.
  6367. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6368. for (const auto &Shadow : LSI->ShadowingDecls) {
  6369. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6370. // Try to avoid the warning when the shadowed decl isn't captured.
  6371. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6372. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6373. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6374. ? diag::warn_decl_shadow_uncaptured_local
  6375. : diag::warn_decl_shadow)
  6376. << Shadow.VD->getDeclName()
  6377. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6378. if (!CaptureLoc.isInvalid())
  6379. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6380. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6381. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6382. }
  6383. }
  6384. /// Check -Wshadow without the advantage of a previous lookup.
  6385. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6386. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6387. return;
  6388. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6389. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6390. LookupName(R, S);
  6391. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6392. CheckShadow(D, ShadowedDecl, R);
  6393. }
  6394. /// Check if 'E', which is an expression that is about to be modified, refers
  6395. /// to a constructor parameter that shadows a field.
  6396. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6397. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6398. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6399. return;
  6400. E = E->IgnoreParenImpCasts();
  6401. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6402. if (!DRE)
  6403. return;
  6404. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6405. auto I = ShadowingDecls.find(D);
  6406. if (I == ShadowingDecls.end())
  6407. return;
  6408. const NamedDecl *ShadowedDecl = I->second;
  6409. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6410. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6411. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6412. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6413. // Avoid issuing multiple warnings about the same decl.
  6414. ShadowingDecls.erase(I);
  6415. }
  6416. /// Check for conflict between this global or extern "C" declaration and
  6417. /// previous global or extern "C" declarations. This is only used in C++.
  6418. template<typename T>
  6419. static bool checkGlobalOrExternCConflict(
  6420. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6421. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6422. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6423. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6424. // The common case: this global doesn't conflict with any extern "C"
  6425. // declaration.
  6426. return false;
  6427. }
  6428. if (Prev) {
  6429. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6430. // Both the old and new declarations have C language linkage. This is a
  6431. // redeclaration.
  6432. Previous.clear();
  6433. Previous.addDecl(Prev);
  6434. return true;
  6435. }
  6436. // This is a global, non-extern "C" declaration, and there is a previous
  6437. // non-global extern "C" declaration. Diagnose if this is a variable
  6438. // declaration.
  6439. if (!isa<VarDecl>(ND))
  6440. return false;
  6441. } else {
  6442. // The declaration is extern "C". Check for any declaration in the
  6443. // translation unit which might conflict.
  6444. if (IsGlobal) {
  6445. // We have already performed the lookup into the translation unit.
  6446. IsGlobal = false;
  6447. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6448. I != E; ++I) {
  6449. if (isa<VarDecl>(*I)) {
  6450. Prev = *I;
  6451. break;
  6452. }
  6453. }
  6454. } else {
  6455. DeclContext::lookup_result R =
  6456. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6457. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6458. I != E; ++I) {
  6459. if (isa<VarDecl>(*I)) {
  6460. Prev = *I;
  6461. break;
  6462. }
  6463. // FIXME: If we have any other entity with this name in global scope,
  6464. // the declaration is ill-formed, but that is a defect: it breaks the
  6465. // 'stat' hack, for instance. Only variables can have mangled name
  6466. // clashes with extern "C" declarations, so only they deserve a
  6467. // diagnostic.
  6468. }
  6469. }
  6470. if (!Prev)
  6471. return false;
  6472. }
  6473. // Use the first declaration's location to ensure we point at something which
  6474. // is lexically inside an extern "C" linkage-spec.
  6475. assert(Prev && "should have found a previous declaration to diagnose");
  6476. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6477. Prev = FD->getFirstDecl();
  6478. else
  6479. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6480. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6481. << IsGlobal << ND;
  6482. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6483. << IsGlobal;
  6484. return false;
  6485. }
  6486. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6487. /// if we have found that this is a redeclaration of some prior entity.
  6488. ///
  6489. /// Per C++ [dcl.link]p6:
  6490. /// Two declarations [for a function or variable] with C language linkage
  6491. /// with the same name that appear in different scopes refer to the same
  6492. /// [entity]. An entity with C language linkage shall not be declared with
  6493. /// the same name as an entity in global scope.
  6494. template<typename T>
  6495. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6496. LookupResult &Previous) {
  6497. if (!S.getLangOpts().CPlusPlus) {
  6498. // In C, when declaring a global variable, look for a corresponding 'extern'
  6499. // variable declared in function scope. We don't need this in C++, because
  6500. // we find local extern decls in the surrounding file-scope DeclContext.
  6501. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6502. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6503. Previous.clear();
  6504. Previous.addDecl(Prev);
  6505. return true;
  6506. }
  6507. }
  6508. return false;
  6509. }
  6510. // A declaration in the translation unit can conflict with an extern "C"
  6511. // declaration.
  6512. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6513. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6514. // An extern "C" declaration can conflict with a declaration in the
  6515. // translation unit or can be a redeclaration of an extern "C" declaration
  6516. // in another scope.
  6517. if (isIncompleteDeclExternC(S,ND))
  6518. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6519. // Neither global nor extern "C": nothing to do.
  6520. return false;
  6521. }
  6522. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6523. // If the decl is already known invalid, don't check it.
  6524. if (NewVD->isInvalidDecl())
  6525. return;
  6526. QualType T = NewVD->getType();
  6527. // Defer checking an 'auto' type until its initializer is attached.
  6528. if (T->isUndeducedType())
  6529. return;
  6530. if (NewVD->hasAttrs())
  6531. CheckAlignasUnderalignment(NewVD);
  6532. if (T->isObjCObjectType()) {
  6533. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6534. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6535. T = Context.getObjCObjectPointerType(T);
  6536. NewVD->setType(T);
  6537. }
  6538. // Emit an error if an address space was applied to decl with local storage.
  6539. // This includes arrays of objects with address space qualifiers, but not
  6540. // automatic variables that point to other address spaces.
  6541. // ISO/IEC TR 18037 S5.1.2
  6542. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6543. T.getAddressSpace() != LangAS::Default) {
  6544. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6545. NewVD->setInvalidDecl();
  6546. return;
  6547. }
  6548. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6549. // scope.
  6550. if (getLangOpts().OpenCLVersion == 120 &&
  6551. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6552. NewVD->isStaticLocal()) {
  6553. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6554. NewVD->setInvalidDecl();
  6555. return;
  6556. }
  6557. if (getLangOpts().OpenCL) {
  6558. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6559. if (NewVD->hasAttr<BlocksAttr>()) {
  6560. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6561. return;
  6562. }
  6563. if (T->isBlockPointerType()) {
  6564. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6565. // can't use 'extern' storage class.
  6566. if (!T.isConstQualified()) {
  6567. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6568. << 0 /*const*/;
  6569. NewVD->setInvalidDecl();
  6570. return;
  6571. }
  6572. if (NewVD->hasExternalStorage()) {
  6573. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6574. NewVD->setInvalidDecl();
  6575. return;
  6576. }
  6577. }
  6578. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6579. // __constant address space.
  6580. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6581. // variables inside a function can also be declared in the global
  6582. // address space.
  6583. // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
  6584. // address space additionally.
  6585. // FIXME: Add local AS for OpenCL C++.
  6586. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6587. NewVD->hasExternalStorage()) {
  6588. if (!T->isSamplerT() &&
  6589. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6590. (T.getAddressSpace() == LangAS::opencl_global &&
  6591. (getLangOpts().OpenCLVersion == 200 ||
  6592. getLangOpts().OpenCLCPlusPlus)))) {
  6593. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6594. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6595. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6596. << Scope << "global or constant";
  6597. else
  6598. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6599. << Scope << "constant";
  6600. NewVD->setInvalidDecl();
  6601. return;
  6602. }
  6603. } else {
  6604. if (T.getAddressSpace() == LangAS::opencl_global) {
  6605. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6606. << 1 /*is any function*/ << "global";
  6607. NewVD->setInvalidDecl();
  6608. return;
  6609. }
  6610. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6611. T.getAddressSpace() == LangAS::opencl_local) {
  6612. FunctionDecl *FD = getCurFunctionDecl();
  6613. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6614. // in functions.
  6615. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6616. if (T.getAddressSpace() == LangAS::opencl_constant)
  6617. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6618. << 0 /*non-kernel only*/ << "constant";
  6619. else
  6620. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6621. << 0 /*non-kernel only*/ << "local";
  6622. NewVD->setInvalidDecl();
  6623. return;
  6624. }
  6625. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6626. // in the outermost scope of a kernel function.
  6627. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6628. if (!getCurScope()->isFunctionScope()) {
  6629. if (T.getAddressSpace() == LangAS::opencl_constant)
  6630. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6631. << "constant";
  6632. else
  6633. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6634. << "local";
  6635. NewVD->setInvalidDecl();
  6636. return;
  6637. }
  6638. }
  6639. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  6640. // If we are parsing a template we didn't deduce an addr
  6641. // space yet.
  6642. T.getAddressSpace() != LangAS::Default) {
  6643. // Do not allow other address spaces on automatic variable.
  6644. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6645. NewVD->setInvalidDecl();
  6646. return;
  6647. }
  6648. }
  6649. }
  6650. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6651. && !NewVD->hasAttr<BlocksAttr>()) {
  6652. if (getLangOpts().getGC() != LangOptions::NonGC)
  6653. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6654. else {
  6655. assert(!getLangOpts().ObjCAutoRefCount);
  6656. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6657. }
  6658. }
  6659. bool isVM = T->isVariablyModifiedType();
  6660. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6661. NewVD->hasAttr<BlocksAttr>())
  6662. setFunctionHasBranchProtectedScope();
  6663. if ((isVM && NewVD->hasLinkage()) ||
  6664. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6665. bool SizeIsNegative;
  6666. llvm::APSInt Oversized;
  6667. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6668. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6669. QualType FixedT;
  6670. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6671. FixedT = FixedTInfo->getType();
  6672. else if (FixedTInfo) {
  6673. // Type and type-as-written are canonically different. We need to fix up
  6674. // both types separately.
  6675. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6676. Oversized);
  6677. }
  6678. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6679. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6680. // FIXME: This won't give the correct result for
  6681. // int a[10][n];
  6682. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6683. if (NewVD->isFileVarDecl())
  6684. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6685. << SizeRange;
  6686. else if (NewVD->isStaticLocal())
  6687. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6688. << SizeRange;
  6689. else
  6690. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6691. << SizeRange;
  6692. NewVD->setInvalidDecl();
  6693. return;
  6694. }
  6695. if (!FixedTInfo) {
  6696. if (NewVD->isFileVarDecl())
  6697. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6698. else
  6699. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6700. NewVD->setInvalidDecl();
  6701. return;
  6702. }
  6703. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6704. NewVD->setType(FixedT);
  6705. NewVD->setTypeSourceInfo(FixedTInfo);
  6706. }
  6707. if (T->isVoidType()) {
  6708. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6709. // of objects and functions.
  6710. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6711. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6712. << T;
  6713. NewVD->setInvalidDecl();
  6714. return;
  6715. }
  6716. }
  6717. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6718. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6719. NewVD->setInvalidDecl();
  6720. return;
  6721. }
  6722. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6723. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6724. NewVD->setInvalidDecl();
  6725. return;
  6726. }
  6727. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6728. RequireLiteralType(NewVD->getLocation(), T,
  6729. diag::err_constexpr_var_non_literal)) {
  6730. NewVD->setInvalidDecl();
  6731. return;
  6732. }
  6733. }
  6734. /// Perform semantic checking on a newly-created variable
  6735. /// declaration.
  6736. ///
  6737. /// This routine performs all of the type-checking required for a
  6738. /// variable declaration once it has been built. It is used both to
  6739. /// check variables after they have been parsed and their declarators
  6740. /// have been translated into a declaration, and to check variables
  6741. /// that have been instantiated from a template.
  6742. ///
  6743. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6744. ///
  6745. /// Returns true if the variable declaration is a redeclaration.
  6746. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6747. CheckVariableDeclarationType(NewVD);
  6748. // If the decl is already known invalid, don't check it.
  6749. if (NewVD->isInvalidDecl())
  6750. return false;
  6751. // If we did not find anything by this name, look for a non-visible
  6752. // extern "C" declaration with the same name.
  6753. if (Previous.empty() &&
  6754. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6755. Previous.setShadowed();
  6756. if (!Previous.empty()) {
  6757. MergeVarDecl(NewVD, Previous);
  6758. return true;
  6759. }
  6760. return false;
  6761. }
  6762. namespace {
  6763. struct FindOverriddenMethod {
  6764. Sema *S;
  6765. CXXMethodDecl *Method;
  6766. /// Member lookup function that determines whether a given C++
  6767. /// method overrides a method in a base class, to be used with
  6768. /// CXXRecordDecl::lookupInBases().
  6769. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6770. RecordDecl *BaseRecord =
  6771. Specifier->getType()->getAs<RecordType>()->getDecl();
  6772. DeclarationName Name = Method->getDeclName();
  6773. // FIXME: Do we care about other names here too?
  6774. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6775. // We really want to find the base class destructor here.
  6776. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6777. CanQualType CT = S->Context.getCanonicalType(T);
  6778. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6779. }
  6780. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6781. Path.Decls = Path.Decls.slice(1)) {
  6782. NamedDecl *D = Path.Decls.front();
  6783. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6784. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6785. return true;
  6786. }
  6787. }
  6788. return false;
  6789. }
  6790. };
  6791. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6792. } // end anonymous namespace
  6793. /// Report an error regarding overriding, along with any relevant
  6794. /// overridden methods.
  6795. ///
  6796. /// \param DiagID the primary error to report.
  6797. /// \param MD the overriding method.
  6798. /// \param OEK which overrides to include as notes.
  6799. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6800. OverrideErrorKind OEK = OEK_All) {
  6801. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6802. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6803. // This check (& the OEK parameter) could be replaced by a predicate, but
  6804. // without lambdas that would be overkill. This is still nicer than writing
  6805. // out the diag loop 3 times.
  6806. if ((OEK == OEK_All) ||
  6807. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6808. (OEK == OEK_Deleted && O->isDeleted()))
  6809. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6810. }
  6811. }
  6812. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6813. /// and if so, check that it's a valid override and remember it.
  6814. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6815. // Look for methods in base classes that this method might override.
  6816. CXXBasePaths Paths;
  6817. FindOverriddenMethod FOM;
  6818. FOM.Method = MD;
  6819. FOM.S = this;
  6820. bool hasDeletedOverridenMethods = false;
  6821. bool hasNonDeletedOverridenMethods = false;
  6822. bool AddedAny = false;
  6823. if (DC->lookupInBases(FOM, Paths)) {
  6824. for (auto *I : Paths.found_decls()) {
  6825. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6826. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6827. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6828. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6829. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6830. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6831. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6832. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6833. AddedAny = true;
  6834. }
  6835. }
  6836. }
  6837. }
  6838. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6839. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6840. }
  6841. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6842. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6843. }
  6844. return AddedAny;
  6845. }
  6846. namespace {
  6847. // Struct for holding all of the extra arguments needed by
  6848. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6849. struct ActOnFDArgs {
  6850. Scope *S;
  6851. Declarator &D;
  6852. MultiTemplateParamsArg TemplateParamLists;
  6853. bool AddToScope;
  6854. };
  6855. } // end anonymous namespace
  6856. namespace {
  6857. // Callback to only accept typo corrections that have a non-zero edit distance.
  6858. // Also only accept corrections that have the same parent decl.
  6859. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  6860. public:
  6861. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6862. CXXRecordDecl *Parent)
  6863. : Context(Context), OriginalFD(TypoFD),
  6864. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6865. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6866. if (candidate.getEditDistance() == 0)
  6867. return false;
  6868. SmallVector<unsigned, 1> MismatchedParams;
  6869. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6870. CDeclEnd = candidate.end();
  6871. CDecl != CDeclEnd; ++CDecl) {
  6872. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6873. if (FD && !FD->hasBody() &&
  6874. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6875. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6876. CXXRecordDecl *Parent = MD->getParent();
  6877. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6878. return true;
  6879. } else if (!ExpectedParent) {
  6880. return true;
  6881. }
  6882. }
  6883. }
  6884. return false;
  6885. }
  6886. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  6887. return llvm::make_unique<DifferentNameValidatorCCC>(*this);
  6888. }
  6889. private:
  6890. ASTContext &Context;
  6891. FunctionDecl *OriginalFD;
  6892. CXXRecordDecl *ExpectedParent;
  6893. };
  6894. } // end anonymous namespace
  6895. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6896. TypoCorrectedFunctionDefinitions.insert(F);
  6897. }
  6898. /// Generate diagnostics for an invalid function redeclaration.
  6899. ///
  6900. /// This routine handles generating the diagnostic messages for an invalid
  6901. /// function redeclaration, including finding possible similar declarations
  6902. /// or performing typo correction if there are no previous declarations with
  6903. /// the same name.
  6904. ///
  6905. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6906. /// the new declaration name does not cause new errors.
  6907. static NamedDecl *DiagnoseInvalidRedeclaration(
  6908. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6909. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6910. DeclarationName Name = NewFD->getDeclName();
  6911. DeclContext *NewDC = NewFD->getDeclContext();
  6912. SmallVector<unsigned, 1> MismatchedParams;
  6913. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6914. TypoCorrection Correction;
  6915. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6916. unsigned DiagMsg =
  6917. IsLocalFriend ? diag::err_no_matching_local_friend :
  6918. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  6919. diag::err_member_decl_does_not_match;
  6920. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6921. IsLocalFriend ? Sema::LookupLocalFriendName
  6922. : Sema::LookupOrdinaryName,
  6923. Sema::ForVisibleRedeclaration);
  6924. NewFD->setInvalidDecl();
  6925. if (IsLocalFriend)
  6926. SemaRef.LookupName(Prev, S);
  6927. else
  6928. SemaRef.LookupQualifiedName(Prev, NewDC);
  6929. assert(!Prev.isAmbiguous() &&
  6930. "Cannot have an ambiguity in previous-declaration lookup");
  6931. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6932. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  6933. MD ? MD->getParent() : nullptr);
  6934. if (!Prev.empty()) {
  6935. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6936. Func != FuncEnd; ++Func) {
  6937. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6938. if (FD &&
  6939. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6940. // Add 1 to the index so that 0 can mean the mismatch didn't
  6941. // involve a parameter
  6942. unsigned ParamNum =
  6943. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6944. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6945. }
  6946. }
  6947. // If the qualified name lookup yielded nothing, try typo correction
  6948. } else if ((Correction = SemaRef.CorrectTypo(
  6949. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6950. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  6951. IsLocalFriend ? nullptr : NewDC))) {
  6952. // Set up everything for the call to ActOnFunctionDeclarator
  6953. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6954. ExtraArgs.D.getIdentifierLoc());
  6955. Previous.clear();
  6956. Previous.setLookupName(Correction.getCorrection());
  6957. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6958. CDeclEnd = Correction.end();
  6959. CDecl != CDeclEnd; ++CDecl) {
  6960. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6961. if (FD && !FD->hasBody() &&
  6962. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6963. Previous.addDecl(FD);
  6964. }
  6965. }
  6966. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6967. NamedDecl *Result;
  6968. // Retry building the function declaration with the new previous
  6969. // declarations, and with errors suppressed.
  6970. {
  6971. // Trap errors.
  6972. Sema::SFINAETrap Trap(SemaRef);
  6973. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6974. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6975. // eliminate the need for the parameter pack ExtraArgs.
  6976. Result = SemaRef.ActOnFunctionDeclarator(
  6977. ExtraArgs.S, ExtraArgs.D,
  6978. Correction.getCorrectionDecl()->getDeclContext(),
  6979. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6980. ExtraArgs.AddToScope);
  6981. if (Trap.hasErrorOccurred())
  6982. Result = nullptr;
  6983. }
  6984. if (Result) {
  6985. // Determine which correction we picked.
  6986. Decl *Canonical = Result->getCanonicalDecl();
  6987. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6988. I != E; ++I)
  6989. if ((*I)->getCanonicalDecl() == Canonical)
  6990. Correction.setCorrectionDecl(*I);
  6991. // Let Sema know about the correction.
  6992. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6993. SemaRef.diagnoseTypo(
  6994. Correction,
  6995. SemaRef.PDiag(IsLocalFriend
  6996. ? diag::err_no_matching_local_friend_suggest
  6997. : diag::err_member_decl_does_not_match_suggest)
  6998. << Name << NewDC << IsDefinition);
  6999. return Result;
  7000. }
  7001. // Pretend the typo correction never occurred
  7002. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7003. ExtraArgs.D.getIdentifierLoc());
  7004. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7005. Previous.clear();
  7006. Previous.setLookupName(Name);
  7007. }
  7008. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7009. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7010. bool NewFDisConst = false;
  7011. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7012. NewFDisConst = NewMD->isConst();
  7013. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7014. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7015. NearMatch != NearMatchEnd; ++NearMatch) {
  7016. FunctionDecl *FD = NearMatch->first;
  7017. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7018. bool FDisConst = MD && MD->isConst();
  7019. bool IsMember = MD || !IsLocalFriend;
  7020. // FIXME: These notes are poorly worded for the local friend case.
  7021. if (unsigned Idx = NearMatch->second) {
  7022. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7023. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7024. if (Loc.isInvalid()) Loc = FD->getLocation();
  7025. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7026. : diag::note_local_decl_close_param_match)
  7027. << Idx << FDParam->getType()
  7028. << NewFD->getParamDecl(Idx - 1)->getType();
  7029. } else if (FDisConst != NewFDisConst) {
  7030. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7031. << NewFDisConst << FD->getSourceRange().getEnd();
  7032. } else
  7033. SemaRef.Diag(FD->getLocation(),
  7034. IsMember ? diag::note_member_def_close_match
  7035. : diag::note_local_decl_close_match);
  7036. }
  7037. return nullptr;
  7038. }
  7039. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7040. switch (D.getDeclSpec().getStorageClassSpec()) {
  7041. default: llvm_unreachable("Unknown storage class!");
  7042. case DeclSpec::SCS_auto:
  7043. case DeclSpec::SCS_register:
  7044. case DeclSpec::SCS_mutable:
  7045. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7046. diag::err_typecheck_sclass_func);
  7047. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7048. D.setInvalidType();
  7049. break;
  7050. case DeclSpec::SCS_unspecified: break;
  7051. case DeclSpec::SCS_extern:
  7052. if (D.getDeclSpec().isExternInLinkageSpec())
  7053. return SC_None;
  7054. return SC_Extern;
  7055. case DeclSpec::SCS_static: {
  7056. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7057. // C99 6.7.1p5:
  7058. // The declaration of an identifier for a function that has
  7059. // block scope shall have no explicit storage-class specifier
  7060. // other than extern
  7061. // See also (C++ [dcl.stc]p4).
  7062. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7063. diag::err_static_block_func);
  7064. break;
  7065. } else
  7066. return SC_Static;
  7067. }
  7068. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7069. }
  7070. // No explicit storage class has already been returned
  7071. return SC_None;
  7072. }
  7073. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7074. DeclContext *DC, QualType &R,
  7075. TypeSourceInfo *TInfo,
  7076. StorageClass SC,
  7077. bool &IsVirtualOkay) {
  7078. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7079. DeclarationName Name = NameInfo.getName();
  7080. FunctionDecl *NewFD = nullptr;
  7081. bool isInline = D.getDeclSpec().isInlineSpecified();
  7082. if (!SemaRef.getLangOpts().CPlusPlus) {
  7083. // Determine whether the function was written with a
  7084. // prototype. This true when:
  7085. // - there is a prototype in the declarator, or
  7086. // - the type R of the function is some kind of typedef or other non-
  7087. // attributed reference to a type name (which eventually refers to a
  7088. // function type).
  7089. bool HasPrototype =
  7090. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7091. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7092. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7093. R, TInfo, SC, isInline, HasPrototype,
  7094. CSK_unspecified);
  7095. if (D.isInvalidType())
  7096. NewFD->setInvalidDecl();
  7097. return NewFD;
  7098. }
  7099. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7100. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7101. // Check that the return type is not an abstract class type.
  7102. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7103. // the class has been completely parsed.
  7104. if (!DC->isRecord() &&
  7105. SemaRef.RequireNonAbstractType(
  7106. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7107. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7108. D.setInvalidType();
  7109. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7110. // This is a C++ constructor declaration.
  7111. assert(DC->isRecord() &&
  7112. "Constructors can only be declared in a member context");
  7113. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7114. return CXXConstructorDecl::Create(
  7115. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7116. TInfo, ExplicitSpecifier, isInline,
  7117. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7118. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7119. // This is a C++ destructor declaration.
  7120. if (DC->isRecord()) {
  7121. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7122. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7123. CXXDestructorDecl *NewDD =
  7124. CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
  7125. NameInfo, R, TInfo, isInline,
  7126. /*isImplicitlyDeclared=*/false);
  7127. // If the destructor needs an implicit exception specification, set it
  7128. // now. FIXME: It'd be nice to be able to create the right type to start
  7129. // with, but the type needs to reference the destructor declaration.
  7130. if (SemaRef.getLangOpts().CPlusPlus11)
  7131. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7132. IsVirtualOkay = true;
  7133. return NewDD;
  7134. } else {
  7135. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7136. D.setInvalidType();
  7137. // Create a FunctionDecl to satisfy the function definition parsing
  7138. // code path.
  7139. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7140. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7141. isInline,
  7142. /*hasPrototype=*/true, ConstexprKind);
  7143. }
  7144. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7145. if (!DC->isRecord()) {
  7146. SemaRef.Diag(D.getIdentifierLoc(),
  7147. diag::err_conv_function_not_member);
  7148. return nullptr;
  7149. }
  7150. SemaRef.CheckConversionDeclarator(D, R, SC);
  7151. IsVirtualOkay = true;
  7152. return CXXConversionDecl::Create(
  7153. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7154. TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
  7155. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7156. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7157. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7158. ExplicitSpecifier, NameInfo, R, TInfo,
  7159. D.getEndLoc());
  7160. } else if (DC->isRecord()) {
  7161. // If the name of the function is the same as the name of the record,
  7162. // then this must be an invalid constructor that has a return type.
  7163. // (The parser checks for a return type and makes the declarator a
  7164. // constructor if it has no return type).
  7165. if (Name.getAsIdentifierInfo() &&
  7166. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7167. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7168. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7169. << SourceRange(D.getIdentifierLoc());
  7170. return nullptr;
  7171. }
  7172. // This is a C++ method declaration.
  7173. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7174. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7175. TInfo, SC, isInline, ConstexprKind, SourceLocation());
  7176. IsVirtualOkay = !Ret->isStatic();
  7177. return Ret;
  7178. } else {
  7179. bool isFriend =
  7180. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7181. if (!isFriend && SemaRef.CurContext->isRecord())
  7182. return nullptr;
  7183. // Determine whether the function was written with a
  7184. // prototype. This true when:
  7185. // - we're in C++ (where every function has a prototype),
  7186. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7187. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7188. ConstexprKind);
  7189. }
  7190. }
  7191. enum OpenCLParamType {
  7192. ValidKernelParam,
  7193. PtrPtrKernelParam,
  7194. PtrKernelParam,
  7195. InvalidAddrSpacePtrKernelParam,
  7196. InvalidKernelParam,
  7197. RecordKernelParam
  7198. };
  7199. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7200. // Size dependent types are just typedefs to normal integer types
  7201. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7202. // integers other than by their names.
  7203. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7204. // Remove typedefs one by one until we reach a typedef
  7205. // for a size dependent type.
  7206. QualType DesugaredTy = Ty;
  7207. do {
  7208. ArrayRef<StringRef> Names(SizeTypeNames);
  7209. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7210. if (Names.end() != Match)
  7211. return true;
  7212. Ty = DesugaredTy;
  7213. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7214. } while (DesugaredTy != Ty);
  7215. return false;
  7216. }
  7217. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7218. if (PT->isPointerType()) {
  7219. QualType PointeeType = PT->getPointeeType();
  7220. if (PointeeType->isPointerType())
  7221. return PtrPtrKernelParam;
  7222. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7223. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7224. PointeeType.getAddressSpace() == LangAS::Default)
  7225. return InvalidAddrSpacePtrKernelParam;
  7226. return PtrKernelParam;
  7227. }
  7228. // OpenCL v1.2 s6.9.k:
  7229. // Arguments to kernel functions in a program cannot be declared with the
  7230. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7231. // uintptr_t or a struct and/or union that contain fields declared to be one
  7232. // of these built-in scalar types.
  7233. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7234. return InvalidKernelParam;
  7235. if (PT->isImageType())
  7236. return PtrKernelParam;
  7237. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7238. return InvalidKernelParam;
  7239. // OpenCL extension spec v1.2 s9.5:
  7240. // This extension adds support for half scalar and vector types as built-in
  7241. // types that can be used for arithmetic operations, conversions etc.
  7242. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7243. return InvalidKernelParam;
  7244. if (PT->isRecordType())
  7245. return RecordKernelParam;
  7246. // Look into an array argument to check if it has a forbidden type.
  7247. if (PT->isArrayType()) {
  7248. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7249. // Call ourself to check an underlying type of an array. Since the
  7250. // getPointeeOrArrayElementType returns an innermost type which is not an
  7251. // array, this recursive call only happens once.
  7252. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7253. }
  7254. return ValidKernelParam;
  7255. }
  7256. static void checkIsValidOpenCLKernelParameter(
  7257. Sema &S,
  7258. Declarator &D,
  7259. ParmVarDecl *Param,
  7260. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7261. QualType PT = Param->getType();
  7262. // Cache the valid types we encounter to avoid rechecking structs that are
  7263. // used again
  7264. if (ValidTypes.count(PT.getTypePtr()))
  7265. return;
  7266. switch (getOpenCLKernelParameterType(S, PT)) {
  7267. case PtrPtrKernelParam:
  7268. // OpenCL v1.2 s6.9.a:
  7269. // A kernel function argument cannot be declared as a
  7270. // pointer to a pointer type.
  7271. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7272. D.setInvalidType();
  7273. return;
  7274. case InvalidAddrSpacePtrKernelParam:
  7275. // OpenCL v1.0 s6.5:
  7276. // __kernel function arguments declared to be a pointer of a type can point
  7277. // to one of the following address spaces only : __global, __local or
  7278. // __constant.
  7279. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7280. D.setInvalidType();
  7281. return;
  7282. // OpenCL v1.2 s6.9.k:
  7283. // Arguments to kernel functions in a program cannot be declared with the
  7284. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7285. // uintptr_t or a struct and/or union that contain fields declared to be
  7286. // one of these built-in scalar types.
  7287. case InvalidKernelParam:
  7288. // OpenCL v1.2 s6.8 n:
  7289. // A kernel function argument cannot be declared
  7290. // of event_t type.
  7291. // Do not diagnose half type since it is diagnosed as invalid argument
  7292. // type for any function elsewhere.
  7293. if (!PT->isHalfType()) {
  7294. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7295. // Explain what typedefs are involved.
  7296. const TypedefType *Typedef = nullptr;
  7297. while ((Typedef = PT->getAs<TypedefType>())) {
  7298. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7299. // SourceLocation may be invalid for a built-in type.
  7300. if (Loc.isValid())
  7301. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7302. PT = Typedef->desugar();
  7303. }
  7304. }
  7305. D.setInvalidType();
  7306. return;
  7307. case PtrKernelParam:
  7308. case ValidKernelParam:
  7309. ValidTypes.insert(PT.getTypePtr());
  7310. return;
  7311. case RecordKernelParam:
  7312. break;
  7313. }
  7314. // Track nested structs we will inspect
  7315. SmallVector<const Decl *, 4> VisitStack;
  7316. // Track where we are in the nested structs. Items will migrate from
  7317. // VisitStack to HistoryStack as we do the DFS for bad field.
  7318. SmallVector<const FieldDecl *, 4> HistoryStack;
  7319. HistoryStack.push_back(nullptr);
  7320. // At this point we already handled everything except of a RecordType or
  7321. // an ArrayType of a RecordType.
  7322. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7323. const RecordType *RecTy =
  7324. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7325. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7326. VisitStack.push_back(RecTy->getDecl());
  7327. assert(VisitStack.back() && "First decl null?");
  7328. do {
  7329. const Decl *Next = VisitStack.pop_back_val();
  7330. if (!Next) {
  7331. assert(!HistoryStack.empty());
  7332. // Found a marker, we have gone up a level
  7333. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7334. ValidTypes.insert(Hist->getType().getTypePtr());
  7335. continue;
  7336. }
  7337. // Adds everything except the original parameter declaration (which is not a
  7338. // field itself) to the history stack.
  7339. const RecordDecl *RD;
  7340. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7341. HistoryStack.push_back(Field);
  7342. QualType FieldTy = Field->getType();
  7343. // Other field types (known to be valid or invalid) are handled while we
  7344. // walk around RecordDecl::fields().
  7345. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7346. "Unexpected type.");
  7347. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7348. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7349. } else {
  7350. RD = cast<RecordDecl>(Next);
  7351. }
  7352. // Add a null marker so we know when we've gone back up a level
  7353. VisitStack.push_back(nullptr);
  7354. for (const auto *FD : RD->fields()) {
  7355. QualType QT = FD->getType();
  7356. if (ValidTypes.count(QT.getTypePtr()))
  7357. continue;
  7358. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7359. if (ParamType == ValidKernelParam)
  7360. continue;
  7361. if (ParamType == RecordKernelParam) {
  7362. VisitStack.push_back(FD);
  7363. continue;
  7364. }
  7365. // OpenCL v1.2 s6.9.p:
  7366. // Arguments to kernel functions that are declared to be a struct or union
  7367. // do not allow OpenCL objects to be passed as elements of the struct or
  7368. // union.
  7369. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7370. ParamType == InvalidAddrSpacePtrKernelParam) {
  7371. S.Diag(Param->getLocation(),
  7372. diag::err_record_with_pointers_kernel_param)
  7373. << PT->isUnionType()
  7374. << PT;
  7375. } else {
  7376. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7377. }
  7378. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7379. << OrigRecDecl->getDeclName();
  7380. // We have an error, now let's go back up through history and show where
  7381. // the offending field came from
  7382. for (ArrayRef<const FieldDecl *>::const_iterator
  7383. I = HistoryStack.begin() + 1,
  7384. E = HistoryStack.end();
  7385. I != E; ++I) {
  7386. const FieldDecl *OuterField = *I;
  7387. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7388. << OuterField->getType();
  7389. }
  7390. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7391. << QT->isPointerType()
  7392. << QT;
  7393. D.setInvalidType();
  7394. return;
  7395. }
  7396. } while (!VisitStack.empty());
  7397. }
  7398. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7399. /// elaborated type specifier in the specified context, and lookup finds
  7400. /// nothing.
  7401. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7402. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7403. DC = DC->getParent();
  7404. return DC;
  7405. }
  7406. /// Find the Scope in which a tag is implicitly declared if we see an
  7407. /// elaborated type specifier in the specified context, and lookup finds
  7408. /// nothing.
  7409. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7410. while (S->isClassScope() ||
  7411. (LangOpts.CPlusPlus &&
  7412. S->isFunctionPrototypeScope()) ||
  7413. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7414. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7415. S = S->getParent();
  7416. return S;
  7417. }
  7418. NamedDecl*
  7419. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7420. TypeSourceInfo *TInfo, LookupResult &Previous,
  7421. MultiTemplateParamsArg TemplateParamLists,
  7422. bool &AddToScope) {
  7423. QualType R = TInfo->getType();
  7424. assert(R->isFunctionType());
  7425. // TODO: consider using NameInfo for diagnostic.
  7426. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7427. DeclarationName Name = NameInfo.getName();
  7428. StorageClass SC = getFunctionStorageClass(*this, D);
  7429. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7430. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7431. diag::err_invalid_thread)
  7432. << DeclSpec::getSpecifierName(TSCS);
  7433. if (D.isFirstDeclarationOfMember())
  7434. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7435. D.getIdentifierLoc());
  7436. bool isFriend = false;
  7437. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7438. bool isMemberSpecialization = false;
  7439. bool isFunctionTemplateSpecialization = false;
  7440. bool isDependentClassScopeExplicitSpecialization = false;
  7441. bool HasExplicitTemplateArgs = false;
  7442. TemplateArgumentListInfo TemplateArgs;
  7443. bool isVirtualOkay = false;
  7444. DeclContext *OriginalDC = DC;
  7445. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7446. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7447. isVirtualOkay);
  7448. if (!NewFD) return nullptr;
  7449. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7450. NewFD->setTopLevelDeclInObjCContainer();
  7451. // Set the lexical context. If this is a function-scope declaration, or has a
  7452. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7453. // context will be different from the semantic context.
  7454. NewFD->setLexicalDeclContext(CurContext);
  7455. if (IsLocalExternDecl)
  7456. NewFD->setLocalExternDecl();
  7457. if (getLangOpts().CPlusPlus) {
  7458. bool isInline = D.getDeclSpec().isInlineSpecified();
  7459. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7460. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7461. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7462. isFriend = D.getDeclSpec().isFriendSpecified();
  7463. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7464. // C++ [class.friend]p5
  7465. // A function can be defined in a friend declaration of a
  7466. // class . . . . Such a function is implicitly inline.
  7467. NewFD->setImplicitlyInline();
  7468. }
  7469. // If this is a method defined in an __interface, and is not a constructor
  7470. // or an overloaded operator, then set the pure flag (isVirtual will already
  7471. // return true).
  7472. if (const CXXRecordDecl *Parent =
  7473. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7474. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7475. NewFD->setPure(true);
  7476. // C++ [class.union]p2
  7477. // A union can have member functions, but not virtual functions.
  7478. if (isVirtual && Parent->isUnion())
  7479. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7480. }
  7481. SetNestedNameSpecifier(*this, NewFD, D);
  7482. isMemberSpecialization = false;
  7483. isFunctionTemplateSpecialization = false;
  7484. if (D.isInvalidType())
  7485. NewFD->setInvalidDecl();
  7486. // Match up the template parameter lists with the scope specifier, then
  7487. // determine whether we have a template or a template specialization.
  7488. bool Invalid = false;
  7489. if (TemplateParameterList *TemplateParams =
  7490. MatchTemplateParametersToScopeSpecifier(
  7491. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7492. D.getCXXScopeSpec(),
  7493. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7494. ? D.getName().TemplateId
  7495. : nullptr,
  7496. TemplateParamLists, isFriend, isMemberSpecialization,
  7497. Invalid)) {
  7498. if (TemplateParams->size() > 0) {
  7499. // This is a function template
  7500. // Check that we can declare a template here.
  7501. if (CheckTemplateDeclScope(S, TemplateParams))
  7502. NewFD->setInvalidDecl();
  7503. // A destructor cannot be a template.
  7504. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7505. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7506. NewFD->setInvalidDecl();
  7507. }
  7508. // If we're adding a template to a dependent context, we may need to
  7509. // rebuilding some of the types used within the template parameter list,
  7510. // now that we know what the current instantiation is.
  7511. if (DC->isDependentContext()) {
  7512. ContextRAII SavedContext(*this, DC);
  7513. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7514. Invalid = true;
  7515. }
  7516. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7517. NewFD->getLocation(),
  7518. Name, TemplateParams,
  7519. NewFD);
  7520. FunctionTemplate->setLexicalDeclContext(CurContext);
  7521. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7522. // For source fidelity, store the other template param lists.
  7523. if (TemplateParamLists.size() > 1) {
  7524. NewFD->setTemplateParameterListsInfo(Context,
  7525. TemplateParamLists.drop_back(1));
  7526. }
  7527. } else {
  7528. // This is a function template specialization.
  7529. isFunctionTemplateSpecialization = true;
  7530. // For source fidelity, store all the template param lists.
  7531. if (TemplateParamLists.size() > 0)
  7532. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7533. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7534. if (isFriend) {
  7535. // We want to remove the "template<>", found here.
  7536. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7537. // If we remove the template<> and the name is not a
  7538. // template-id, we're actually silently creating a problem:
  7539. // the friend declaration will refer to an untemplated decl,
  7540. // and clearly the user wants a template specialization. So
  7541. // we need to insert '<>' after the name.
  7542. SourceLocation InsertLoc;
  7543. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7544. InsertLoc = D.getName().getSourceRange().getEnd();
  7545. InsertLoc = getLocForEndOfToken(InsertLoc);
  7546. }
  7547. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7548. << Name << RemoveRange
  7549. << FixItHint::CreateRemoval(RemoveRange)
  7550. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7551. }
  7552. }
  7553. } else {
  7554. // All template param lists were matched against the scope specifier:
  7555. // this is NOT (an explicit specialization of) a template.
  7556. if (TemplateParamLists.size() > 0)
  7557. // For source fidelity, store all the template param lists.
  7558. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7559. }
  7560. if (Invalid) {
  7561. NewFD->setInvalidDecl();
  7562. if (FunctionTemplate)
  7563. FunctionTemplate->setInvalidDecl();
  7564. }
  7565. // C++ [dcl.fct.spec]p5:
  7566. // The virtual specifier shall only be used in declarations of
  7567. // nonstatic class member functions that appear within a
  7568. // member-specification of a class declaration; see 10.3.
  7569. //
  7570. if (isVirtual && !NewFD->isInvalidDecl()) {
  7571. if (!isVirtualOkay) {
  7572. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7573. diag::err_virtual_non_function);
  7574. } else if (!CurContext->isRecord()) {
  7575. // 'virtual' was specified outside of the class.
  7576. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7577. diag::err_virtual_out_of_class)
  7578. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7579. } else if (NewFD->getDescribedFunctionTemplate()) {
  7580. // C++ [temp.mem]p3:
  7581. // A member function template shall not be virtual.
  7582. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7583. diag::err_virtual_member_function_template)
  7584. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7585. } else {
  7586. // Okay: Add virtual to the method.
  7587. NewFD->setVirtualAsWritten(true);
  7588. }
  7589. if (getLangOpts().CPlusPlus14 &&
  7590. NewFD->getReturnType()->isUndeducedType())
  7591. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7592. }
  7593. if (getLangOpts().CPlusPlus14 &&
  7594. (NewFD->isDependentContext() ||
  7595. (isFriend && CurContext->isDependentContext())) &&
  7596. NewFD->getReturnType()->isUndeducedType()) {
  7597. // If the function template is referenced directly (for instance, as a
  7598. // member of the current instantiation), pretend it has a dependent type.
  7599. // This is not really justified by the standard, but is the only sane
  7600. // thing to do.
  7601. // FIXME: For a friend function, we have not marked the function as being
  7602. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7603. const FunctionProtoType *FPT =
  7604. NewFD->getType()->castAs<FunctionProtoType>();
  7605. QualType Result =
  7606. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7607. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7608. FPT->getExtProtoInfo()));
  7609. }
  7610. // C++ [dcl.fct.spec]p3:
  7611. // The inline specifier shall not appear on a block scope function
  7612. // declaration.
  7613. if (isInline && !NewFD->isInvalidDecl()) {
  7614. if (CurContext->isFunctionOrMethod()) {
  7615. // 'inline' is not allowed on block scope function declaration.
  7616. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7617. diag::err_inline_declaration_block_scope) << Name
  7618. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7619. }
  7620. }
  7621. // C++ [dcl.fct.spec]p6:
  7622. // The explicit specifier shall be used only in the declaration of a
  7623. // constructor or conversion function within its class definition;
  7624. // see 12.3.1 and 12.3.2.
  7625. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7626. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7627. if (!CurContext->isRecord()) {
  7628. // 'explicit' was specified outside of the class.
  7629. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7630. diag::err_explicit_out_of_class)
  7631. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7632. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7633. !isa<CXXConversionDecl>(NewFD)) {
  7634. // 'explicit' was specified on a function that wasn't a constructor
  7635. // or conversion function.
  7636. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7637. diag::err_explicit_non_ctor_or_conv_function)
  7638. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7639. }
  7640. }
  7641. if (ConstexprKind != CSK_unspecified) {
  7642. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7643. // are implicitly inline.
  7644. NewFD->setImplicitlyInline();
  7645. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7646. // be either constructors or to return a literal type. Therefore,
  7647. // destructors cannot be declared constexpr.
  7648. if (isa<CXXDestructorDecl>(NewFD))
  7649. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  7650. << (ConstexprKind == CSK_consteval);
  7651. }
  7652. // If __module_private__ was specified, mark the function accordingly.
  7653. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7654. if (isFunctionTemplateSpecialization) {
  7655. SourceLocation ModulePrivateLoc
  7656. = D.getDeclSpec().getModulePrivateSpecLoc();
  7657. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7658. << 0
  7659. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7660. } else {
  7661. NewFD->setModulePrivate();
  7662. if (FunctionTemplate)
  7663. FunctionTemplate->setModulePrivate();
  7664. }
  7665. }
  7666. if (isFriend) {
  7667. if (FunctionTemplate) {
  7668. FunctionTemplate->setObjectOfFriendDecl();
  7669. FunctionTemplate->setAccess(AS_public);
  7670. }
  7671. NewFD->setObjectOfFriendDecl();
  7672. NewFD->setAccess(AS_public);
  7673. }
  7674. // If a function is defined as defaulted or deleted, mark it as such now.
  7675. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7676. // definition kind to FDK_Definition.
  7677. switch (D.getFunctionDefinitionKind()) {
  7678. case FDK_Declaration:
  7679. case FDK_Definition:
  7680. break;
  7681. case FDK_Defaulted:
  7682. NewFD->setDefaulted();
  7683. break;
  7684. case FDK_Deleted:
  7685. NewFD->setDeletedAsWritten();
  7686. break;
  7687. }
  7688. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7689. D.isFunctionDefinition()) {
  7690. // C++ [class.mfct]p2:
  7691. // A member function may be defined (8.4) in its class definition, in
  7692. // which case it is an inline member function (7.1.2)
  7693. NewFD->setImplicitlyInline();
  7694. }
  7695. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7696. !CurContext->isRecord()) {
  7697. // C++ [class.static]p1:
  7698. // A data or function member of a class may be declared static
  7699. // in a class definition, in which case it is a static member of
  7700. // the class.
  7701. // Complain about the 'static' specifier if it's on an out-of-line
  7702. // member function definition.
  7703. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7704. // member function template declaration and class member template
  7705. // declaration (MSVC versions before 2015), warn about this.
  7706. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7707. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7708. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7709. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7710. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7711. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7712. }
  7713. // C++11 [except.spec]p15:
  7714. // A deallocation function with no exception-specification is treated
  7715. // as if it were specified with noexcept(true).
  7716. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7717. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7718. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7719. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7720. NewFD->setType(Context.getFunctionType(
  7721. FPT->getReturnType(), FPT->getParamTypes(),
  7722. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7723. }
  7724. // Filter out previous declarations that don't match the scope.
  7725. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7726. D.getCXXScopeSpec().isNotEmpty() ||
  7727. isMemberSpecialization ||
  7728. isFunctionTemplateSpecialization);
  7729. // Handle GNU asm-label extension (encoded as an attribute).
  7730. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7731. // The parser guarantees this is a string.
  7732. StringLiteral *SE = cast<StringLiteral>(E);
  7733. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7734. SE->getString(), 0));
  7735. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7736. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7737. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7738. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7739. if (isDeclExternC(NewFD)) {
  7740. NewFD->addAttr(I->second);
  7741. ExtnameUndeclaredIdentifiers.erase(I);
  7742. } else
  7743. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7744. << /*Variable*/0 << NewFD;
  7745. }
  7746. }
  7747. // Copy the parameter declarations from the declarator D to the function
  7748. // declaration NewFD, if they are available. First scavenge them into Params.
  7749. SmallVector<ParmVarDecl*, 16> Params;
  7750. unsigned FTIIdx;
  7751. if (D.isFunctionDeclarator(FTIIdx)) {
  7752. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7753. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7754. // function that takes no arguments, not a function that takes a
  7755. // single void argument.
  7756. // We let through "const void" here because Sema::GetTypeForDeclarator
  7757. // already checks for that case.
  7758. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7759. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7760. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7761. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7762. Param->setDeclContext(NewFD);
  7763. Params.push_back(Param);
  7764. if (Param->isInvalidDecl())
  7765. NewFD->setInvalidDecl();
  7766. }
  7767. }
  7768. if (!getLangOpts().CPlusPlus) {
  7769. // In C, find all the tag declarations from the prototype and move them
  7770. // into the function DeclContext. Remove them from the surrounding tag
  7771. // injection context of the function, which is typically but not always
  7772. // the TU.
  7773. DeclContext *PrototypeTagContext =
  7774. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7775. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7776. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7777. // We don't want to reparent enumerators. Look at their parent enum
  7778. // instead.
  7779. if (!TD) {
  7780. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7781. TD = cast<EnumDecl>(ECD->getDeclContext());
  7782. }
  7783. if (!TD)
  7784. continue;
  7785. DeclContext *TagDC = TD->getLexicalDeclContext();
  7786. if (!TagDC->containsDecl(TD))
  7787. continue;
  7788. TagDC->removeDecl(TD);
  7789. TD->setDeclContext(NewFD);
  7790. NewFD->addDecl(TD);
  7791. // Preserve the lexical DeclContext if it is not the surrounding tag
  7792. // injection context of the FD. In this example, the semantic context of
  7793. // E will be f and the lexical context will be S, while both the
  7794. // semantic and lexical contexts of S will be f:
  7795. // void f(struct S { enum E { a } f; } s);
  7796. if (TagDC != PrototypeTagContext)
  7797. TD->setLexicalDeclContext(TagDC);
  7798. }
  7799. }
  7800. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7801. // When we're declaring a function with a typedef, typeof, etc as in the
  7802. // following example, we'll need to synthesize (unnamed)
  7803. // parameters for use in the declaration.
  7804. //
  7805. // @code
  7806. // typedef void fn(int);
  7807. // fn f;
  7808. // @endcode
  7809. // Synthesize a parameter for each argument type.
  7810. for (const auto &AI : FT->param_types()) {
  7811. ParmVarDecl *Param =
  7812. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7813. Param->setScopeInfo(0, Params.size());
  7814. Params.push_back(Param);
  7815. }
  7816. } else {
  7817. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7818. "Should not need args for typedef of non-prototype fn");
  7819. }
  7820. // Finally, we know we have the right number of parameters, install them.
  7821. NewFD->setParams(Params);
  7822. if (D.getDeclSpec().isNoreturnSpecified())
  7823. NewFD->addAttr(
  7824. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7825. Context, 0));
  7826. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7827. // because all functions have linkage.
  7828. if (!NewFD->isInvalidDecl() &&
  7829. NewFD->getReturnType()->isVariablyModifiedType()) {
  7830. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7831. NewFD->setInvalidDecl();
  7832. }
  7833. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7834. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7835. !NewFD->hasAttr<SectionAttr>()) {
  7836. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7837. PragmaClangTextSection.SectionName,
  7838. PragmaClangTextSection.PragmaLocation));
  7839. }
  7840. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7841. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7842. !NewFD->hasAttr<SectionAttr>()) {
  7843. NewFD->addAttr(
  7844. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7845. CodeSegStack.CurrentValue->getString(),
  7846. CodeSegStack.CurrentPragmaLocation));
  7847. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7848. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7849. ASTContext::PSF_Read,
  7850. NewFD))
  7851. NewFD->dropAttr<SectionAttr>();
  7852. }
  7853. // Apply an implicit CodeSegAttr from class declspec or
  7854. // apply an implicit SectionAttr from #pragma code_seg if active.
  7855. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7856. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7857. D.isFunctionDefinition())) {
  7858. NewFD->addAttr(SAttr);
  7859. }
  7860. }
  7861. // Handle attributes.
  7862. ProcessDeclAttributes(S, NewFD, D);
  7863. if (getLangOpts().OpenCL) {
  7864. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7865. // type declaration will generate a compilation error.
  7866. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7867. if (AddressSpace != LangAS::Default) {
  7868. Diag(NewFD->getLocation(),
  7869. diag::err_opencl_return_value_with_address_space);
  7870. NewFD->setInvalidDecl();
  7871. }
  7872. }
  7873. if (!getLangOpts().CPlusPlus) {
  7874. // Perform semantic checking on the function declaration.
  7875. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7876. CheckMain(NewFD, D.getDeclSpec());
  7877. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7878. CheckMSVCRTEntryPoint(NewFD);
  7879. if (!NewFD->isInvalidDecl())
  7880. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7881. isMemberSpecialization));
  7882. else if (!Previous.empty())
  7883. // Recover gracefully from an invalid redeclaration.
  7884. D.setRedeclaration(true);
  7885. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7886. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7887. "previous declaration set still overloaded");
  7888. // Diagnose no-prototype function declarations with calling conventions that
  7889. // don't support variadic calls. Only do this in C and do it after merging
  7890. // possibly prototyped redeclarations.
  7891. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7892. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7893. CallingConv CC = FT->getExtInfo().getCC();
  7894. if (!supportsVariadicCall(CC)) {
  7895. // Windows system headers sometimes accidentally use stdcall without
  7896. // (void) parameters, so we relax this to a warning.
  7897. int DiagID =
  7898. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7899. Diag(NewFD->getLocation(), DiagID)
  7900. << FunctionType::getNameForCallConv(CC);
  7901. }
  7902. }
  7903. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  7904. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  7905. checkNonTrivialCUnion(NewFD->getReturnType(),
  7906. NewFD->getReturnTypeSourceRange().getBegin(),
  7907. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  7908. } else {
  7909. // C++11 [replacement.functions]p3:
  7910. // The program's definitions shall not be specified as inline.
  7911. //
  7912. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7913. //
  7914. // Suppress the diagnostic if the function is __attribute__((used)), since
  7915. // that forces an external definition to be emitted.
  7916. if (D.getDeclSpec().isInlineSpecified() &&
  7917. NewFD->isReplaceableGlobalAllocationFunction() &&
  7918. !NewFD->hasAttr<UsedAttr>())
  7919. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7920. diag::ext_operator_new_delete_declared_inline)
  7921. << NewFD->getDeclName();
  7922. // If the declarator is a template-id, translate the parser's template
  7923. // argument list into our AST format.
  7924. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  7925. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7926. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7927. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7928. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7929. TemplateId->NumArgs);
  7930. translateTemplateArguments(TemplateArgsPtr,
  7931. TemplateArgs);
  7932. HasExplicitTemplateArgs = true;
  7933. if (NewFD->isInvalidDecl()) {
  7934. HasExplicitTemplateArgs = false;
  7935. } else if (FunctionTemplate) {
  7936. // Function template with explicit template arguments.
  7937. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7938. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7939. HasExplicitTemplateArgs = false;
  7940. } else {
  7941. assert((isFunctionTemplateSpecialization ||
  7942. D.getDeclSpec().isFriendSpecified()) &&
  7943. "should have a 'template<>' for this decl");
  7944. // "friend void foo<>(int);" is an implicit specialization decl.
  7945. isFunctionTemplateSpecialization = true;
  7946. }
  7947. } else if (isFriend && isFunctionTemplateSpecialization) {
  7948. // This combination is only possible in a recovery case; the user
  7949. // wrote something like:
  7950. // template <> friend void foo(int);
  7951. // which we're recovering from as if the user had written:
  7952. // friend void foo<>(int);
  7953. // Go ahead and fake up a template id.
  7954. HasExplicitTemplateArgs = true;
  7955. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7956. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7957. }
  7958. // We do not add HD attributes to specializations here because
  7959. // they may have different constexpr-ness compared to their
  7960. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7961. // may end up with different effective targets. Instead, a
  7962. // specialization inherits its target attributes from its template
  7963. // in the CheckFunctionTemplateSpecialization() call below.
  7964. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7965. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7966. // If it's a friend (and only if it's a friend), it's possible
  7967. // that either the specialized function type or the specialized
  7968. // template is dependent, and therefore matching will fail. In
  7969. // this case, don't check the specialization yet.
  7970. bool InstantiationDependent = false;
  7971. if (isFunctionTemplateSpecialization && isFriend &&
  7972. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7973. TemplateSpecializationType::anyDependentTemplateArguments(
  7974. TemplateArgs,
  7975. InstantiationDependent))) {
  7976. assert(HasExplicitTemplateArgs &&
  7977. "friend function specialization without template args");
  7978. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7979. Previous))
  7980. NewFD->setInvalidDecl();
  7981. } else if (isFunctionTemplateSpecialization) {
  7982. if (CurContext->isDependentContext() && CurContext->isRecord()
  7983. && !isFriend) {
  7984. isDependentClassScopeExplicitSpecialization = true;
  7985. } else if (!NewFD->isInvalidDecl() &&
  7986. CheckFunctionTemplateSpecialization(
  7987. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7988. Previous))
  7989. NewFD->setInvalidDecl();
  7990. // C++ [dcl.stc]p1:
  7991. // A storage-class-specifier shall not be specified in an explicit
  7992. // specialization (14.7.3)
  7993. FunctionTemplateSpecializationInfo *Info =
  7994. NewFD->getTemplateSpecializationInfo();
  7995. if (Info && SC != SC_None) {
  7996. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7997. Diag(NewFD->getLocation(),
  7998. diag::err_explicit_specialization_inconsistent_storage_class)
  7999. << SC
  8000. << FixItHint::CreateRemoval(
  8001. D.getDeclSpec().getStorageClassSpecLoc());
  8002. else
  8003. Diag(NewFD->getLocation(),
  8004. diag::ext_explicit_specialization_storage_class)
  8005. << FixItHint::CreateRemoval(
  8006. D.getDeclSpec().getStorageClassSpecLoc());
  8007. }
  8008. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8009. if (CheckMemberSpecialization(NewFD, Previous))
  8010. NewFD->setInvalidDecl();
  8011. }
  8012. // Perform semantic checking on the function declaration.
  8013. if (!isDependentClassScopeExplicitSpecialization) {
  8014. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8015. CheckMain(NewFD, D.getDeclSpec());
  8016. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8017. CheckMSVCRTEntryPoint(NewFD);
  8018. if (!NewFD->isInvalidDecl())
  8019. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8020. isMemberSpecialization));
  8021. else if (!Previous.empty())
  8022. // Recover gracefully from an invalid redeclaration.
  8023. D.setRedeclaration(true);
  8024. }
  8025. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8026. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8027. "previous declaration set still overloaded");
  8028. NamedDecl *PrincipalDecl = (FunctionTemplate
  8029. ? cast<NamedDecl>(FunctionTemplate)
  8030. : NewFD);
  8031. if (isFriend && NewFD->getPreviousDecl()) {
  8032. AccessSpecifier Access = AS_public;
  8033. if (!NewFD->isInvalidDecl())
  8034. Access = NewFD->getPreviousDecl()->getAccess();
  8035. NewFD->setAccess(Access);
  8036. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8037. }
  8038. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8039. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8040. PrincipalDecl->setNonMemberOperator();
  8041. // If we have a function template, check the template parameter
  8042. // list. This will check and merge default template arguments.
  8043. if (FunctionTemplate) {
  8044. FunctionTemplateDecl *PrevTemplate =
  8045. FunctionTemplate->getPreviousDecl();
  8046. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8047. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8048. : nullptr,
  8049. D.getDeclSpec().isFriendSpecified()
  8050. ? (D.isFunctionDefinition()
  8051. ? TPC_FriendFunctionTemplateDefinition
  8052. : TPC_FriendFunctionTemplate)
  8053. : (D.getCXXScopeSpec().isSet() &&
  8054. DC && DC->isRecord() &&
  8055. DC->isDependentContext())
  8056. ? TPC_ClassTemplateMember
  8057. : TPC_FunctionTemplate);
  8058. }
  8059. if (NewFD->isInvalidDecl()) {
  8060. // Ignore all the rest of this.
  8061. } else if (!D.isRedeclaration()) {
  8062. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8063. AddToScope };
  8064. // Fake up an access specifier if it's supposed to be a class member.
  8065. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8066. NewFD->setAccess(AS_public);
  8067. // Qualified decls generally require a previous declaration.
  8068. if (D.getCXXScopeSpec().isSet()) {
  8069. // ...with the major exception of templated-scope or
  8070. // dependent-scope friend declarations.
  8071. // TODO: we currently also suppress this check in dependent
  8072. // contexts because (1) the parameter depth will be off when
  8073. // matching friend templates and (2) we might actually be
  8074. // selecting a friend based on a dependent factor. But there
  8075. // are situations where these conditions don't apply and we
  8076. // can actually do this check immediately.
  8077. //
  8078. // Unless the scope is dependent, it's always an error if qualified
  8079. // redeclaration lookup found nothing at all. Diagnose that now;
  8080. // nothing will diagnose that error later.
  8081. if (isFriend &&
  8082. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8083. (!Previous.empty() && CurContext->isDependentContext()))) {
  8084. // ignore these
  8085. } else {
  8086. // The user tried to provide an out-of-line definition for a
  8087. // function that is a member of a class or namespace, but there
  8088. // was no such member function declared (C++ [class.mfct]p2,
  8089. // C++ [namespace.memdef]p2). For example:
  8090. //
  8091. // class X {
  8092. // void f() const;
  8093. // };
  8094. //
  8095. // void X::f() { } // ill-formed
  8096. //
  8097. // Complain about this problem, and attempt to suggest close
  8098. // matches (e.g., those that differ only in cv-qualifiers and
  8099. // whether the parameter types are references).
  8100. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8101. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8102. AddToScope = ExtraArgs.AddToScope;
  8103. return Result;
  8104. }
  8105. }
  8106. // Unqualified local friend declarations are required to resolve
  8107. // to something.
  8108. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8109. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8110. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8111. AddToScope = ExtraArgs.AddToScope;
  8112. return Result;
  8113. }
  8114. }
  8115. } else if (!D.isFunctionDefinition() &&
  8116. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8117. !isFriend && !isFunctionTemplateSpecialization &&
  8118. !isMemberSpecialization) {
  8119. // An out-of-line member function declaration must also be a
  8120. // definition (C++ [class.mfct]p2).
  8121. // Note that this is not the case for explicit specializations of
  8122. // function templates or member functions of class templates, per
  8123. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8124. // extension for compatibility with old SWIG code which likes to
  8125. // generate them.
  8126. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8127. << D.getCXXScopeSpec().getRange();
  8128. }
  8129. }
  8130. ProcessPragmaWeak(S, NewFD);
  8131. checkAttributesAfterMerging(*this, *NewFD);
  8132. AddKnownFunctionAttributes(NewFD);
  8133. if (NewFD->hasAttr<OverloadableAttr>() &&
  8134. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8135. Diag(NewFD->getLocation(),
  8136. diag::err_attribute_overloadable_no_prototype)
  8137. << NewFD;
  8138. // Turn this into a variadic function with no parameters.
  8139. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8140. FunctionProtoType::ExtProtoInfo EPI(
  8141. Context.getDefaultCallingConvention(true, false));
  8142. EPI.Variadic = true;
  8143. EPI.ExtInfo = FT->getExtInfo();
  8144. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8145. NewFD->setType(R);
  8146. }
  8147. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8148. // member, set the visibility of this function.
  8149. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8150. AddPushedVisibilityAttribute(NewFD);
  8151. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8152. // marking the function.
  8153. AddCFAuditedAttribute(NewFD);
  8154. // If this is a function definition, check if we have to apply optnone due to
  8155. // a pragma.
  8156. if(D.isFunctionDefinition())
  8157. AddRangeBasedOptnone(NewFD);
  8158. // If this is the first declaration of an extern C variable, update
  8159. // the map of such variables.
  8160. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8161. isIncompleteDeclExternC(*this, NewFD))
  8162. RegisterLocallyScopedExternCDecl(NewFD, S);
  8163. // Set this FunctionDecl's range up to the right paren.
  8164. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8165. if (D.isRedeclaration() && !Previous.empty()) {
  8166. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8167. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8168. isMemberSpecialization ||
  8169. isFunctionTemplateSpecialization,
  8170. D.isFunctionDefinition());
  8171. }
  8172. if (getLangOpts().CUDA) {
  8173. IdentifierInfo *II = NewFD->getIdentifier();
  8174. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8175. !NewFD->isInvalidDecl() &&
  8176. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8177. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8178. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8179. << getCudaConfigureFuncName();
  8180. Context.setcudaConfigureCallDecl(NewFD);
  8181. }
  8182. // Variadic functions, other than a *declaration* of printf, are not allowed
  8183. // in device-side CUDA code, unless someone passed
  8184. // -fcuda-allow-variadic-functions.
  8185. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8186. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8187. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8188. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8189. !D.isFunctionDefinition())) {
  8190. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8191. }
  8192. }
  8193. MarkUnusedFileScopedDecl(NewFD);
  8194. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8195. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8196. if ((getLangOpts().OpenCLVersion >= 120)
  8197. && (SC == SC_Static)) {
  8198. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8199. D.setInvalidType();
  8200. }
  8201. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8202. if (!NewFD->getReturnType()->isVoidType()) {
  8203. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8204. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8205. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8206. : FixItHint());
  8207. D.setInvalidType();
  8208. }
  8209. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8210. for (auto Param : NewFD->parameters())
  8211. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8212. if (getLangOpts().OpenCLCPlusPlus) {
  8213. if (DC->isRecord()) {
  8214. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8215. D.setInvalidType();
  8216. }
  8217. if (FunctionTemplate) {
  8218. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8219. D.setInvalidType();
  8220. }
  8221. }
  8222. }
  8223. if (getLangOpts().CPlusPlus) {
  8224. if (FunctionTemplate) {
  8225. if (NewFD->isInvalidDecl())
  8226. FunctionTemplate->setInvalidDecl();
  8227. return FunctionTemplate;
  8228. }
  8229. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8230. CompleteMemberSpecialization(NewFD, Previous);
  8231. }
  8232. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8233. QualType PT = Param->getType();
  8234. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8235. // types.
  8236. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8237. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8238. QualType ElemTy = PipeTy->getElementType();
  8239. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8240. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8241. D.setInvalidType();
  8242. }
  8243. }
  8244. }
  8245. }
  8246. // Here we have an function template explicit specialization at class scope.
  8247. // The actual specialization will be postponed to template instatiation
  8248. // time via the ClassScopeFunctionSpecializationDecl node.
  8249. if (isDependentClassScopeExplicitSpecialization) {
  8250. ClassScopeFunctionSpecializationDecl *NewSpec =
  8251. ClassScopeFunctionSpecializationDecl::Create(
  8252. Context, CurContext, NewFD->getLocation(),
  8253. cast<CXXMethodDecl>(NewFD),
  8254. HasExplicitTemplateArgs, TemplateArgs);
  8255. CurContext->addDecl(NewSpec);
  8256. AddToScope = false;
  8257. }
  8258. // Diagnose availability attributes. Availability cannot be used on functions
  8259. // that are run during load/unload.
  8260. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8261. if (NewFD->hasAttr<ConstructorAttr>()) {
  8262. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8263. << 1;
  8264. NewFD->dropAttr<AvailabilityAttr>();
  8265. }
  8266. if (NewFD->hasAttr<DestructorAttr>()) {
  8267. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8268. << 2;
  8269. NewFD->dropAttr<AvailabilityAttr>();
  8270. }
  8271. }
  8272. return NewFD;
  8273. }
  8274. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8275. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8276. /// the class and nested classes -- this includes compiler-generated special
  8277. /// member functions -- are put in the specified segment."
  8278. /// The actual behavior is a little more complicated. The Microsoft compiler
  8279. /// won't check outer classes if there is an active value from #pragma code_seg.
  8280. /// The CodeSeg is always applied from the direct parent but only from outer
  8281. /// classes when the #pragma code_seg stack is empty. See:
  8282. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8283. /// available since MS has removed the page.
  8284. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8285. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8286. if (!Method)
  8287. return nullptr;
  8288. const CXXRecordDecl *Parent = Method->getParent();
  8289. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8290. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8291. NewAttr->setImplicit(true);
  8292. return NewAttr;
  8293. }
  8294. // The Microsoft compiler won't check outer classes for the CodeSeg
  8295. // when the #pragma code_seg stack is active.
  8296. if (S.CodeSegStack.CurrentValue)
  8297. return nullptr;
  8298. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8299. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8300. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8301. NewAttr->setImplicit(true);
  8302. return NewAttr;
  8303. }
  8304. }
  8305. return nullptr;
  8306. }
  8307. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8308. /// containing class. Otherwise it will return implicit SectionAttr if the
  8309. /// function is a definition and there is an active value on CodeSegStack
  8310. /// (from the current #pragma code-seg value).
  8311. ///
  8312. /// \param FD Function being declared.
  8313. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8314. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8315. /// nullptr if no attribute should be added.
  8316. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8317. bool IsDefinition) {
  8318. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8319. return A;
  8320. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8321. CodeSegStack.CurrentValue) {
  8322. return SectionAttr::CreateImplicit(getASTContext(),
  8323. SectionAttr::Declspec_allocate,
  8324. CodeSegStack.CurrentValue->getString(),
  8325. CodeSegStack.CurrentPragmaLocation);
  8326. }
  8327. return nullptr;
  8328. }
  8329. /// Determines if we can perform a correct type check for \p D as a
  8330. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8331. /// best-effort check.
  8332. ///
  8333. /// \param NewD The new declaration.
  8334. /// \param OldD The old declaration.
  8335. /// \param NewT The portion of the type of the new declaration to check.
  8336. /// \param OldT The portion of the type of the old declaration to check.
  8337. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8338. QualType NewT, QualType OldT) {
  8339. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8340. return true;
  8341. // For dependently-typed local extern declarations and friends, we can't
  8342. // perform a correct type check in general until instantiation:
  8343. //
  8344. // int f();
  8345. // template<typename T> void g() { T f(); }
  8346. //
  8347. // (valid if g() is only instantiated with T = int).
  8348. if (NewT->isDependentType() &&
  8349. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8350. return false;
  8351. // Similarly, if the previous declaration was a dependent local extern
  8352. // declaration, we don't really know its type yet.
  8353. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8354. return false;
  8355. return true;
  8356. }
  8357. /// Checks if the new declaration declared in dependent context must be
  8358. /// put in the same redeclaration chain as the specified declaration.
  8359. ///
  8360. /// \param D Declaration that is checked.
  8361. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8362. /// same declaration name.
  8363. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8364. /// belongs to.
  8365. ///
  8366. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8367. if (!D->getLexicalDeclContext()->isDependentContext())
  8368. return true;
  8369. // Don't chain dependent friend function definitions until instantiation, to
  8370. // permit cases like
  8371. //
  8372. // void func();
  8373. // template<typename T> class C1 { friend void func() {} };
  8374. // template<typename T> class C2 { friend void func() {} };
  8375. //
  8376. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8377. //
  8378. // FIXME: This need only apply to function definitions. For now, we proxy
  8379. // this by checking for a file-scope function. We do not want this to apply
  8380. // to friend declarations nominating member functions, because that gets in
  8381. // the way of access checks.
  8382. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8383. return false;
  8384. auto *VD = dyn_cast<ValueDecl>(D);
  8385. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8386. return !VD || !PrevVD ||
  8387. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8388. PrevVD->getType());
  8389. }
  8390. /// Check the target attribute of the function for MultiVersion
  8391. /// validity.
  8392. ///
  8393. /// Returns true if there was an error, false otherwise.
  8394. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8395. const auto *TA = FD->getAttr<TargetAttr>();
  8396. assert(TA && "MultiVersion Candidate requires a target attribute");
  8397. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8398. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8399. enum ErrType { Feature = 0, Architecture = 1 };
  8400. if (!ParseInfo.Architecture.empty() &&
  8401. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8402. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8403. << Architecture << ParseInfo.Architecture;
  8404. return true;
  8405. }
  8406. for (const auto &Feat : ParseInfo.Features) {
  8407. auto BareFeat = StringRef{Feat}.substr(1);
  8408. if (Feat[0] == '-') {
  8409. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8410. << Feature << ("no-" + BareFeat).str();
  8411. return true;
  8412. }
  8413. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8414. !TargetInfo.isValidFeatureName(BareFeat)) {
  8415. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8416. << Feature << BareFeat;
  8417. return true;
  8418. }
  8419. }
  8420. return false;
  8421. }
  8422. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8423. MultiVersionKind MVType) {
  8424. for (const Attr *A : FD->attrs()) {
  8425. switch (A->getKind()) {
  8426. case attr::CPUDispatch:
  8427. case attr::CPUSpecific:
  8428. if (MVType != MultiVersionKind::CPUDispatch &&
  8429. MVType != MultiVersionKind::CPUSpecific)
  8430. return true;
  8431. break;
  8432. case attr::Target:
  8433. if (MVType != MultiVersionKind::Target)
  8434. return true;
  8435. break;
  8436. default:
  8437. return true;
  8438. }
  8439. }
  8440. return false;
  8441. }
  8442. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8443. const FunctionDecl *NewFD,
  8444. bool CausesMV,
  8445. MultiVersionKind MVType) {
  8446. enum DoesntSupport {
  8447. FuncTemplates = 0,
  8448. VirtFuncs = 1,
  8449. DeducedReturn = 2,
  8450. Constructors = 3,
  8451. Destructors = 4,
  8452. DeletedFuncs = 5,
  8453. DefaultedFuncs = 6,
  8454. ConstexprFuncs = 7,
  8455. ConstevalFuncs = 8,
  8456. };
  8457. enum Different {
  8458. CallingConv = 0,
  8459. ReturnType = 1,
  8460. ConstexprSpec = 2,
  8461. InlineSpec = 3,
  8462. StorageClass = 4,
  8463. Linkage = 5
  8464. };
  8465. bool IsCPUSpecificCPUDispatchMVType =
  8466. MVType == MultiVersionKind::CPUDispatch ||
  8467. MVType == MultiVersionKind::CPUSpecific;
  8468. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8469. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8470. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8471. return true;
  8472. }
  8473. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8474. return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8475. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8476. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8477. if (OldFD)
  8478. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8479. return true;
  8480. }
  8481. // For now, disallow all other attributes. These should be opt-in, but
  8482. // an analysis of all of them is a future FIXME.
  8483. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8484. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8485. << IsCPUSpecificCPUDispatchMVType;
  8486. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8487. return true;
  8488. }
  8489. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8490. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8491. << IsCPUSpecificCPUDispatchMVType;
  8492. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8493. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8494. << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
  8495. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8496. if (NewCXXFD->isVirtual())
  8497. return S.Diag(NewCXXFD->getLocation(),
  8498. diag::err_multiversion_doesnt_support)
  8499. << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
  8500. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8501. return S.Diag(NewCXXCtor->getLocation(),
  8502. diag::err_multiversion_doesnt_support)
  8503. << IsCPUSpecificCPUDispatchMVType << Constructors;
  8504. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8505. return S.Diag(NewCXXDtor->getLocation(),
  8506. diag::err_multiversion_doesnt_support)
  8507. << IsCPUSpecificCPUDispatchMVType << Destructors;
  8508. }
  8509. if (NewFD->isDeleted())
  8510. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8511. << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
  8512. if (NewFD->isDefaulted())
  8513. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8514. << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
  8515. if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
  8516. MVType == MultiVersionKind::CPUSpecific))
  8517. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8518. << IsCPUSpecificCPUDispatchMVType
  8519. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  8520. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8521. const auto *NewType = cast<FunctionType>(NewQType);
  8522. QualType NewReturnType = NewType->getReturnType();
  8523. if (NewReturnType->isUndeducedType())
  8524. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8525. << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
  8526. // Only allow transition to MultiVersion if it hasn't been used.
  8527. if (OldFD && CausesMV && OldFD->isUsed(false))
  8528. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8529. // Ensure the return type is identical.
  8530. if (OldFD) {
  8531. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8532. const auto *OldType = cast<FunctionType>(OldQType);
  8533. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8534. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8535. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8536. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8537. << CallingConv;
  8538. QualType OldReturnType = OldType->getReturnType();
  8539. if (OldReturnType != NewReturnType)
  8540. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8541. << ReturnType;
  8542. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  8543. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8544. << ConstexprSpec;
  8545. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8546. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8547. << InlineSpec;
  8548. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8549. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8550. << StorageClass;
  8551. if (OldFD->isExternC() != NewFD->isExternC())
  8552. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8553. << Linkage;
  8554. if (S.CheckEquivalentExceptionSpec(
  8555. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8556. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8557. return true;
  8558. }
  8559. return false;
  8560. }
  8561. /// Check the validity of a multiversion function declaration that is the
  8562. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8563. ///
  8564. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8565. ///
  8566. /// Returns true if there was an error, false otherwise.
  8567. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8568. MultiVersionKind MVType,
  8569. const TargetAttr *TA) {
  8570. assert(MVType != MultiVersionKind::None &&
  8571. "Function lacks multiversion attribute");
  8572. // Target only causes MV if it is default, otherwise this is a normal
  8573. // function.
  8574. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8575. return false;
  8576. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8577. FD->setInvalidDecl();
  8578. return true;
  8579. }
  8580. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8581. FD->setInvalidDecl();
  8582. return true;
  8583. }
  8584. FD->setIsMultiVersion();
  8585. return false;
  8586. }
  8587. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8588. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8589. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8590. return true;
  8591. }
  8592. return false;
  8593. }
  8594. static bool CheckTargetCausesMultiVersioning(
  8595. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8596. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8597. LookupResult &Previous) {
  8598. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8599. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8600. // Sort order doesn't matter, it just needs to be consistent.
  8601. llvm::sort(NewParsed.Features);
  8602. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8603. // to change, this is a simple redeclaration.
  8604. if (!NewTA->isDefaultVersion() &&
  8605. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8606. return false;
  8607. // Otherwise, this decl causes MultiVersioning.
  8608. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8609. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8610. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8611. NewFD->setInvalidDecl();
  8612. return true;
  8613. }
  8614. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8615. MultiVersionKind::Target)) {
  8616. NewFD->setInvalidDecl();
  8617. return true;
  8618. }
  8619. if (CheckMultiVersionValue(S, NewFD)) {
  8620. NewFD->setInvalidDecl();
  8621. return true;
  8622. }
  8623. // If this is 'default', permit the forward declaration.
  8624. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8625. Redeclaration = true;
  8626. OldDecl = OldFD;
  8627. OldFD->setIsMultiVersion();
  8628. NewFD->setIsMultiVersion();
  8629. return false;
  8630. }
  8631. if (CheckMultiVersionValue(S, OldFD)) {
  8632. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8633. NewFD->setInvalidDecl();
  8634. return true;
  8635. }
  8636. TargetAttr::ParsedTargetAttr OldParsed =
  8637. OldTA->parse(std::less<std::string>());
  8638. if (OldParsed == NewParsed) {
  8639. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8640. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8641. NewFD->setInvalidDecl();
  8642. return true;
  8643. }
  8644. for (const auto *FD : OldFD->redecls()) {
  8645. const auto *CurTA = FD->getAttr<TargetAttr>();
  8646. // We allow forward declarations before ANY multiversioning attributes, but
  8647. // nothing after the fact.
  8648. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8649. (!CurTA || CurTA->isInherited())) {
  8650. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8651. << 0;
  8652. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8653. NewFD->setInvalidDecl();
  8654. return true;
  8655. }
  8656. }
  8657. OldFD->setIsMultiVersion();
  8658. NewFD->setIsMultiVersion();
  8659. Redeclaration = false;
  8660. MergeTypeWithPrevious = false;
  8661. OldDecl = nullptr;
  8662. Previous.clear();
  8663. return false;
  8664. }
  8665. /// Check the validity of a new function declaration being added to an existing
  8666. /// multiversioned declaration collection.
  8667. static bool CheckMultiVersionAdditionalDecl(
  8668. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8669. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8670. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8671. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8672. LookupResult &Previous) {
  8673. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8674. // Disallow mixing of multiversioning types.
  8675. if ((OldMVType == MultiVersionKind::Target &&
  8676. NewMVType != MultiVersionKind::Target) ||
  8677. (NewMVType == MultiVersionKind::Target &&
  8678. OldMVType != MultiVersionKind::Target)) {
  8679. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8680. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8681. NewFD->setInvalidDecl();
  8682. return true;
  8683. }
  8684. TargetAttr::ParsedTargetAttr NewParsed;
  8685. if (NewTA) {
  8686. NewParsed = NewTA->parse();
  8687. llvm::sort(NewParsed.Features);
  8688. }
  8689. bool UseMemberUsingDeclRules =
  8690. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8691. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8692. // previous member of the MultiVersion set.
  8693. for (NamedDecl *ND : Previous) {
  8694. FunctionDecl *CurFD = ND->getAsFunction();
  8695. if (!CurFD)
  8696. continue;
  8697. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8698. continue;
  8699. if (NewMVType == MultiVersionKind::Target) {
  8700. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8701. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8702. NewFD->setIsMultiVersion();
  8703. Redeclaration = true;
  8704. OldDecl = ND;
  8705. return false;
  8706. }
  8707. TargetAttr::ParsedTargetAttr CurParsed =
  8708. CurTA->parse(std::less<std::string>());
  8709. if (CurParsed == NewParsed) {
  8710. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8711. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8712. NewFD->setInvalidDecl();
  8713. return true;
  8714. }
  8715. } else {
  8716. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8717. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8718. // Handle CPUDispatch/CPUSpecific versions.
  8719. // Only 1 CPUDispatch function is allowed, this will make it go through
  8720. // the redeclaration errors.
  8721. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8722. CurFD->hasAttr<CPUDispatchAttr>()) {
  8723. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8724. std::equal(
  8725. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8726. NewCPUDisp->cpus_begin(),
  8727. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8728. return Cur->getName() == New->getName();
  8729. })) {
  8730. NewFD->setIsMultiVersion();
  8731. Redeclaration = true;
  8732. OldDecl = ND;
  8733. return false;
  8734. }
  8735. // If the declarations don't match, this is an error condition.
  8736. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8737. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8738. NewFD->setInvalidDecl();
  8739. return true;
  8740. }
  8741. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8742. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8743. std::equal(
  8744. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8745. NewCPUSpec->cpus_begin(),
  8746. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8747. return Cur->getName() == New->getName();
  8748. })) {
  8749. NewFD->setIsMultiVersion();
  8750. Redeclaration = true;
  8751. OldDecl = ND;
  8752. return false;
  8753. }
  8754. // Only 1 version of CPUSpecific is allowed for each CPU.
  8755. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8756. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8757. if (CurII == NewII) {
  8758. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8759. << NewII;
  8760. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8761. NewFD->setInvalidDecl();
  8762. return true;
  8763. }
  8764. }
  8765. }
  8766. }
  8767. // If the two decls aren't the same MVType, there is no possible error
  8768. // condition.
  8769. }
  8770. }
  8771. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8772. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8773. // handled in the attribute adding step.
  8774. if (NewMVType == MultiVersionKind::Target &&
  8775. CheckMultiVersionValue(S, NewFD)) {
  8776. NewFD->setInvalidDecl();
  8777. return true;
  8778. }
  8779. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8780. !OldFD->isMultiVersion(), NewMVType)) {
  8781. NewFD->setInvalidDecl();
  8782. return true;
  8783. }
  8784. // Permit forward declarations in the case where these two are compatible.
  8785. if (!OldFD->isMultiVersion()) {
  8786. OldFD->setIsMultiVersion();
  8787. NewFD->setIsMultiVersion();
  8788. Redeclaration = true;
  8789. OldDecl = OldFD;
  8790. return false;
  8791. }
  8792. NewFD->setIsMultiVersion();
  8793. Redeclaration = false;
  8794. MergeTypeWithPrevious = false;
  8795. OldDecl = nullptr;
  8796. Previous.clear();
  8797. return false;
  8798. }
  8799. /// Check the validity of a mulitversion function declaration.
  8800. /// Also sets the multiversion'ness' of the function itself.
  8801. ///
  8802. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8803. ///
  8804. /// Returns true if there was an error, false otherwise.
  8805. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8806. bool &Redeclaration, NamedDecl *&OldDecl,
  8807. bool &MergeTypeWithPrevious,
  8808. LookupResult &Previous) {
  8809. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8810. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8811. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8812. // Mixing Multiversioning types is prohibited.
  8813. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8814. (NewCPUDisp && NewCPUSpec)) {
  8815. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8816. NewFD->setInvalidDecl();
  8817. return true;
  8818. }
  8819. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8820. // Main isn't allowed to become a multiversion function, however it IS
  8821. // permitted to have 'main' be marked with the 'target' optimization hint.
  8822. if (NewFD->isMain()) {
  8823. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8824. MVType == MultiVersionKind::CPUDispatch ||
  8825. MVType == MultiVersionKind::CPUSpecific) {
  8826. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8827. NewFD->setInvalidDecl();
  8828. return true;
  8829. }
  8830. return false;
  8831. }
  8832. if (!OldDecl || !OldDecl->getAsFunction() ||
  8833. OldDecl->getDeclContext()->getRedeclContext() !=
  8834. NewFD->getDeclContext()->getRedeclContext()) {
  8835. // If there's no previous declaration, AND this isn't attempting to cause
  8836. // multiversioning, this isn't an error condition.
  8837. if (MVType == MultiVersionKind::None)
  8838. return false;
  8839. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  8840. }
  8841. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8842. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8843. return false;
  8844. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8845. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8846. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8847. NewFD->setInvalidDecl();
  8848. return true;
  8849. }
  8850. // Handle the target potentially causes multiversioning case.
  8851. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8852. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8853. Redeclaration, OldDecl,
  8854. MergeTypeWithPrevious, Previous);
  8855. // At this point, we have a multiversion function decl (in OldFD) AND an
  8856. // appropriate attribute in the current function decl. Resolve that these are
  8857. // still compatible with previous declarations.
  8858. return CheckMultiVersionAdditionalDecl(
  8859. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8860. OldDecl, MergeTypeWithPrevious, Previous);
  8861. }
  8862. /// Perform semantic checking of a new function declaration.
  8863. ///
  8864. /// Performs semantic analysis of the new function declaration
  8865. /// NewFD. This routine performs all semantic checking that does not
  8866. /// require the actual declarator involved in the declaration, and is
  8867. /// used both for the declaration of functions as they are parsed
  8868. /// (called via ActOnDeclarator) and for the declaration of functions
  8869. /// that have been instantiated via C++ template instantiation (called
  8870. /// via InstantiateDecl).
  8871. ///
  8872. /// \param IsMemberSpecialization whether this new function declaration is
  8873. /// a member specialization (that replaces any definition provided by the
  8874. /// previous declaration).
  8875. ///
  8876. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8877. ///
  8878. /// \returns true if the function declaration is a redeclaration.
  8879. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8880. LookupResult &Previous,
  8881. bool IsMemberSpecialization) {
  8882. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8883. "Variably modified return types are not handled here");
  8884. // Determine whether the type of this function should be merged with
  8885. // a previous visible declaration. This never happens for functions in C++,
  8886. // and always happens in C if the previous declaration was visible.
  8887. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8888. !Previous.isShadowed();
  8889. bool Redeclaration = false;
  8890. NamedDecl *OldDecl = nullptr;
  8891. bool MayNeedOverloadableChecks = false;
  8892. // Merge or overload the declaration with an existing declaration of
  8893. // the same name, if appropriate.
  8894. if (!Previous.empty()) {
  8895. // Determine whether NewFD is an overload of PrevDecl or
  8896. // a declaration that requires merging. If it's an overload,
  8897. // there's no more work to do here; we'll just add the new
  8898. // function to the scope.
  8899. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8900. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8901. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8902. Redeclaration = true;
  8903. OldDecl = Candidate;
  8904. }
  8905. } else {
  8906. MayNeedOverloadableChecks = true;
  8907. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8908. /*NewIsUsingDecl*/ false)) {
  8909. case Ovl_Match:
  8910. Redeclaration = true;
  8911. break;
  8912. case Ovl_NonFunction:
  8913. Redeclaration = true;
  8914. break;
  8915. case Ovl_Overload:
  8916. Redeclaration = false;
  8917. break;
  8918. }
  8919. }
  8920. }
  8921. // Check for a previous extern "C" declaration with this name.
  8922. if (!Redeclaration &&
  8923. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8924. if (!Previous.empty()) {
  8925. // This is an extern "C" declaration with the same name as a previous
  8926. // declaration, and thus redeclares that entity...
  8927. Redeclaration = true;
  8928. OldDecl = Previous.getFoundDecl();
  8929. MergeTypeWithPrevious = false;
  8930. // ... except in the presence of __attribute__((overloadable)).
  8931. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8932. NewFD->hasAttr<OverloadableAttr>()) {
  8933. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8934. MayNeedOverloadableChecks = true;
  8935. Redeclaration = false;
  8936. OldDecl = nullptr;
  8937. }
  8938. }
  8939. }
  8940. }
  8941. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  8942. MergeTypeWithPrevious, Previous))
  8943. return Redeclaration;
  8944. // C++11 [dcl.constexpr]p8:
  8945. // A constexpr specifier for a non-static member function that is not
  8946. // a constructor declares that member function to be const.
  8947. //
  8948. // This needs to be delayed until we know whether this is an out-of-line
  8949. // definition of a static member function.
  8950. //
  8951. // This rule is not present in C++1y, so we produce a backwards
  8952. // compatibility warning whenever it happens in C++11.
  8953. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8954. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8955. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8956. !MD->getMethodQualifiers().hasConst()) {
  8957. CXXMethodDecl *OldMD = nullptr;
  8958. if (OldDecl)
  8959. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8960. if (!OldMD || !OldMD->isStatic()) {
  8961. const FunctionProtoType *FPT =
  8962. MD->getType()->castAs<FunctionProtoType>();
  8963. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8964. EPI.TypeQuals.addConst();
  8965. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8966. FPT->getParamTypes(), EPI));
  8967. // Warn that we did this, if we're not performing template instantiation.
  8968. // In that case, we'll have warned already when the template was defined.
  8969. if (!inTemplateInstantiation()) {
  8970. SourceLocation AddConstLoc;
  8971. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8972. .IgnoreParens().getAs<FunctionTypeLoc>())
  8973. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8974. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8975. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8976. }
  8977. }
  8978. }
  8979. if (Redeclaration) {
  8980. // NewFD and OldDecl represent declarations that need to be
  8981. // merged.
  8982. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8983. NewFD->setInvalidDecl();
  8984. return Redeclaration;
  8985. }
  8986. Previous.clear();
  8987. Previous.addDecl(OldDecl);
  8988. if (FunctionTemplateDecl *OldTemplateDecl =
  8989. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8990. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  8991. FunctionTemplateDecl *NewTemplateDecl
  8992. = NewFD->getDescribedFunctionTemplate();
  8993. assert(NewTemplateDecl && "Template/non-template mismatch");
  8994. // The call to MergeFunctionDecl above may have created some state in
  8995. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  8996. // can add it as a redeclaration.
  8997. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  8998. NewFD->setPreviousDeclaration(OldFD);
  8999. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9000. if (NewFD->isCXXClassMember()) {
  9001. NewFD->setAccess(OldTemplateDecl->getAccess());
  9002. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9003. }
  9004. // If this is an explicit specialization of a member that is a function
  9005. // template, mark it as a member specialization.
  9006. if (IsMemberSpecialization &&
  9007. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9008. NewTemplateDecl->setMemberSpecialization();
  9009. assert(OldTemplateDecl->isMemberSpecialization());
  9010. // Explicit specializations of a member template do not inherit deleted
  9011. // status from the parent member template that they are specializing.
  9012. if (OldFD->isDeleted()) {
  9013. // FIXME: This assert will not hold in the presence of modules.
  9014. assert(OldFD->getCanonicalDecl() == OldFD);
  9015. // FIXME: We need an update record for this AST mutation.
  9016. OldFD->setDeletedAsWritten(false);
  9017. }
  9018. }
  9019. } else {
  9020. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9021. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9022. // This needs to happen first so that 'inline' propagates.
  9023. NewFD->setPreviousDeclaration(OldFD);
  9024. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9025. if (NewFD->isCXXClassMember())
  9026. NewFD->setAccess(OldFD->getAccess());
  9027. }
  9028. }
  9029. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9030. !NewFD->getAttr<OverloadableAttr>()) {
  9031. assert((Previous.empty() ||
  9032. llvm::any_of(Previous,
  9033. [](const NamedDecl *ND) {
  9034. return ND->hasAttr<OverloadableAttr>();
  9035. })) &&
  9036. "Non-redecls shouldn't happen without overloadable present");
  9037. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9038. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9039. return FD && !FD->hasAttr<OverloadableAttr>();
  9040. });
  9041. if (OtherUnmarkedIter != Previous.end()) {
  9042. Diag(NewFD->getLocation(),
  9043. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9044. Diag((*OtherUnmarkedIter)->getLocation(),
  9045. diag::note_attribute_overloadable_prev_overload)
  9046. << false;
  9047. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9048. }
  9049. }
  9050. // Semantic checking for this function declaration (in isolation).
  9051. if (getLangOpts().CPlusPlus) {
  9052. // C++-specific checks.
  9053. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9054. CheckConstructor(Constructor);
  9055. } else if (CXXDestructorDecl *Destructor =
  9056. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9057. CXXRecordDecl *Record = Destructor->getParent();
  9058. QualType ClassType = Context.getTypeDeclType(Record);
  9059. // FIXME: Shouldn't we be able to perform this check even when the class
  9060. // type is dependent? Both gcc and edg can handle that.
  9061. if (!ClassType->isDependentType()) {
  9062. DeclarationName Name
  9063. = Context.DeclarationNames.getCXXDestructorName(
  9064. Context.getCanonicalType(ClassType));
  9065. if (NewFD->getDeclName() != Name) {
  9066. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9067. NewFD->setInvalidDecl();
  9068. return Redeclaration;
  9069. }
  9070. }
  9071. } else if (CXXConversionDecl *Conversion
  9072. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9073. ActOnConversionDeclarator(Conversion);
  9074. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9075. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9076. CheckDeductionGuideTemplate(TD);
  9077. // A deduction guide is not on the list of entities that can be
  9078. // explicitly specialized.
  9079. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9080. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9081. << /*explicit specialization*/ 1;
  9082. }
  9083. // Find any virtual functions that this function overrides.
  9084. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9085. if (!Method->isFunctionTemplateSpecialization() &&
  9086. !Method->getDescribedFunctionTemplate() &&
  9087. Method->isCanonicalDecl()) {
  9088. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9089. // If the function was marked as "static", we have a problem.
  9090. if (NewFD->getStorageClass() == SC_Static) {
  9091. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9092. }
  9093. }
  9094. }
  9095. if (Method->isStatic())
  9096. checkThisInStaticMemberFunctionType(Method);
  9097. }
  9098. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9099. if (NewFD->isOverloadedOperator() &&
  9100. CheckOverloadedOperatorDeclaration(NewFD)) {
  9101. NewFD->setInvalidDecl();
  9102. return Redeclaration;
  9103. }
  9104. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9105. if (NewFD->getLiteralIdentifier() &&
  9106. CheckLiteralOperatorDeclaration(NewFD)) {
  9107. NewFD->setInvalidDecl();
  9108. return Redeclaration;
  9109. }
  9110. // In C++, check default arguments now that we have merged decls. Unless
  9111. // the lexical context is the class, because in this case this is done
  9112. // during delayed parsing anyway.
  9113. if (!CurContext->isRecord())
  9114. CheckCXXDefaultArguments(NewFD);
  9115. // If this function declares a builtin function, check the type of this
  9116. // declaration against the expected type for the builtin.
  9117. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9118. ASTContext::GetBuiltinTypeError Error;
  9119. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9120. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9121. // If the type of the builtin differs only in its exception
  9122. // specification, that's OK.
  9123. // FIXME: If the types do differ in this way, it would be better to
  9124. // retain the 'noexcept' form of the type.
  9125. if (!T.isNull() &&
  9126. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9127. NewFD->getType()))
  9128. // The type of this function differs from the type of the builtin,
  9129. // so forget about the builtin entirely.
  9130. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9131. }
  9132. // If this function is declared as being extern "C", then check to see if
  9133. // the function returns a UDT (class, struct, or union type) that is not C
  9134. // compatible, and if it does, warn the user.
  9135. // But, issue any diagnostic on the first declaration only.
  9136. if (Previous.empty() && NewFD->isExternC()) {
  9137. QualType R = NewFD->getReturnType();
  9138. if (R->isIncompleteType() && !R->isVoidType())
  9139. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9140. << NewFD << R;
  9141. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9142. !R->isObjCObjectPointerType())
  9143. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9144. }
  9145. // C++1z [dcl.fct]p6:
  9146. // [...] whether the function has a non-throwing exception-specification
  9147. // [is] part of the function type
  9148. //
  9149. // This results in an ABI break between C++14 and C++17 for functions whose
  9150. // declared type includes an exception-specification in a parameter or
  9151. // return type. (Exception specifications on the function itself are OK in
  9152. // most cases, and exception specifications are not permitted in most other
  9153. // contexts where they could make it into a mangling.)
  9154. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9155. auto HasNoexcept = [&](QualType T) -> bool {
  9156. // Strip off declarator chunks that could be between us and a function
  9157. // type. We don't need to look far, exception specifications are very
  9158. // restricted prior to C++17.
  9159. if (auto *RT = T->getAs<ReferenceType>())
  9160. T = RT->getPointeeType();
  9161. else if (T->isAnyPointerType())
  9162. T = T->getPointeeType();
  9163. else if (auto *MPT = T->getAs<MemberPointerType>())
  9164. T = MPT->getPointeeType();
  9165. if (auto *FPT = T->getAs<FunctionProtoType>())
  9166. if (FPT->isNothrow())
  9167. return true;
  9168. return false;
  9169. };
  9170. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9171. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9172. for (QualType T : FPT->param_types())
  9173. AnyNoexcept |= HasNoexcept(T);
  9174. if (AnyNoexcept)
  9175. Diag(NewFD->getLocation(),
  9176. diag::warn_cxx17_compat_exception_spec_in_signature)
  9177. << NewFD;
  9178. }
  9179. if (!Redeclaration && LangOpts.CUDA)
  9180. checkCUDATargetOverload(NewFD, Previous);
  9181. }
  9182. return Redeclaration;
  9183. }
  9184. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9185. // C++11 [basic.start.main]p3:
  9186. // A program that [...] declares main to be inline, static or
  9187. // constexpr is ill-formed.
  9188. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9189. // appear in a declaration of main.
  9190. // static main is not an error under C99, but we should warn about it.
  9191. // We accept _Noreturn main as an extension.
  9192. if (FD->getStorageClass() == SC_Static)
  9193. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9194. ? diag::err_static_main : diag::warn_static_main)
  9195. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9196. if (FD->isInlineSpecified())
  9197. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9198. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9199. if (DS.isNoreturnSpecified()) {
  9200. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9201. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9202. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9203. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9204. << FixItHint::CreateRemoval(NoreturnRange);
  9205. }
  9206. if (FD->isConstexpr()) {
  9207. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9208. << FD->isConsteval()
  9209. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9210. FD->setConstexprKind(CSK_unspecified);
  9211. }
  9212. if (getLangOpts().OpenCL) {
  9213. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9214. << FD->hasAttr<OpenCLKernelAttr>();
  9215. FD->setInvalidDecl();
  9216. return;
  9217. }
  9218. QualType T = FD->getType();
  9219. assert(T->isFunctionType() && "function decl is not of function type");
  9220. const FunctionType* FT = T->castAs<FunctionType>();
  9221. // Set default calling convention for main()
  9222. if (FT->getCallConv() != CC_C) {
  9223. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9224. FD->setType(QualType(FT, 0));
  9225. T = Context.getCanonicalType(FD->getType());
  9226. }
  9227. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9228. // In C with GNU extensions we allow main() to have non-integer return
  9229. // type, but we should warn about the extension, and we disable the
  9230. // implicit-return-zero rule.
  9231. // GCC in C mode accepts qualified 'int'.
  9232. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9233. FD->setHasImplicitReturnZero(true);
  9234. else {
  9235. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9236. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9237. if (RTRange.isValid())
  9238. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9239. << FixItHint::CreateReplacement(RTRange, "int");
  9240. }
  9241. } else {
  9242. // In C and C++, main magically returns 0 if you fall off the end;
  9243. // set the flag which tells us that.
  9244. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9245. // All the standards say that main() should return 'int'.
  9246. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9247. FD->setHasImplicitReturnZero(true);
  9248. else {
  9249. // Otherwise, this is just a flat-out error.
  9250. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9251. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9252. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9253. : FixItHint());
  9254. FD->setInvalidDecl(true);
  9255. }
  9256. }
  9257. // Treat protoless main() as nullary.
  9258. if (isa<FunctionNoProtoType>(FT)) return;
  9259. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9260. unsigned nparams = FTP->getNumParams();
  9261. assert(FD->getNumParams() == nparams);
  9262. bool HasExtraParameters = (nparams > 3);
  9263. if (FTP->isVariadic()) {
  9264. Diag(FD->getLocation(), diag::ext_variadic_main);
  9265. // FIXME: if we had information about the location of the ellipsis, we
  9266. // could add a FixIt hint to remove it as a parameter.
  9267. }
  9268. // Darwin passes an undocumented fourth argument of type char**. If
  9269. // other platforms start sprouting these, the logic below will start
  9270. // getting shifty.
  9271. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9272. HasExtraParameters = false;
  9273. if (HasExtraParameters) {
  9274. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9275. FD->setInvalidDecl(true);
  9276. nparams = 3;
  9277. }
  9278. // FIXME: a lot of the following diagnostics would be improved
  9279. // if we had some location information about types.
  9280. QualType CharPP =
  9281. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9282. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9283. for (unsigned i = 0; i < nparams; ++i) {
  9284. QualType AT = FTP->getParamType(i);
  9285. bool mismatch = true;
  9286. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9287. mismatch = false;
  9288. else if (Expected[i] == CharPP) {
  9289. // As an extension, the following forms are okay:
  9290. // char const **
  9291. // char const * const *
  9292. // char * const *
  9293. QualifierCollector qs;
  9294. const PointerType* PT;
  9295. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9296. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9297. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9298. Context.CharTy)) {
  9299. qs.removeConst();
  9300. mismatch = !qs.empty();
  9301. }
  9302. }
  9303. if (mismatch) {
  9304. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9305. // TODO: suggest replacing given type with expected type
  9306. FD->setInvalidDecl(true);
  9307. }
  9308. }
  9309. if (nparams == 1 && !FD->isInvalidDecl()) {
  9310. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9311. }
  9312. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9313. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9314. FD->setInvalidDecl();
  9315. }
  9316. }
  9317. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9318. QualType T = FD->getType();
  9319. assert(T->isFunctionType() && "function decl is not of function type");
  9320. const FunctionType *FT = T->castAs<FunctionType>();
  9321. // Set an implicit return of 'zero' if the function can return some integral,
  9322. // enumeration, pointer or nullptr type.
  9323. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9324. FT->getReturnType()->isAnyPointerType() ||
  9325. FT->getReturnType()->isNullPtrType())
  9326. // DllMain is exempt because a return value of zero means it failed.
  9327. if (FD->getName() != "DllMain")
  9328. FD->setHasImplicitReturnZero(true);
  9329. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9330. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9331. FD->setInvalidDecl();
  9332. }
  9333. }
  9334. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9335. // FIXME: Need strict checking. In C89, we need to check for
  9336. // any assignment, increment, decrement, function-calls, or
  9337. // commas outside of a sizeof. In C99, it's the same list,
  9338. // except that the aforementioned are allowed in unevaluated
  9339. // expressions. Everything else falls under the
  9340. // "may accept other forms of constant expressions" exception.
  9341. // (We never end up here for C++, so the constant expression
  9342. // rules there don't matter.)
  9343. const Expr *Culprit;
  9344. if (Init->isConstantInitializer(Context, false, &Culprit))
  9345. return false;
  9346. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9347. << Culprit->getSourceRange();
  9348. return true;
  9349. }
  9350. namespace {
  9351. // Visits an initialization expression to see if OrigDecl is evaluated in
  9352. // its own initialization and throws a warning if it does.
  9353. class SelfReferenceChecker
  9354. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9355. Sema &S;
  9356. Decl *OrigDecl;
  9357. bool isRecordType;
  9358. bool isPODType;
  9359. bool isReferenceType;
  9360. bool isInitList;
  9361. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9362. public:
  9363. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9364. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9365. S(S), OrigDecl(OrigDecl) {
  9366. isPODType = false;
  9367. isRecordType = false;
  9368. isReferenceType = false;
  9369. isInitList = false;
  9370. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9371. isPODType = VD->getType().isPODType(S.Context);
  9372. isRecordType = VD->getType()->isRecordType();
  9373. isReferenceType = VD->getType()->isReferenceType();
  9374. }
  9375. }
  9376. // For most expressions, just call the visitor. For initializer lists,
  9377. // track the index of the field being initialized since fields are
  9378. // initialized in order allowing use of previously initialized fields.
  9379. void CheckExpr(Expr *E) {
  9380. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9381. if (!InitList) {
  9382. Visit(E);
  9383. return;
  9384. }
  9385. // Track and increment the index here.
  9386. isInitList = true;
  9387. InitFieldIndex.push_back(0);
  9388. for (auto Child : InitList->children()) {
  9389. CheckExpr(cast<Expr>(Child));
  9390. ++InitFieldIndex.back();
  9391. }
  9392. InitFieldIndex.pop_back();
  9393. }
  9394. // Returns true if MemberExpr is checked and no further checking is needed.
  9395. // Returns false if additional checking is required.
  9396. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9397. llvm::SmallVector<FieldDecl*, 4> Fields;
  9398. Expr *Base = E;
  9399. bool ReferenceField = false;
  9400. // Get the field members used.
  9401. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9402. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9403. if (!FD)
  9404. return false;
  9405. Fields.push_back(FD);
  9406. if (FD->getType()->isReferenceType())
  9407. ReferenceField = true;
  9408. Base = ME->getBase()->IgnoreParenImpCasts();
  9409. }
  9410. // Keep checking only if the base Decl is the same.
  9411. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9412. if (!DRE || DRE->getDecl() != OrigDecl)
  9413. return false;
  9414. // A reference field can be bound to an unininitialized field.
  9415. if (CheckReference && !ReferenceField)
  9416. return true;
  9417. // Convert FieldDecls to their index number.
  9418. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9419. for (const FieldDecl *I : llvm::reverse(Fields))
  9420. UsedFieldIndex.push_back(I->getFieldIndex());
  9421. // See if a warning is needed by checking the first difference in index
  9422. // numbers. If field being used has index less than the field being
  9423. // initialized, then the use is safe.
  9424. for (auto UsedIter = UsedFieldIndex.begin(),
  9425. UsedEnd = UsedFieldIndex.end(),
  9426. OrigIter = InitFieldIndex.begin(),
  9427. OrigEnd = InitFieldIndex.end();
  9428. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9429. if (*UsedIter < *OrigIter)
  9430. return true;
  9431. if (*UsedIter > *OrigIter)
  9432. break;
  9433. }
  9434. // TODO: Add a different warning which will print the field names.
  9435. HandleDeclRefExpr(DRE);
  9436. return true;
  9437. }
  9438. // For most expressions, the cast is directly above the DeclRefExpr.
  9439. // For conditional operators, the cast can be outside the conditional
  9440. // operator if both expressions are DeclRefExpr's.
  9441. void HandleValue(Expr *E) {
  9442. E = E->IgnoreParens();
  9443. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9444. HandleDeclRefExpr(DRE);
  9445. return;
  9446. }
  9447. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9448. Visit(CO->getCond());
  9449. HandleValue(CO->getTrueExpr());
  9450. HandleValue(CO->getFalseExpr());
  9451. return;
  9452. }
  9453. if (BinaryConditionalOperator *BCO =
  9454. dyn_cast<BinaryConditionalOperator>(E)) {
  9455. Visit(BCO->getCond());
  9456. HandleValue(BCO->getFalseExpr());
  9457. return;
  9458. }
  9459. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9460. HandleValue(OVE->getSourceExpr());
  9461. return;
  9462. }
  9463. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9464. if (BO->getOpcode() == BO_Comma) {
  9465. Visit(BO->getLHS());
  9466. HandleValue(BO->getRHS());
  9467. return;
  9468. }
  9469. }
  9470. if (isa<MemberExpr>(E)) {
  9471. if (isInitList) {
  9472. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9473. false /*CheckReference*/))
  9474. return;
  9475. }
  9476. Expr *Base = E->IgnoreParenImpCasts();
  9477. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9478. // Check for static member variables and don't warn on them.
  9479. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9480. return;
  9481. Base = ME->getBase()->IgnoreParenImpCasts();
  9482. }
  9483. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9484. HandleDeclRefExpr(DRE);
  9485. return;
  9486. }
  9487. Visit(E);
  9488. }
  9489. // Reference types not handled in HandleValue are handled here since all
  9490. // uses of references are bad, not just r-value uses.
  9491. void VisitDeclRefExpr(DeclRefExpr *E) {
  9492. if (isReferenceType)
  9493. HandleDeclRefExpr(E);
  9494. }
  9495. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9496. if (E->getCastKind() == CK_LValueToRValue) {
  9497. HandleValue(E->getSubExpr());
  9498. return;
  9499. }
  9500. Inherited::VisitImplicitCastExpr(E);
  9501. }
  9502. void VisitMemberExpr(MemberExpr *E) {
  9503. if (isInitList) {
  9504. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9505. return;
  9506. }
  9507. // Don't warn on arrays since they can be treated as pointers.
  9508. if (E->getType()->canDecayToPointerType()) return;
  9509. // Warn when a non-static method call is followed by non-static member
  9510. // field accesses, which is followed by a DeclRefExpr.
  9511. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9512. bool Warn = (MD && !MD->isStatic());
  9513. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9514. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9515. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9516. Warn = false;
  9517. Base = ME->getBase()->IgnoreParenImpCasts();
  9518. }
  9519. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9520. if (Warn)
  9521. HandleDeclRefExpr(DRE);
  9522. return;
  9523. }
  9524. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9525. // Visit that expression.
  9526. Visit(Base);
  9527. }
  9528. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9529. Expr *Callee = E->getCallee();
  9530. if (isa<UnresolvedLookupExpr>(Callee))
  9531. return Inherited::VisitCXXOperatorCallExpr(E);
  9532. Visit(Callee);
  9533. for (auto Arg: E->arguments())
  9534. HandleValue(Arg->IgnoreParenImpCasts());
  9535. }
  9536. void VisitUnaryOperator(UnaryOperator *E) {
  9537. // For POD record types, addresses of its own members are well-defined.
  9538. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9539. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9540. if (!isPODType)
  9541. HandleValue(E->getSubExpr());
  9542. return;
  9543. }
  9544. if (E->isIncrementDecrementOp()) {
  9545. HandleValue(E->getSubExpr());
  9546. return;
  9547. }
  9548. Inherited::VisitUnaryOperator(E);
  9549. }
  9550. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9551. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9552. if (E->getConstructor()->isCopyConstructor()) {
  9553. Expr *ArgExpr = E->getArg(0);
  9554. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9555. if (ILE->getNumInits() == 1)
  9556. ArgExpr = ILE->getInit(0);
  9557. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9558. if (ICE->getCastKind() == CK_NoOp)
  9559. ArgExpr = ICE->getSubExpr();
  9560. HandleValue(ArgExpr);
  9561. return;
  9562. }
  9563. Inherited::VisitCXXConstructExpr(E);
  9564. }
  9565. void VisitCallExpr(CallExpr *E) {
  9566. // Treat std::move as a use.
  9567. if (E->isCallToStdMove()) {
  9568. HandleValue(E->getArg(0));
  9569. return;
  9570. }
  9571. Inherited::VisitCallExpr(E);
  9572. }
  9573. void VisitBinaryOperator(BinaryOperator *E) {
  9574. if (E->isCompoundAssignmentOp()) {
  9575. HandleValue(E->getLHS());
  9576. Visit(E->getRHS());
  9577. return;
  9578. }
  9579. Inherited::VisitBinaryOperator(E);
  9580. }
  9581. // A custom visitor for BinaryConditionalOperator is needed because the
  9582. // regular visitor would check the condition and true expression separately
  9583. // but both point to the same place giving duplicate diagnostics.
  9584. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9585. Visit(E->getCond());
  9586. Visit(E->getFalseExpr());
  9587. }
  9588. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9589. Decl* ReferenceDecl = DRE->getDecl();
  9590. if (OrigDecl != ReferenceDecl) return;
  9591. unsigned diag;
  9592. if (isReferenceType) {
  9593. diag = diag::warn_uninit_self_reference_in_reference_init;
  9594. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9595. diag = diag::warn_static_self_reference_in_init;
  9596. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9597. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9598. DRE->getDecl()->getType()->isRecordType()) {
  9599. diag = diag::warn_uninit_self_reference_in_init;
  9600. } else {
  9601. // Local variables will be handled by the CFG analysis.
  9602. return;
  9603. }
  9604. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9605. S.PDiag(diag)
  9606. << DRE->getDecl() << OrigDecl->getLocation()
  9607. << DRE->getSourceRange());
  9608. }
  9609. };
  9610. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9611. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9612. bool DirectInit) {
  9613. // Parameters arguments are occassionially constructed with itself,
  9614. // for instance, in recursive functions. Skip them.
  9615. if (isa<ParmVarDecl>(OrigDecl))
  9616. return;
  9617. E = E->IgnoreParens();
  9618. // Skip checking T a = a where T is not a record or reference type.
  9619. // Doing so is a way to silence uninitialized warnings.
  9620. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9621. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9622. if (ICE->getCastKind() == CK_LValueToRValue)
  9623. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9624. if (DRE->getDecl() == OrigDecl)
  9625. return;
  9626. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9627. }
  9628. } // end anonymous namespace
  9629. namespace {
  9630. // Simple wrapper to add the name of a variable or (if no variable is
  9631. // available) a DeclarationName into a diagnostic.
  9632. struct VarDeclOrName {
  9633. VarDecl *VDecl;
  9634. DeclarationName Name;
  9635. friend const Sema::SemaDiagnosticBuilder &
  9636. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9637. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9638. }
  9639. };
  9640. } // end anonymous namespace
  9641. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9642. DeclarationName Name, QualType Type,
  9643. TypeSourceInfo *TSI,
  9644. SourceRange Range, bool DirectInit,
  9645. Expr *Init) {
  9646. bool IsInitCapture = !VDecl;
  9647. assert((!VDecl || !VDecl->isInitCapture()) &&
  9648. "init captures are expected to be deduced prior to initialization");
  9649. VarDeclOrName VN{VDecl, Name};
  9650. DeducedType *Deduced = Type->getContainedDeducedType();
  9651. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9652. // C++11 [dcl.spec.auto]p3
  9653. if (!Init) {
  9654. assert(VDecl && "no init for init capture deduction?");
  9655. // Except for class argument deduction, and then for an initializing
  9656. // declaration only, i.e. no static at class scope or extern.
  9657. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9658. VDecl->hasExternalStorage() ||
  9659. VDecl->isStaticDataMember()) {
  9660. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9661. << VDecl->getDeclName() << Type;
  9662. return QualType();
  9663. }
  9664. }
  9665. ArrayRef<Expr*> DeduceInits;
  9666. if (Init)
  9667. DeduceInits = Init;
  9668. if (DirectInit) {
  9669. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9670. DeduceInits = PL->exprs();
  9671. }
  9672. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9673. assert(VDecl && "non-auto type for init capture deduction?");
  9674. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9675. InitializationKind Kind = InitializationKind::CreateForInit(
  9676. VDecl->getLocation(), DirectInit, Init);
  9677. // FIXME: Initialization should not be taking a mutable list of inits.
  9678. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9679. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9680. InitsCopy);
  9681. }
  9682. if (DirectInit) {
  9683. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9684. DeduceInits = IL->inits();
  9685. }
  9686. // Deduction only works if we have exactly one source expression.
  9687. if (DeduceInits.empty()) {
  9688. // It isn't possible to write this directly, but it is possible to
  9689. // end up in this situation with "auto x(some_pack...);"
  9690. Diag(Init->getBeginLoc(), IsInitCapture
  9691. ? diag::err_init_capture_no_expression
  9692. : diag::err_auto_var_init_no_expression)
  9693. << VN << Type << Range;
  9694. return QualType();
  9695. }
  9696. if (DeduceInits.size() > 1) {
  9697. Diag(DeduceInits[1]->getBeginLoc(),
  9698. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9699. : diag::err_auto_var_init_multiple_expressions)
  9700. << VN << Type << Range;
  9701. return QualType();
  9702. }
  9703. Expr *DeduceInit = DeduceInits[0];
  9704. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9705. Diag(Init->getBeginLoc(), IsInitCapture
  9706. ? diag::err_init_capture_paren_braces
  9707. : diag::err_auto_var_init_paren_braces)
  9708. << isa<InitListExpr>(Init) << VN << Type << Range;
  9709. return QualType();
  9710. }
  9711. // Expressions default to 'id' when we're in a debugger.
  9712. bool DefaultedAnyToId = false;
  9713. if (getLangOpts().DebuggerCastResultToId &&
  9714. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9715. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9716. if (Result.isInvalid()) {
  9717. return QualType();
  9718. }
  9719. Init = Result.get();
  9720. DefaultedAnyToId = true;
  9721. }
  9722. // C++ [dcl.decomp]p1:
  9723. // If the assignment-expression [...] has array type A and no ref-qualifier
  9724. // is present, e has type cv A
  9725. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9726. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9727. DeduceInit->getType()->isConstantArrayType())
  9728. return Context.getQualifiedType(DeduceInit->getType(),
  9729. Type.getQualifiers());
  9730. QualType DeducedType;
  9731. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9732. if (!IsInitCapture)
  9733. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9734. else if (isa<InitListExpr>(Init))
  9735. Diag(Range.getBegin(),
  9736. diag::err_init_capture_deduction_failure_from_init_list)
  9737. << VN
  9738. << (DeduceInit->getType().isNull() ? TSI->getType()
  9739. : DeduceInit->getType())
  9740. << DeduceInit->getSourceRange();
  9741. else
  9742. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9743. << VN << TSI->getType()
  9744. << (DeduceInit->getType().isNull() ? TSI->getType()
  9745. : DeduceInit->getType())
  9746. << DeduceInit->getSourceRange();
  9747. }
  9748. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9749. // 'id' instead of a specific object type prevents most of our usual
  9750. // checks.
  9751. // We only want to warn outside of template instantiations, though:
  9752. // inside a template, the 'id' could have come from a parameter.
  9753. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9754. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9755. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9756. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9757. }
  9758. return DeducedType;
  9759. }
  9760. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9761. Expr *Init) {
  9762. QualType DeducedType = deduceVarTypeFromInitializer(
  9763. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9764. VDecl->getSourceRange(), DirectInit, Init);
  9765. if (DeducedType.isNull()) {
  9766. VDecl->setInvalidDecl();
  9767. return true;
  9768. }
  9769. VDecl->setType(DeducedType);
  9770. assert(VDecl->isLinkageValid());
  9771. // In ARC, infer lifetime.
  9772. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9773. VDecl->setInvalidDecl();
  9774. // If this is a redeclaration, check that the type we just deduced matches
  9775. // the previously declared type.
  9776. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9777. // We never need to merge the type, because we cannot form an incomplete
  9778. // array of auto, nor deduce such a type.
  9779. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9780. }
  9781. // Check the deduced type is valid for a variable declaration.
  9782. CheckVariableDeclarationType(VDecl);
  9783. return VDecl->isInvalidDecl();
  9784. }
  9785. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  9786. SourceLocation Loc) {
  9787. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  9788. Init = CE->getSubExpr();
  9789. QualType InitType = Init->getType();
  9790. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9791. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9792. "shouldn't be called if type doesn't have a non-trivial C struct");
  9793. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  9794. for (auto I : ILE->inits()) {
  9795. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  9796. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  9797. continue;
  9798. SourceLocation SL = I->getExprLoc();
  9799. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  9800. }
  9801. return;
  9802. }
  9803. if (isa<ImplicitValueInitExpr>(Init)) {
  9804. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9805. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  9806. NTCUK_Init);
  9807. } else {
  9808. // Assume all other explicit initializers involving copying some existing
  9809. // object.
  9810. // TODO: ignore any explicit initializers where we can guarantee
  9811. // copy-elision.
  9812. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  9813. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  9814. }
  9815. }
  9816. namespace {
  9817. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  9818. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9819. void> {
  9820. using Super =
  9821. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  9822. void>;
  9823. DiagNonTrivalCUnionDefaultInitializeVisitor(
  9824. QualType OrigTy, SourceLocation OrigLoc,
  9825. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  9826. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9827. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  9828. const FieldDecl *FD, bool InNonTrivialUnion) {
  9829. if (const auto *AT = S.Context.getAsArrayType(QT))
  9830. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9831. InNonTrivialUnion);
  9832. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  9833. }
  9834. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9835. bool InNonTrivialUnion) {
  9836. if (InNonTrivialUnion)
  9837. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9838. << 1 << 0 << QT << FD->getName();
  9839. }
  9840. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9841. if (InNonTrivialUnion)
  9842. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9843. << 1 << 0 << QT << FD->getName();
  9844. }
  9845. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9846. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9847. if (RD->isUnion()) {
  9848. if (OrigLoc.isValid()) {
  9849. bool IsUnion = false;
  9850. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9851. IsUnion = OrigRD->isUnion();
  9852. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9853. << 0 << OrigTy << IsUnion << UseContext;
  9854. // Reset OrigLoc so that this diagnostic is emitted only once.
  9855. OrigLoc = SourceLocation();
  9856. }
  9857. InNonTrivialUnion = true;
  9858. }
  9859. if (InNonTrivialUnion)
  9860. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  9861. << 0 << 0 << QT.getUnqualifiedType() << "";
  9862. for (const FieldDecl *FD : RD->fields())
  9863. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  9864. }
  9865. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  9866. // The non-trivial C union type or the struct/union type that contains a
  9867. // non-trivial C union.
  9868. QualType OrigTy;
  9869. SourceLocation OrigLoc;
  9870. Sema::NonTrivialCUnionContext UseContext;
  9871. Sema &S;
  9872. };
  9873. struct DiagNonTrivalCUnionDestructedTypeVisitor
  9874. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  9875. using Super =
  9876. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  9877. DiagNonTrivalCUnionDestructedTypeVisitor(
  9878. QualType OrigTy, SourceLocation OrigLoc,
  9879. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  9880. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9881. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  9882. const FieldDecl *FD, bool InNonTrivialUnion) {
  9883. if (const auto *AT = S.Context.getAsArrayType(QT))
  9884. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9885. InNonTrivialUnion);
  9886. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  9887. }
  9888. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9889. bool InNonTrivialUnion) {
  9890. if (InNonTrivialUnion)
  9891. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9892. << 1 << 1 << QT << FD->getName();
  9893. }
  9894. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9895. if (InNonTrivialUnion)
  9896. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9897. << 1 << 1 << QT << FD->getName();
  9898. }
  9899. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9900. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9901. if (RD->isUnion()) {
  9902. if (OrigLoc.isValid()) {
  9903. bool IsUnion = false;
  9904. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9905. IsUnion = OrigRD->isUnion();
  9906. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9907. << 1 << OrigTy << IsUnion << UseContext;
  9908. // Reset OrigLoc so that this diagnostic is emitted only once.
  9909. OrigLoc = SourceLocation();
  9910. }
  9911. InNonTrivialUnion = true;
  9912. }
  9913. if (InNonTrivialUnion)
  9914. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  9915. << 0 << 1 << QT.getUnqualifiedType() << "";
  9916. for (const FieldDecl *FD : RD->fields())
  9917. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  9918. }
  9919. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  9920. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  9921. bool InNonTrivialUnion) {}
  9922. // The non-trivial C union type or the struct/union type that contains a
  9923. // non-trivial C union.
  9924. QualType OrigTy;
  9925. SourceLocation OrigLoc;
  9926. Sema::NonTrivialCUnionContext UseContext;
  9927. Sema &S;
  9928. };
  9929. struct DiagNonTrivalCUnionCopyVisitor
  9930. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  9931. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  9932. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  9933. Sema::NonTrivialCUnionContext UseContext,
  9934. Sema &S)
  9935. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  9936. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  9937. const FieldDecl *FD, bool InNonTrivialUnion) {
  9938. if (const auto *AT = S.Context.getAsArrayType(QT))
  9939. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  9940. InNonTrivialUnion);
  9941. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  9942. }
  9943. void visitARCStrong(QualType QT, const FieldDecl *FD,
  9944. bool InNonTrivialUnion) {
  9945. if (InNonTrivialUnion)
  9946. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9947. << 1 << 2 << QT << FD->getName();
  9948. }
  9949. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9950. if (InNonTrivialUnion)
  9951. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  9952. << 1 << 2 << QT << FD->getName();
  9953. }
  9954. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  9955. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  9956. if (RD->isUnion()) {
  9957. if (OrigLoc.isValid()) {
  9958. bool IsUnion = false;
  9959. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  9960. IsUnion = OrigRD->isUnion();
  9961. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  9962. << 2 << OrigTy << IsUnion << UseContext;
  9963. // Reset OrigLoc so that this diagnostic is emitted only once.
  9964. OrigLoc = SourceLocation();
  9965. }
  9966. InNonTrivialUnion = true;
  9967. }
  9968. if (InNonTrivialUnion)
  9969. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  9970. << 0 << 2 << QT.getUnqualifiedType() << "";
  9971. for (const FieldDecl *FD : RD->fields())
  9972. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  9973. }
  9974. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  9975. const FieldDecl *FD, bool InNonTrivialUnion) {}
  9976. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  9977. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  9978. bool InNonTrivialUnion) {}
  9979. // The non-trivial C union type or the struct/union type that contains a
  9980. // non-trivial C union.
  9981. QualType OrigTy;
  9982. SourceLocation OrigLoc;
  9983. Sema::NonTrivialCUnionContext UseContext;
  9984. Sema &S;
  9985. };
  9986. } // namespace
  9987. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  9988. NonTrivialCUnionContext UseContext,
  9989. unsigned NonTrivialKind) {
  9990. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9991. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  9992. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9993. "shouldn't be called if type doesn't have a non-trivial C union");
  9994. if ((NonTrivialKind & NTCUK_Init) &&
  9995. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9996. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  9997. .visit(QT, nullptr, false);
  9998. if ((NonTrivialKind & NTCUK_Destruct) &&
  9999. QT.hasNonTrivialToPrimitiveDestructCUnion())
  10000. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  10001. .visit(QT, nullptr, false);
  10002. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  10003. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  10004. .visit(QT, nullptr, false);
  10005. }
  10006. /// AddInitializerToDecl - Adds the initializer Init to the
  10007. /// declaration dcl. If DirectInit is true, this is C++ direct
  10008. /// initialization rather than copy initialization.
  10009. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  10010. // If there is no declaration, there was an error parsing it. Just ignore
  10011. // the initializer.
  10012. if (!RealDecl || RealDecl->isInvalidDecl()) {
  10013. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  10014. return;
  10015. }
  10016. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  10017. // Pure-specifiers are handled in ActOnPureSpecifier.
  10018. Diag(Method->getLocation(), diag::err_member_function_initialization)
  10019. << Method->getDeclName() << Init->getSourceRange();
  10020. Method->setInvalidDecl();
  10021. return;
  10022. }
  10023. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  10024. if (!VDecl) {
  10025. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  10026. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  10027. RealDecl->setInvalidDecl();
  10028. return;
  10029. }
  10030. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  10031. if (VDecl->getType()->isUndeducedType()) {
  10032. // Attempt typo correction early so that the type of the init expression can
  10033. // be deduced based on the chosen correction if the original init contains a
  10034. // TypoExpr.
  10035. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  10036. if (!Res.isUsable()) {
  10037. RealDecl->setInvalidDecl();
  10038. return;
  10039. }
  10040. Init = Res.get();
  10041. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  10042. return;
  10043. }
  10044. // dllimport cannot be used on variable definitions.
  10045. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  10046. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  10047. VDecl->setInvalidDecl();
  10048. return;
  10049. }
  10050. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  10051. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  10052. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  10053. VDecl->setInvalidDecl();
  10054. return;
  10055. }
  10056. if (!VDecl->getType()->isDependentType()) {
  10057. // A definition must end up with a complete type, which means it must be
  10058. // complete with the restriction that an array type might be completed by
  10059. // the initializer; note that later code assumes this restriction.
  10060. QualType BaseDeclType = VDecl->getType();
  10061. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  10062. BaseDeclType = Array->getElementType();
  10063. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  10064. diag::err_typecheck_decl_incomplete_type)) {
  10065. RealDecl->setInvalidDecl();
  10066. return;
  10067. }
  10068. // The variable can not have an abstract class type.
  10069. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  10070. diag::err_abstract_type_in_decl,
  10071. AbstractVariableType))
  10072. VDecl->setInvalidDecl();
  10073. }
  10074. // If adding the initializer will turn this declaration into a definition,
  10075. // and we already have a definition for this variable, diagnose or otherwise
  10076. // handle the situation.
  10077. VarDecl *Def;
  10078. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  10079. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  10080. !VDecl->isThisDeclarationADemotedDefinition() &&
  10081. checkVarDeclRedefinition(Def, VDecl))
  10082. return;
  10083. if (getLangOpts().CPlusPlus) {
  10084. // C++ [class.static.data]p4
  10085. // If a static data member is of const integral or const
  10086. // enumeration type, its declaration in the class definition can
  10087. // specify a constant-initializer which shall be an integral
  10088. // constant expression (5.19). In that case, the member can appear
  10089. // in integral constant expressions. The member shall still be
  10090. // defined in a namespace scope if it is used in the program and the
  10091. // namespace scope definition shall not contain an initializer.
  10092. //
  10093. // We already performed a redefinition check above, but for static
  10094. // data members we also need to check whether there was an in-class
  10095. // declaration with an initializer.
  10096. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  10097. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  10098. << VDecl->getDeclName();
  10099. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  10100. diag::note_previous_initializer)
  10101. << 0;
  10102. return;
  10103. }
  10104. if (VDecl->hasLocalStorage())
  10105. setFunctionHasBranchProtectedScope();
  10106. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  10107. VDecl->setInvalidDecl();
  10108. return;
  10109. }
  10110. }
  10111. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10112. // a kernel function cannot be initialized."
  10113. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10114. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10115. VDecl->setInvalidDecl();
  10116. return;
  10117. }
  10118. // Get the decls type and save a reference for later, since
  10119. // CheckInitializerTypes may change it.
  10120. QualType DclT = VDecl->getType(), SavT = DclT;
  10121. // Expressions default to 'id' when we're in a debugger
  10122. // and we are assigning it to a variable of Objective-C pointer type.
  10123. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10124. Init->getType() == Context.UnknownAnyTy) {
  10125. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10126. if (Result.isInvalid()) {
  10127. VDecl->setInvalidDecl();
  10128. return;
  10129. }
  10130. Init = Result.get();
  10131. }
  10132. // Perform the initialization.
  10133. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  10134. if (!VDecl->isInvalidDecl()) {
  10135. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10136. InitializationKind Kind = InitializationKind::CreateForInit(
  10137. VDecl->getLocation(), DirectInit, Init);
  10138. MultiExprArg Args = Init;
  10139. if (CXXDirectInit)
  10140. Args = MultiExprArg(CXXDirectInit->getExprs(),
  10141. CXXDirectInit->getNumExprs());
  10142. // Try to correct any TypoExprs in the initialization arguments.
  10143. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  10144. ExprResult Res = CorrectDelayedTyposInExpr(
  10145. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  10146. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  10147. return Init.Failed() ? ExprError() : E;
  10148. });
  10149. if (Res.isInvalid()) {
  10150. VDecl->setInvalidDecl();
  10151. } else if (Res.get() != Args[Idx]) {
  10152. Args[Idx] = Res.get();
  10153. }
  10154. }
  10155. if (VDecl->isInvalidDecl())
  10156. return;
  10157. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  10158. /*TopLevelOfInitList=*/false,
  10159. /*TreatUnavailableAsInvalid=*/false);
  10160. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  10161. if (Result.isInvalid()) {
  10162. VDecl->setInvalidDecl();
  10163. return;
  10164. }
  10165. Init = Result.getAs<Expr>();
  10166. }
  10167. // Check for self-references within variable initializers.
  10168. // Variables declared within a function/method body (except for references)
  10169. // are handled by a dataflow analysis.
  10170. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  10171. VDecl->getType()->isReferenceType()) {
  10172. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  10173. }
  10174. // If the type changed, it means we had an incomplete type that was
  10175. // completed by the initializer. For example:
  10176. // int ary[] = { 1, 3, 5 };
  10177. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  10178. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  10179. VDecl->setType(DclT);
  10180. if (!VDecl->isInvalidDecl()) {
  10181. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  10182. if (VDecl->hasAttr<BlocksAttr>())
  10183. checkRetainCycles(VDecl, Init);
  10184. // It is safe to assign a weak reference into a strong variable.
  10185. // Although this code can still have problems:
  10186. // id x = self.weakProp;
  10187. // id y = self.weakProp;
  10188. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10189. // paths through the function. This should be revisited if
  10190. // -Wrepeated-use-of-weak is made flow-sensitive.
  10191. if (FunctionScopeInfo *FSI = getCurFunction())
  10192. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  10193. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  10194. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10195. Init->getBeginLoc()))
  10196. FSI->markSafeWeakUse(Init);
  10197. }
  10198. // The initialization is usually a full-expression.
  10199. //
  10200. // FIXME: If this is a braced initialization of an aggregate, it is not
  10201. // an expression, and each individual field initializer is a separate
  10202. // full-expression. For instance, in:
  10203. //
  10204. // struct Temp { ~Temp(); };
  10205. // struct S { S(Temp); };
  10206. // struct T { S a, b; } t = { Temp(), Temp() }
  10207. //
  10208. // we should destroy the first Temp before constructing the second.
  10209. ExprResult Result =
  10210. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  10211. /*DiscardedValue*/ false, VDecl->isConstexpr());
  10212. if (Result.isInvalid()) {
  10213. VDecl->setInvalidDecl();
  10214. return;
  10215. }
  10216. Init = Result.get();
  10217. // Attach the initializer to the decl.
  10218. VDecl->setInit(Init);
  10219. if (VDecl->isLocalVarDecl()) {
  10220. // Don't check the initializer if the declaration is malformed.
  10221. if (VDecl->isInvalidDecl()) {
  10222. // do nothing
  10223. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  10224. // This is true even in OpenCL C++.
  10225. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  10226. CheckForConstantInitializer(Init, DclT);
  10227. // Otherwise, C++ does not restrict the initializer.
  10228. } else if (getLangOpts().CPlusPlus) {
  10229. // do nothing
  10230. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  10231. // static storage duration shall be constant expressions or string literals.
  10232. } else if (VDecl->getStorageClass() == SC_Static) {
  10233. CheckForConstantInitializer(Init, DclT);
  10234. // C89 is stricter than C99 for aggregate initializers.
  10235. // C89 6.5.7p3: All the expressions [...] in an initializer list
  10236. // for an object that has aggregate or union type shall be
  10237. // constant expressions.
  10238. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  10239. isa<InitListExpr>(Init)) {
  10240. const Expr *Culprit;
  10241. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  10242. Diag(Culprit->getExprLoc(),
  10243. diag::ext_aggregate_init_not_constant)
  10244. << Culprit->getSourceRange();
  10245. }
  10246. }
  10247. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10248. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10249. if (VDecl->hasLocalStorage())
  10250. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10251. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10252. VDecl->getLexicalDeclContext()->isRecord()) {
  10253. // This is an in-class initialization for a static data member, e.g.,
  10254. //
  10255. // struct S {
  10256. // static const int value = 17;
  10257. // };
  10258. // C++ [class.mem]p4:
  10259. // A member-declarator can contain a constant-initializer only
  10260. // if it declares a static member (9.4) of const integral or
  10261. // const enumeration type, see 9.4.2.
  10262. //
  10263. // C++11 [class.static.data]p3:
  10264. // If a non-volatile non-inline const static data member is of integral
  10265. // or enumeration type, its declaration in the class definition can
  10266. // specify a brace-or-equal-initializer in which every initializer-clause
  10267. // that is an assignment-expression is a constant expression. A static
  10268. // data member of literal type can be declared in the class definition
  10269. // with the constexpr specifier; if so, its declaration shall specify a
  10270. // brace-or-equal-initializer in which every initializer-clause that is
  10271. // an assignment-expression is a constant expression.
  10272. // Do nothing on dependent types.
  10273. if (DclT->isDependentType()) {
  10274. // Allow any 'static constexpr' members, whether or not they are of literal
  10275. // type. We separately check that every constexpr variable is of literal
  10276. // type.
  10277. } else if (VDecl->isConstexpr()) {
  10278. // Require constness.
  10279. } else if (!DclT.isConstQualified()) {
  10280. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10281. << Init->getSourceRange();
  10282. VDecl->setInvalidDecl();
  10283. // We allow integer constant expressions in all cases.
  10284. } else if (DclT->isIntegralOrEnumerationType()) {
  10285. // Check whether the expression is a constant expression.
  10286. SourceLocation Loc;
  10287. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10288. // In C++11, a non-constexpr const static data member with an
  10289. // in-class initializer cannot be volatile.
  10290. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10291. else if (Init->isValueDependent())
  10292. ; // Nothing to check.
  10293. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10294. ; // Ok, it's an ICE!
  10295. else if (Init->getType()->isScopedEnumeralType() &&
  10296. Init->isCXX11ConstantExpr(Context))
  10297. ; // Ok, it is a scoped-enum constant expression.
  10298. else if (Init->isEvaluatable(Context)) {
  10299. // If we can constant fold the initializer through heroics, accept it,
  10300. // but report this as a use of an extension for -pedantic.
  10301. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10302. << Init->getSourceRange();
  10303. } else {
  10304. // Otherwise, this is some crazy unknown case. Report the issue at the
  10305. // location provided by the isIntegerConstantExpr failed check.
  10306. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10307. << Init->getSourceRange();
  10308. VDecl->setInvalidDecl();
  10309. }
  10310. // We allow foldable floating-point constants as an extension.
  10311. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10312. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10313. // it anyway and provide a fixit to add the 'constexpr'.
  10314. if (getLangOpts().CPlusPlus11) {
  10315. Diag(VDecl->getLocation(),
  10316. diag::ext_in_class_initializer_float_type_cxx11)
  10317. << DclT << Init->getSourceRange();
  10318. Diag(VDecl->getBeginLoc(),
  10319. diag::note_in_class_initializer_float_type_cxx11)
  10320. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10321. } else {
  10322. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10323. << DclT << Init->getSourceRange();
  10324. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10325. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10326. << Init->getSourceRange();
  10327. VDecl->setInvalidDecl();
  10328. }
  10329. }
  10330. // Suggest adding 'constexpr' in C++11 for literal types.
  10331. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10332. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10333. << DclT << Init->getSourceRange()
  10334. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10335. VDecl->setConstexpr(true);
  10336. } else {
  10337. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10338. << DclT << Init->getSourceRange();
  10339. VDecl->setInvalidDecl();
  10340. }
  10341. } else if (VDecl->isFileVarDecl()) {
  10342. // In C, extern is typically used to avoid tentative definitions when
  10343. // declaring variables in headers, but adding an intializer makes it a
  10344. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10345. // In C++, extern is often used to give implictly static const variables
  10346. // external linkage, so don't warn in that case. If selectany is present,
  10347. // this might be header code intended for C and C++ inclusion, so apply the
  10348. // C++ rules.
  10349. if (VDecl->getStorageClass() == SC_Extern &&
  10350. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10351. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10352. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10353. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10354. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10355. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10356. // external linkage by default if the variable is declared with
  10357. // __declspec(dllexport).
  10358. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10359. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10360. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10361. VDecl->setStorageClass(SC_Extern);
  10362. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10363. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10364. CheckForConstantInitializer(Init, DclT);
  10365. }
  10366. QualType InitType = Init->getType();
  10367. if (!InitType.isNull() &&
  10368. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10369. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  10370. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  10371. // We will represent direct-initialization similarly to copy-initialization:
  10372. // int x(1); -as-> int x = 1;
  10373. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10374. //
  10375. // Clients that want to distinguish between the two forms, can check for
  10376. // direct initializer using VarDecl::getInitStyle().
  10377. // A major benefit is that clients that don't particularly care about which
  10378. // exactly form was it (like the CodeGen) can handle both cases without
  10379. // special case code.
  10380. // C++ 8.5p11:
  10381. // The form of initialization (using parentheses or '=') is generally
  10382. // insignificant, but does matter when the entity being initialized has a
  10383. // class type.
  10384. if (CXXDirectInit) {
  10385. assert(DirectInit && "Call-style initializer must be direct init.");
  10386. VDecl->setInitStyle(VarDecl::CallInit);
  10387. } else if (DirectInit) {
  10388. // This must be list-initialization. No other way is direct-initialization.
  10389. VDecl->setInitStyle(VarDecl::ListInit);
  10390. }
  10391. CheckCompleteVariableDeclaration(VDecl);
  10392. }
  10393. /// ActOnInitializerError - Given that there was an error parsing an
  10394. /// initializer for the given declaration, try to return to some form
  10395. /// of sanity.
  10396. void Sema::ActOnInitializerError(Decl *D) {
  10397. // Our main concern here is re-establishing invariants like "a
  10398. // variable's type is either dependent or complete".
  10399. if (!D || D->isInvalidDecl()) return;
  10400. VarDecl *VD = dyn_cast<VarDecl>(D);
  10401. if (!VD) return;
  10402. // Bindings are not usable if we can't make sense of the initializer.
  10403. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10404. for (auto *BD : DD->bindings())
  10405. BD->setInvalidDecl();
  10406. // Auto types are meaningless if we can't make sense of the initializer.
  10407. if (ParsingInitForAutoVars.count(D)) {
  10408. D->setInvalidDecl();
  10409. return;
  10410. }
  10411. QualType Ty = VD->getType();
  10412. if (Ty->isDependentType()) return;
  10413. // Require a complete type.
  10414. if (RequireCompleteType(VD->getLocation(),
  10415. Context.getBaseElementType(Ty),
  10416. diag::err_typecheck_decl_incomplete_type)) {
  10417. VD->setInvalidDecl();
  10418. return;
  10419. }
  10420. // Require a non-abstract type.
  10421. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10422. diag::err_abstract_type_in_decl,
  10423. AbstractVariableType)) {
  10424. VD->setInvalidDecl();
  10425. return;
  10426. }
  10427. // Don't bother complaining about constructors or destructors,
  10428. // though.
  10429. }
  10430. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10431. // If there is no declaration, there was an error parsing it. Just ignore it.
  10432. if (!RealDecl)
  10433. return;
  10434. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10435. QualType Type = Var->getType();
  10436. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10437. if (isa<DecompositionDecl>(RealDecl)) {
  10438. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10439. Var->setInvalidDecl();
  10440. return;
  10441. }
  10442. if (Type->isUndeducedType() &&
  10443. DeduceVariableDeclarationType(Var, false, nullptr))
  10444. return;
  10445. // C++11 [class.static.data]p3: A static data member can be declared with
  10446. // the constexpr specifier; if so, its declaration shall specify
  10447. // a brace-or-equal-initializer.
  10448. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10449. // the definition of a variable [...] or the declaration of a static data
  10450. // member.
  10451. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10452. !Var->isThisDeclarationADemotedDefinition()) {
  10453. if (Var->isStaticDataMember()) {
  10454. // C++1z removes the relevant rule; the in-class declaration is always
  10455. // a definition there.
  10456. if (!getLangOpts().CPlusPlus17) {
  10457. Diag(Var->getLocation(),
  10458. diag::err_constexpr_static_mem_var_requires_init)
  10459. << Var->getDeclName();
  10460. Var->setInvalidDecl();
  10461. return;
  10462. }
  10463. } else {
  10464. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10465. Var->setInvalidDecl();
  10466. return;
  10467. }
  10468. }
  10469. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10470. // be initialized.
  10471. if (!Var->isInvalidDecl() &&
  10472. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10473. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10474. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10475. Var->setInvalidDecl();
  10476. return;
  10477. }
  10478. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  10479. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  10480. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10481. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  10482. NTCUC_DefaultInitializedObject, NTCUK_Init);
  10483. switch (DefKind) {
  10484. case VarDecl::Definition:
  10485. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10486. break;
  10487. // We have an out-of-line definition of a static data member
  10488. // that has an in-class initializer, so we type-check this like
  10489. // a declaration.
  10490. //
  10491. LLVM_FALLTHROUGH;
  10492. case VarDecl::DeclarationOnly:
  10493. // It's only a declaration.
  10494. // Block scope. C99 6.7p7: If an identifier for an object is
  10495. // declared with no linkage (C99 6.2.2p6), the type for the
  10496. // object shall be complete.
  10497. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10498. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10499. RequireCompleteType(Var->getLocation(), Type,
  10500. diag::err_typecheck_decl_incomplete_type))
  10501. Var->setInvalidDecl();
  10502. // Make sure that the type is not abstract.
  10503. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10504. RequireNonAbstractType(Var->getLocation(), Type,
  10505. diag::err_abstract_type_in_decl,
  10506. AbstractVariableType))
  10507. Var->setInvalidDecl();
  10508. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10509. Var->getStorageClass() == SC_PrivateExtern) {
  10510. Diag(Var->getLocation(), diag::warn_private_extern);
  10511. Diag(Var->getLocation(), diag::note_private_extern);
  10512. }
  10513. return;
  10514. case VarDecl::TentativeDefinition:
  10515. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10516. // object that has file scope without an initializer, and without a
  10517. // storage-class specifier or with the storage-class specifier "static",
  10518. // constitutes a tentative definition. Note: A tentative definition with
  10519. // external linkage is valid (C99 6.2.2p5).
  10520. if (!Var->isInvalidDecl()) {
  10521. if (const IncompleteArrayType *ArrayT
  10522. = Context.getAsIncompleteArrayType(Type)) {
  10523. if (RequireCompleteType(Var->getLocation(),
  10524. ArrayT->getElementType(),
  10525. diag::err_illegal_decl_array_incomplete_type))
  10526. Var->setInvalidDecl();
  10527. } else if (Var->getStorageClass() == SC_Static) {
  10528. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10529. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10530. // declared type shall not be an incomplete type.
  10531. // NOTE: code such as the following
  10532. // static struct s;
  10533. // struct s { int a; };
  10534. // is accepted by gcc. Hence here we issue a warning instead of
  10535. // an error and we do not invalidate the static declaration.
  10536. // NOTE: to avoid multiple warnings, only check the first declaration.
  10537. if (Var->isFirstDecl())
  10538. RequireCompleteType(Var->getLocation(), Type,
  10539. diag::ext_typecheck_decl_incomplete_type);
  10540. }
  10541. }
  10542. // Record the tentative definition; we're done.
  10543. if (!Var->isInvalidDecl())
  10544. TentativeDefinitions.push_back(Var);
  10545. return;
  10546. }
  10547. // Provide a specific diagnostic for uninitialized variable
  10548. // definitions with incomplete array type.
  10549. if (Type->isIncompleteArrayType()) {
  10550. Diag(Var->getLocation(),
  10551. diag::err_typecheck_incomplete_array_needs_initializer);
  10552. Var->setInvalidDecl();
  10553. return;
  10554. }
  10555. // Provide a specific diagnostic for uninitialized variable
  10556. // definitions with reference type.
  10557. if (Type->isReferenceType()) {
  10558. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10559. << Var->getDeclName()
  10560. << SourceRange(Var->getLocation(), Var->getLocation());
  10561. Var->setInvalidDecl();
  10562. return;
  10563. }
  10564. // Do not attempt to type-check the default initializer for a
  10565. // variable with dependent type.
  10566. if (Type->isDependentType())
  10567. return;
  10568. if (Var->isInvalidDecl())
  10569. return;
  10570. if (!Var->hasAttr<AliasAttr>()) {
  10571. if (RequireCompleteType(Var->getLocation(),
  10572. Context.getBaseElementType(Type),
  10573. diag::err_typecheck_decl_incomplete_type)) {
  10574. Var->setInvalidDecl();
  10575. return;
  10576. }
  10577. } else {
  10578. return;
  10579. }
  10580. // The variable can not have an abstract class type.
  10581. if (RequireNonAbstractType(Var->getLocation(), Type,
  10582. diag::err_abstract_type_in_decl,
  10583. AbstractVariableType)) {
  10584. Var->setInvalidDecl();
  10585. return;
  10586. }
  10587. // Check for jumps past the implicit initializer. C++0x
  10588. // clarifies that this applies to a "variable with automatic
  10589. // storage duration", not a "local variable".
  10590. // C++11 [stmt.dcl]p3
  10591. // A program that jumps from a point where a variable with automatic
  10592. // storage duration is not in scope to a point where it is in scope is
  10593. // ill-formed unless the variable has scalar type, class type with a
  10594. // trivial default constructor and a trivial destructor, a cv-qualified
  10595. // version of one of these types, or an array of one of the preceding
  10596. // types and is declared without an initializer.
  10597. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10598. if (const RecordType *Record
  10599. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10600. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10601. // Mark the function (if we're in one) for further checking even if the
  10602. // looser rules of C++11 do not require such checks, so that we can
  10603. // diagnose incompatibilities with C++98.
  10604. if (!CXXRecord->isPOD())
  10605. setFunctionHasBranchProtectedScope();
  10606. }
  10607. }
  10608. // In OpenCL, we can't initialize objects in the __local address space,
  10609. // even implicitly, so don't synthesize an implicit initializer.
  10610. if (getLangOpts().OpenCL &&
  10611. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10612. return;
  10613. // C++03 [dcl.init]p9:
  10614. // If no initializer is specified for an object, and the
  10615. // object is of (possibly cv-qualified) non-POD class type (or
  10616. // array thereof), the object shall be default-initialized; if
  10617. // the object is of const-qualified type, the underlying class
  10618. // type shall have a user-declared default
  10619. // constructor. Otherwise, if no initializer is specified for
  10620. // a non- static object, the object and its subobjects, if
  10621. // any, have an indeterminate initial value); if the object
  10622. // or any of its subobjects are of const-qualified type, the
  10623. // program is ill-formed.
  10624. // C++0x [dcl.init]p11:
  10625. // If no initializer is specified for an object, the object is
  10626. // default-initialized; [...].
  10627. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10628. InitializationKind Kind
  10629. = InitializationKind::CreateDefault(Var->getLocation());
  10630. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10631. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10632. if (Init.isInvalid())
  10633. Var->setInvalidDecl();
  10634. else if (Init.get()) {
  10635. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10636. // This is important for template substitution.
  10637. Var->setInitStyle(VarDecl::CallInit);
  10638. }
  10639. CheckCompleteVariableDeclaration(Var);
  10640. }
  10641. }
  10642. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10643. // If there is no declaration, there was an error parsing it. Ignore it.
  10644. if (!D)
  10645. return;
  10646. VarDecl *VD = dyn_cast<VarDecl>(D);
  10647. if (!VD) {
  10648. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10649. D->setInvalidDecl();
  10650. return;
  10651. }
  10652. VD->setCXXForRangeDecl(true);
  10653. // for-range-declaration cannot be given a storage class specifier.
  10654. int Error = -1;
  10655. switch (VD->getStorageClass()) {
  10656. case SC_None:
  10657. break;
  10658. case SC_Extern:
  10659. Error = 0;
  10660. break;
  10661. case SC_Static:
  10662. Error = 1;
  10663. break;
  10664. case SC_PrivateExtern:
  10665. Error = 2;
  10666. break;
  10667. case SC_Auto:
  10668. Error = 3;
  10669. break;
  10670. case SC_Register:
  10671. Error = 4;
  10672. break;
  10673. }
  10674. if (Error != -1) {
  10675. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10676. << VD->getDeclName() << Error;
  10677. D->setInvalidDecl();
  10678. }
  10679. }
  10680. StmtResult
  10681. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10682. IdentifierInfo *Ident,
  10683. ParsedAttributes &Attrs,
  10684. SourceLocation AttrEnd) {
  10685. // C++1y [stmt.iter]p1:
  10686. // A range-based for statement of the form
  10687. // for ( for-range-identifier : for-range-initializer ) statement
  10688. // is equivalent to
  10689. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10690. DeclSpec DS(Attrs.getPool().getFactory());
  10691. const char *PrevSpec;
  10692. unsigned DiagID;
  10693. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10694. getPrintingPolicy());
  10695. Declarator D(DS, DeclaratorContext::ForContext);
  10696. D.SetIdentifier(Ident, IdentLoc);
  10697. D.takeAttributes(Attrs, AttrEnd);
  10698. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10699. IdentLoc);
  10700. Decl *Var = ActOnDeclarator(S, D);
  10701. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10702. FinalizeDeclaration(Var);
  10703. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10704. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10705. }
  10706. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10707. if (var->isInvalidDecl()) return;
  10708. if (getLangOpts().OpenCL) {
  10709. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10710. // initialiser
  10711. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10712. !var->hasInit()) {
  10713. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10714. << 1 /*Init*/;
  10715. var->setInvalidDecl();
  10716. return;
  10717. }
  10718. }
  10719. // In Objective-C, don't allow jumps past the implicit initialization of a
  10720. // local retaining variable.
  10721. if (getLangOpts().ObjC &&
  10722. var->hasLocalStorage()) {
  10723. switch (var->getType().getObjCLifetime()) {
  10724. case Qualifiers::OCL_None:
  10725. case Qualifiers::OCL_ExplicitNone:
  10726. case Qualifiers::OCL_Autoreleasing:
  10727. break;
  10728. case Qualifiers::OCL_Weak:
  10729. case Qualifiers::OCL_Strong:
  10730. setFunctionHasBranchProtectedScope();
  10731. break;
  10732. }
  10733. }
  10734. if (var->hasLocalStorage() &&
  10735. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10736. setFunctionHasBranchProtectedScope();
  10737. // Warn about externally-visible variables being defined without a
  10738. // prior declaration. We only want to do this for global
  10739. // declarations, but we also specifically need to avoid doing it for
  10740. // class members because the linkage of an anonymous class can
  10741. // change if it's later given a typedef name.
  10742. if (var->isThisDeclarationADefinition() &&
  10743. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10744. var->isExternallyVisible() && var->hasLinkage() &&
  10745. !var->isInline() && !var->getDescribedVarTemplate() &&
  10746. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10747. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10748. var->getLocation())) {
  10749. // Find a previous declaration that's not a definition.
  10750. VarDecl *prev = var->getPreviousDecl();
  10751. while (prev && prev->isThisDeclarationADefinition())
  10752. prev = prev->getPreviousDecl();
  10753. if (!prev) {
  10754. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10755. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  10756. << /* variable */ 0;
  10757. }
  10758. }
  10759. // Cache the result of checking for constant initialization.
  10760. Optional<bool> CacheHasConstInit;
  10761. const Expr *CacheCulprit = nullptr;
  10762. auto checkConstInit = [&]() mutable {
  10763. if (!CacheHasConstInit)
  10764. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10765. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10766. return *CacheHasConstInit;
  10767. };
  10768. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10769. if (var->getType().isDestructedType()) {
  10770. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10771. // The type of an object with thread storage duration shall not
  10772. // have a non-trivial destructor.
  10773. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10774. if (getLangOpts().CPlusPlus11)
  10775. Diag(var->getLocation(), diag::note_use_thread_local);
  10776. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10777. if (!checkConstInit()) {
  10778. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10779. // An object of thread storage duration shall not require dynamic
  10780. // initialization.
  10781. // FIXME: Need strict checking here.
  10782. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10783. << CacheCulprit->getSourceRange();
  10784. if (getLangOpts().CPlusPlus11)
  10785. Diag(var->getLocation(), diag::note_use_thread_local);
  10786. }
  10787. }
  10788. }
  10789. // Apply section attributes and pragmas to global variables.
  10790. bool GlobalStorage = var->hasGlobalStorage();
  10791. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10792. !inTemplateInstantiation()) {
  10793. PragmaStack<StringLiteral *> *Stack = nullptr;
  10794. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10795. if (var->getType().isConstQualified())
  10796. Stack = &ConstSegStack;
  10797. else if (!var->getInit()) {
  10798. Stack = &BSSSegStack;
  10799. SectionFlags |= ASTContext::PSF_Write;
  10800. } else {
  10801. Stack = &DataSegStack;
  10802. SectionFlags |= ASTContext::PSF_Write;
  10803. }
  10804. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10805. var->addAttr(SectionAttr::CreateImplicit(
  10806. Context, SectionAttr::Declspec_allocate,
  10807. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10808. }
  10809. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10810. if (UnifySection(SA->getName(), SectionFlags, var))
  10811. var->dropAttr<SectionAttr>();
  10812. // Apply the init_seg attribute if this has an initializer. If the
  10813. // initializer turns out to not be dynamic, we'll end up ignoring this
  10814. // attribute.
  10815. if (CurInitSeg && var->getInit())
  10816. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10817. CurInitSegLoc));
  10818. }
  10819. // All the following checks are C++ only.
  10820. if (!getLangOpts().CPlusPlus) {
  10821. // If this variable must be emitted, add it as an initializer for the
  10822. // current module.
  10823. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10824. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10825. return;
  10826. }
  10827. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10828. CheckCompleteDecompositionDeclaration(DD);
  10829. QualType type = var->getType();
  10830. if (type->isDependentType()) return;
  10831. if (var->hasAttr<BlocksAttr>())
  10832. getCurFunction()->addByrefBlockVar(var);
  10833. Expr *Init = var->getInit();
  10834. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10835. QualType baseType = Context.getBaseElementType(type);
  10836. if (Init && !Init->isValueDependent()) {
  10837. if (var->isConstexpr()) {
  10838. SmallVector<PartialDiagnosticAt, 8> Notes;
  10839. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10840. SourceLocation DiagLoc = var->getLocation();
  10841. // If the note doesn't add any useful information other than a source
  10842. // location, fold it into the primary diagnostic.
  10843. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10844. diag::note_invalid_subexpr_in_const_expr) {
  10845. DiagLoc = Notes[0].first;
  10846. Notes.clear();
  10847. }
  10848. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10849. << var << Init->getSourceRange();
  10850. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10851. Diag(Notes[I].first, Notes[I].second);
  10852. }
  10853. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  10854. // Check whether the initializer of a const variable of integral or
  10855. // enumeration type is an ICE now, since we can't tell whether it was
  10856. // initialized by a constant expression if we check later.
  10857. var->checkInitIsICE();
  10858. }
  10859. // Don't emit further diagnostics about constexpr globals since they
  10860. // were just diagnosed.
  10861. if (!var->isConstexpr() && GlobalStorage &&
  10862. var->hasAttr<RequireConstantInitAttr>()) {
  10863. // FIXME: Need strict checking in C++03 here.
  10864. bool DiagErr = getLangOpts().CPlusPlus11
  10865. ? !var->checkInitIsICE() : !checkConstInit();
  10866. if (DiagErr) {
  10867. auto attr = var->getAttr<RequireConstantInitAttr>();
  10868. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10869. << Init->getSourceRange();
  10870. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  10871. << attr->getRange();
  10872. if (getLangOpts().CPlusPlus11) {
  10873. APValue Value;
  10874. SmallVector<PartialDiagnosticAt, 8> Notes;
  10875. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10876. for (auto &it : Notes)
  10877. Diag(it.first, it.second);
  10878. } else {
  10879. Diag(CacheCulprit->getExprLoc(),
  10880. diag::note_invalid_subexpr_in_const_expr)
  10881. << CacheCulprit->getSourceRange();
  10882. }
  10883. }
  10884. }
  10885. else if (!var->isConstexpr() && IsGlobal &&
  10886. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10887. var->getLocation())) {
  10888. // Warn about globals which don't have a constant initializer. Don't
  10889. // warn about globals with a non-trivial destructor because we already
  10890. // warned about them.
  10891. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10892. if (!(RD && !RD->hasTrivialDestructor())) {
  10893. if (!checkConstInit())
  10894. Diag(var->getLocation(), diag::warn_global_constructor)
  10895. << Init->getSourceRange();
  10896. }
  10897. }
  10898. }
  10899. // Require the destructor.
  10900. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10901. FinalizeVarWithDestructor(var, recordType);
  10902. // If this variable must be emitted, add it as an initializer for the current
  10903. // module.
  10904. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10905. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10906. }
  10907. /// Determines if a variable's alignment is dependent.
  10908. static bool hasDependentAlignment(VarDecl *VD) {
  10909. if (VD->getType()->isDependentType())
  10910. return true;
  10911. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10912. if (I->isAlignmentDependent())
  10913. return true;
  10914. return false;
  10915. }
  10916. /// Check if VD needs to be dllexport/dllimport due to being in a
  10917. /// dllexport/import function.
  10918. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  10919. assert(VD->isStaticLocal());
  10920. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10921. // Find outermost function when VD is in lambda function.
  10922. while (FD && !getDLLAttr(FD) &&
  10923. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  10924. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  10925. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  10926. }
  10927. if (!FD)
  10928. return;
  10929. // Static locals inherit dll attributes from their function.
  10930. if (Attr *A = getDLLAttr(FD)) {
  10931. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10932. NewAttr->setInherited(true);
  10933. VD->addAttr(NewAttr);
  10934. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  10935. auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
  10936. getASTContext(),
  10937. A->getSpellingListIndex());
  10938. NewAttr->setInherited(true);
  10939. VD->addAttr(NewAttr);
  10940. // Export this function to enforce exporting this static variable even
  10941. // if it is not used in this compilation unit.
  10942. if (!FD->hasAttr<DLLExportAttr>())
  10943. FD->addAttr(NewAttr);
  10944. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  10945. auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
  10946. getASTContext(),
  10947. A->getSpellingListIndex());
  10948. NewAttr->setInherited(true);
  10949. VD->addAttr(NewAttr);
  10950. }
  10951. }
  10952. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10953. /// any semantic actions necessary after any initializer has been attached.
  10954. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10955. // Note that we are no longer parsing the initializer for this declaration.
  10956. ParsingInitForAutoVars.erase(ThisDecl);
  10957. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10958. if (!VD)
  10959. return;
  10960. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10961. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10962. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10963. if (PragmaClangBSSSection.Valid)
  10964. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10965. PragmaClangBSSSection.SectionName,
  10966. PragmaClangBSSSection.PragmaLocation));
  10967. if (PragmaClangDataSection.Valid)
  10968. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10969. PragmaClangDataSection.SectionName,
  10970. PragmaClangDataSection.PragmaLocation));
  10971. if (PragmaClangRodataSection.Valid)
  10972. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10973. PragmaClangRodataSection.SectionName,
  10974. PragmaClangRodataSection.PragmaLocation));
  10975. }
  10976. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10977. for (auto *BD : DD->bindings()) {
  10978. FinalizeDeclaration(BD);
  10979. }
  10980. }
  10981. checkAttributesAfterMerging(*this, *VD);
  10982. // Perform TLS alignment check here after attributes attached to the variable
  10983. // which may affect the alignment have been processed. Only perform the check
  10984. // if the target has a maximum TLS alignment (zero means no constraints).
  10985. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10986. // Protect the check so that it's not performed on dependent types and
  10987. // dependent alignments (we can't determine the alignment in that case).
  10988. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10989. !VD->isInvalidDecl()) {
  10990. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10991. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10992. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10993. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10994. << (unsigned)MaxAlignChars.getQuantity();
  10995. }
  10996. }
  10997. }
  10998. if (VD->isStaticLocal()) {
  10999. CheckStaticLocalForDllExport(VD);
  11000. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  11001. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  11002. // function, only __shared__ variables or variables without any device
  11003. // memory qualifiers may be declared with static storage class.
  11004. // Note: It is unclear how a function-scope non-const static variable
  11005. // without device memory qualifier is implemented, therefore only static
  11006. // const variable without device memory qualifier is allowed.
  11007. [&]() {
  11008. if (!getLangOpts().CUDA)
  11009. return;
  11010. if (VD->hasAttr<CUDASharedAttr>())
  11011. return;
  11012. if (VD->getType().isConstQualified() &&
  11013. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  11014. return;
  11015. if (CUDADiagIfDeviceCode(VD->getLocation(),
  11016. diag::err_device_static_local_var)
  11017. << CurrentCUDATarget())
  11018. VD->setInvalidDecl();
  11019. }();
  11020. }
  11021. }
  11022. // Perform check for initializers of device-side global variables.
  11023. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  11024. // 7.5). We must also apply the same checks to all __shared__
  11025. // variables whether they are local or not. CUDA also allows
  11026. // constant initializers for __constant__ and __device__ variables.
  11027. if (getLangOpts().CUDA)
  11028. checkAllowedCUDAInitializer(VD);
  11029. // Grab the dllimport or dllexport attribute off of the VarDecl.
  11030. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  11031. // Imported static data members cannot be defined out-of-line.
  11032. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  11033. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  11034. VD->isThisDeclarationADefinition()) {
  11035. // We allow definitions of dllimport class template static data members
  11036. // with a warning.
  11037. CXXRecordDecl *Context =
  11038. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  11039. bool IsClassTemplateMember =
  11040. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  11041. Context->getDescribedClassTemplate();
  11042. Diag(VD->getLocation(),
  11043. IsClassTemplateMember
  11044. ? diag::warn_attribute_dllimport_static_field_definition
  11045. : diag::err_attribute_dllimport_static_field_definition);
  11046. Diag(IA->getLocation(), diag::note_attribute);
  11047. if (!IsClassTemplateMember)
  11048. VD->setInvalidDecl();
  11049. }
  11050. }
  11051. // dllimport/dllexport variables cannot be thread local, their TLS index
  11052. // isn't exported with the variable.
  11053. if (DLLAttr && VD->getTLSKind()) {
  11054. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11055. if (F && getDLLAttr(F)) {
  11056. assert(VD->isStaticLocal());
  11057. // But if this is a static local in a dlimport/dllexport function, the
  11058. // function will never be inlined, which means the var would never be
  11059. // imported, so having it marked import/export is safe.
  11060. } else {
  11061. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  11062. << DLLAttr;
  11063. VD->setInvalidDecl();
  11064. }
  11065. }
  11066. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  11067. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  11068. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  11069. VD->dropAttr<UsedAttr>();
  11070. }
  11071. }
  11072. const DeclContext *DC = VD->getDeclContext();
  11073. // If there's a #pragma GCC visibility in scope, and this isn't a class
  11074. // member, set the visibility of this variable.
  11075. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  11076. AddPushedVisibilityAttribute(VD);
  11077. // FIXME: Warn on unused var template partial specializations.
  11078. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  11079. MarkUnusedFileScopedDecl(VD);
  11080. // Now we have parsed the initializer and can update the table of magic
  11081. // tag values.
  11082. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  11083. !VD->getType()->isIntegralOrEnumerationType())
  11084. return;
  11085. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  11086. const Expr *MagicValueExpr = VD->getInit();
  11087. if (!MagicValueExpr) {
  11088. continue;
  11089. }
  11090. llvm::APSInt MagicValueInt;
  11091. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  11092. Diag(I->getRange().getBegin(),
  11093. diag::err_type_tag_for_datatype_not_ice)
  11094. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11095. continue;
  11096. }
  11097. if (MagicValueInt.getActiveBits() > 64) {
  11098. Diag(I->getRange().getBegin(),
  11099. diag::err_type_tag_for_datatype_too_large)
  11100. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11101. continue;
  11102. }
  11103. uint64_t MagicValue = MagicValueInt.getZExtValue();
  11104. RegisterTypeTagForDatatype(I->getArgumentKind(),
  11105. MagicValue,
  11106. I->getMatchingCType(),
  11107. I->getLayoutCompatible(),
  11108. I->getMustBeNull());
  11109. }
  11110. }
  11111. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  11112. auto *VD = dyn_cast<VarDecl>(DD);
  11113. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  11114. }
  11115. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  11116. ArrayRef<Decl *> Group) {
  11117. SmallVector<Decl*, 8> Decls;
  11118. if (DS.isTypeSpecOwned())
  11119. Decls.push_back(DS.getRepAsDecl());
  11120. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  11121. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  11122. bool DiagnosedMultipleDecomps = false;
  11123. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  11124. bool DiagnosedNonDeducedAuto = false;
  11125. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11126. if (Decl *D = Group[i]) {
  11127. // For declarators, there are some additional syntactic-ish checks we need
  11128. // to perform.
  11129. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  11130. if (!FirstDeclaratorInGroup)
  11131. FirstDeclaratorInGroup = DD;
  11132. if (!FirstDecompDeclaratorInGroup)
  11133. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  11134. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  11135. !hasDeducedAuto(DD))
  11136. FirstNonDeducedAutoInGroup = DD;
  11137. if (FirstDeclaratorInGroup != DD) {
  11138. // A decomposition declaration cannot be combined with any other
  11139. // declaration in the same group.
  11140. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  11141. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  11142. diag::err_decomp_decl_not_alone)
  11143. << FirstDeclaratorInGroup->getSourceRange()
  11144. << DD->getSourceRange();
  11145. DiagnosedMultipleDecomps = true;
  11146. }
  11147. // A declarator that uses 'auto' in any way other than to declare a
  11148. // variable with a deduced type cannot be combined with any other
  11149. // declarator in the same group.
  11150. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  11151. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  11152. diag::err_auto_non_deduced_not_alone)
  11153. << FirstNonDeducedAutoInGroup->getType()
  11154. ->hasAutoForTrailingReturnType()
  11155. << FirstDeclaratorInGroup->getSourceRange()
  11156. << DD->getSourceRange();
  11157. DiagnosedNonDeducedAuto = true;
  11158. }
  11159. }
  11160. }
  11161. Decls.push_back(D);
  11162. }
  11163. }
  11164. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  11165. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  11166. handleTagNumbering(Tag, S);
  11167. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  11168. getLangOpts().CPlusPlus)
  11169. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  11170. }
  11171. }
  11172. return BuildDeclaratorGroup(Decls);
  11173. }
  11174. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  11175. /// group, performing any necessary semantic checking.
  11176. Sema::DeclGroupPtrTy
  11177. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  11178. // C++14 [dcl.spec.auto]p7: (DR1347)
  11179. // If the type that replaces the placeholder type is not the same in each
  11180. // deduction, the program is ill-formed.
  11181. if (Group.size() > 1) {
  11182. QualType Deduced;
  11183. VarDecl *DeducedDecl = nullptr;
  11184. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11185. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  11186. if (!D || D->isInvalidDecl())
  11187. break;
  11188. DeducedType *DT = D->getType()->getContainedDeducedType();
  11189. if (!DT || DT->getDeducedType().isNull())
  11190. continue;
  11191. if (Deduced.isNull()) {
  11192. Deduced = DT->getDeducedType();
  11193. DeducedDecl = D;
  11194. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  11195. auto *AT = dyn_cast<AutoType>(DT);
  11196. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  11197. diag::err_auto_different_deductions)
  11198. << (AT ? (unsigned)AT->getKeyword() : 3)
  11199. << Deduced << DeducedDecl->getDeclName()
  11200. << DT->getDeducedType() << D->getDeclName()
  11201. << DeducedDecl->getInit()->getSourceRange()
  11202. << D->getInit()->getSourceRange();
  11203. D->setInvalidDecl();
  11204. break;
  11205. }
  11206. }
  11207. }
  11208. ActOnDocumentableDecls(Group);
  11209. return DeclGroupPtrTy::make(
  11210. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  11211. }
  11212. void Sema::ActOnDocumentableDecl(Decl *D) {
  11213. ActOnDocumentableDecls(D);
  11214. }
  11215. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  11216. // Don't parse the comment if Doxygen diagnostics are ignored.
  11217. if (Group.empty() || !Group[0])
  11218. return;
  11219. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  11220. Group[0]->getLocation()) &&
  11221. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  11222. Group[0]->getLocation()))
  11223. return;
  11224. if (Group.size() >= 2) {
  11225. // This is a decl group. Normally it will contain only declarations
  11226. // produced from declarator list. But in case we have any definitions or
  11227. // additional declaration references:
  11228. // 'typedef struct S {} S;'
  11229. // 'typedef struct S *S;'
  11230. // 'struct S *pS;'
  11231. // FinalizeDeclaratorGroup adds these as separate declarations.
  11232. Decl *MaybeTagDecl = Group[0];
  11233. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  11234. Group = Group.slice(1);
  11235. }
  11236. }
  11237. // See if there are any new comments that are not attached to a decl.
  11238. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  11239. if (!Comments.empty() &&
  11240. !Comments.back()->isAttached()) {
  11241. // There is at least one comment that not attached to a decl.
  11242. // Maybe it should be attached to one of these decls?
  11243. //
  11244. // Note that this way we pick up not only comments that precede the
  11245. // declaration, but also comments that *follow* the declaration -- thanks to
  11246. // the lookahead in the lexer: we've consumed the semicolon and looked
  11247. // ahead through comments.
  11248. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  11249. Context.getCommentForDecl(Group[i], &PP);
  11250. }
  11251. }
  11252. /// Common checks for a parameter-declaration that should apply to both function
  11253. /// parameters and non-type template parameters.
  11254. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  11255. // Check that there are no default arguments inside the type of this
  11256. // parameter.
  11257. if (getLangOpts().CPlusPlus)
  11258. CheckExtraCXXDefaultArguments(D);
  11259. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11260. if (D.getCXXScopeSpec().isSet()) {
  11261. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11262. << D.getCXXScopeSpec().getRange();
  11263. }
  11264. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  11265. // simple identifier except [...irrelevant cases...].
  11266. switch (D.getName().getKind()) {
  11267. case UnqualifiedIdKind::IK_Identifier:
  11268. break;
  11269. case UnqualifiedIdKind::IK_OperatorFunctionId:
  11270. case UnqualifiedIdKind::IK_ConversionFunctionId:
  11271. case UnqualifiedIdKind::IK_LiteralOperatorId:
  11272. case UnqualifiedIdKind::IK_ConstructorName:
  11273. case UnqualifiedIdKind::IK_DestructorName:
  11274. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  11275. case UnqualifiedIdKind::IK_DeductionGuideName:
  11276. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11277. << GetNameForDeclarator(D).getName();
  11278. break;
  11279. case UnqualifiedIdKind::IK_TemplateId:
  11280. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  11281. // GetNameForDeclarator would not produce a useful name in this case.
  11282. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  11283. break;
  11284. }
  11285. }
  11286. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  11287. /// to introduce parameters into function prototype scope.
  11288. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  11289. const DeclSpec &DS = D.getDeclSpec();
  11290. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  11291. // C++03 [dcl.stc]p2 also permits 'auto'.
  11292. StorageClass SC = SC_None;
  11293. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  11294. SC = SC_Register;
  11295. // In C++11, the 'register' storage class specifier is deprecated.
  11296. // In C++17, it is not allowed, but we tolerate it as an extension.
  11297. if (getLangOpts().CPlusPlus11) {
  11298. Diag(DS.getStorageClassSpecLoc(),
  11299. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11300. : diag::warn_deprecated_register)
  11301. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11302. }
  11303. } else if (getLangOpts().CPlusPlus &&
  11304. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11305. SC = SC_Auto;
  11306. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11307. Diag(DS.getStorageClassSpecLoc(),
  11308. diag::err_invalid_storage_class_in_func_decl);
  11309. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11310. }
  11311. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11312. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11313. << DeclSpec::getSpecifierName(TSCS);
  11314. if (DS.isInlineSpecified())
  11315. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11316. << getLangOpts().CPlusPlus17;
  11317. if (DS.hasConstexprSpecifier())
  11318. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11319. << 0 << (D.getDeclSpec().getConstexprSpecifier() == CSK_consteval);
  11320. DiagnoseFunctionSpecifiers(DS);
  11321. CheckFunctionOrTemplateParamDeclarator(S, D);
  11322. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11323. QualType parmDeclType = TInfo->getType();
  11324. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11325. IdentifierInfo *II = D.getIdentifier();
  11326. if (II) {
  11327. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11328. ForVisibleRedeclaration);
  11329. LookupName(R, S);
  11330. if (R.isSingleResult()) {
  11331. NamedDecl *PrevDecl = R.getFoundDecl();
  11332. if (PrevDecl->isTemplateParameter()) {
  11333. // Maybe we will complain about the shadowed template parameter.
  11334. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11335. // Just pretend that we didn't see the previous declaration.
  11336. PrevDecl = nullptr;
  11337. } else if (S->isDeclScope(PrevDecl)) {
  11338. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11339. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11340. // Recover by removing the name
  11341. II = nullptr;
  11342. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11343. D.setInvalidType(true);
  11344. }
  11345. }
  11346. }
  11347. // Temporarily put parameter variables in the translation unit, not
  11348. // the enclosing context. This prevents them from accidentally
  11349. // looking like class members in C++.
  11350. ParmVarDecl *New =
  11351. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11352. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11353. if (D.isInvalidType())
  11354. New->setInvalidDecl();
  11355. assert(S->isFunctionPrototypeScope());
  11356. assert(S->getFunctionPrototypeDepth() >= 1);
  11357. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11358. S->getNextFunctionPrototypeIndex());
  11359. // Add the parameter declaration into this scope.
  11360. S->AddDecl(New);
  11361. if (II)
  11362. IdResolver.AddDecl(New);
  11363. ProcessDeclAttributes(S, New, D);
  11364. if (D.getDeclSpec().isModulePrivateSpecified())
  11365. Diag(New->getLocation(), diag::err_module_private_local)
  11366. << 1 << New->getDeclName()
  11367. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11368. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11369. if (New->hasAttr<BlocksAttr>()) {
  11370. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11371. }
  11372. return New;
  11373. }
  11374. /// Synthesizes a variable for a parameter arising from a
  11375. /// typedef.
  11376. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11377. SourceLocation Loc,
  11378. QualType T) {
  11379. /* FIXME: setting StartLoc == Loc.
  11380. Would it be worth to modify callers so as to provide proper source
  11381. location for the unnamed parameters, embedding the parameter's type? */
  11382. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11383. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11384. SC_None, nullptr);
  11385. Param->setImplicit();
  11386. return Param;
  11387. }
  11388. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11389. // Don't diagnose unused-parameter errors in template instantiations; we
  11390. // will already have done so in the template itself.
  11391. if (inTemplateInstantiation())
  11392. return;
  11393. for (const ParmVarDecl *Parameter : Parameters) {
  11394. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11395. !Parameter->hasAttr<UnusedAttr>()) {
  11396. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11397. << Parameter->getDeclName();
  11398. }
  11399. }
  11400. }
  11401. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11402. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11403. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11404. return;
  11405. // Warn if the return value is pass-by-value and larger than the specified
  11406. // threshold.
  11407. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11408. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11409. if (Size > LangOpts.NumLargeByValueCopy)
  11410. Diag(D->getLocation(), diag::warn_return_value_size)
  11411. << D->getDeclName() << Size;
  11412. }
  11413. // Warn if any parameter is pass-by-value and larger than the specified
  11414. // threshold.
  11415. for (const ParmVarDecl *Parameter : Parameters) {
  11416. QualType T = Parameter->getType();
  11417. if (T->isDependentType() || !T.isPODType(Context))
  11418. continue;
  11419. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11420. if (Size > LangOpts.NumLargeByValueCopy)
  11421. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11422. << Parameter->getDeclName() << Size;
  11423. }
  11424. }
  11425. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11426. SourceLocation NameLoc, IdentifierInfo *Name,
  11427. QualType T, TypeSourceInfo *TSInfo,
  11428. StorageClass SC) {
  11429. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11430. if (getLangOpts().ObjCAutoRefCount &&
  11431. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11432. T->isObjCLifetimeType()) {
  11433. Qualifiers::ObjCLifetime lifetime;
  11434. // Special cases for arrays:
  11435. // - if it's const, use __unsafe_unretained
  11436. // - otherwise, it's an error
  11437. if (T->isArrayType()) {
  11438. if (!T.isConstQualified()) {
  11439. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11440. DelayedDiagnostics.add(
  11441. sema::DelayedDiagnostic::makeForbiddenType(
  11442. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11443. else
  11444. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11445. << TSInfo->getTypeLoc().getSourceRange();
  11446. }
  11447. lifetime = Qualifiers::OCL_ExplicitNone;
  11448. } else {
  11449. lifetime = T->getObjCARCImplicitLifetime();
  11450. }
  11451. T = Context.getLifetimeQualifiedType(T, lifetime);
  11452. }
  11453. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11454. Context.getAdjustedParameterType(T),
  11455. TSInfo, SC, nullptr);
  11456. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  11457. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11458. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  11459. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  11460. // Parameters can not be abstract class types.
  11461. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11462. // the class has been completely parsed.
  11463. if (!CurContext->isRecord() &&
  11464. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11465. AbstractParamType))
  11466. New->setInvalidDecl();
  11467. // Parameter declarators cannot be interface types. All ObjC objects are
  11468. // passed by reference.
  11469. if (T->isObjCObjectType()) {
  11470. SourceLocation TypeEndLoc =
  11471. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11472. Diag(NameLoc,
  11473. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11474. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11475. T = Context.getObjCObjectPointerType(T);
  11476. New->setType(T);
  11477. }
  11478. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11479. // duration shall not be qualified by an address-space qualifier."
  11480. // Since all parameters have automatic store duration, they can not have
  11481. // an address space.
  11482. if (T.getAddressSpace() != LangAS::Default &&
  11483. // OpenCL allows function arguments declared to be an array of a type
  11484. // to be qualified with an address space.
  11485. !(getLangOpts().OpenCL &&
  11486. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11487. Diag(NameLoc, diag::err_arg_with_address_space);
  11488. New->setInvalidDecl();
  11489. }
  11490. return New;
  11491. }
  11492. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11493. SourceLocation LocAfterDecls) {
  11494. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11495. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11496. // for a K&R function.
  11497. if (!FTI.hasPrototype) {
  11498. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11499. --i;
  11500. if (FTI.Params[i].Param == nullptr) {
  11501. SmallString<256> Code;
  11502. llvm::raw_svector_ostream(Code)
  11503. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11504. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11505. << FTI.Params[i].Ident
  11506. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11507. // Implicitly declare the argument as type 'int' for lack of a better
  11508. // type.
  11509. AttributeFactory attrs;
  11510. DeclSpec DS(attrs);
  11511. const char* PrevSpec; // unused
  11512. unsigned DiagID; // unused
  11513. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11514. DiagID, Context.getPrintingPolicy());
  11515. // Use the identifier location for the type source range.
  11516. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11517. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11518. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11519. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11520. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11521. }
  11522. }
  11523. }
  11524. }
  11525. Decl *
  11526. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11527. MultiTemplateParamsArg TemplateParameterLists,
  11528. SkipBodyInfo *SkipBody) {
  11529. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11530. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11531. Scope *ParentScope = FnBodyScope->getParent();
  11532. D.setFunctionDefinitionKind(FDK_Definition);
  11533. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11534. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11535. }
  11536. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11537. Consumer.HandleInlineFunctionDefinition(D);
  11538. }
  11539. static bool
  11540. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11541. const FunctionDecl *&PossiblePrototype) {
  11542. // Don't warn about invalid declarations.
  11543. if (FD->isInvalidDecl())
  11544. return false;
  11545. // Or declarations that aren't global.
  11546. if (!FD->isGlobal())
  11547. return false;
  11548. // Don't warn about C++ member functions.
  11549. if (isa<CXXMethodDecl>(FD))
  11550. return false;
  11551. // Don't warn about 'main'.
  11552. if (FD->isMain())
  11553. return false;
  11554. // Don't warn about inline functions.
  11555. if (FD->isInlined())
  11556. return false;
  11557. // Don't warn about function templates.
  11558. if (FD->getDescribedFunctionTemplate())
  11559. return false;
  11560. // Don't warn about function template specializations.
  11561. if (FD->isFunctionTemplateSpecialization())
  11562. return false;
  11563. // Don't warn for OpenCL kernels.
  11564. if (FD->hasAttr<OpenCLKernelAttr>())
  11565. return false;
  11566. // Don't warn on explicitly deleted functions.
  11567. if (FD->isDeleted())
  11568. return false;
  11569. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11570. Prev; Prev = Prev->getPreviousDecl()) {
  11571. // Ignore any declarations that occur in function or method
  11572. // scope, because they aren't visible from the header.
  11573. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11574. continue;
  11575. PossiblePrototype = Prev;
  11576. return Prev->getType()->isFunctionNoProtoType();
  11577. }
  11578. return true;
  11579. }
  11580. void
  11581. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11582. const FunctionDecl *EffectiveDefinition,
  11583. SkipBodyInfo *SkipBody) {
  11584. const FunctionDecl *Definition = EffectiveDefinition;
  11585. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11586. // If this is a friend function defined in a class template, it does not
  11587. // have a body until it is used, nevertheless it is a definition, see
  11588. // [temp.inst]p2:
  11589. //
  11590. // ... for the purpose of determining whether an instantiated redeclaration
  11591. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11592. // corresponds to a definition in the template is considered to be a
  11593. // definition.
  11594. //
  11595. // The following code must produce redefinition error:
  11596. //
  11597. // template<typename T> struct C20 { friend void func_20() {} };
  11598. // C20<int> c20i;
  11599. // void func_20() {}
  11600. //
  11601. for (auto I : FD->redecls()) {
  11602. if (I != FD && !I->isInvalidDecl() &&
  11603. I->getFriendObjectKind() != Decl::FOK_None) {
  11604. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11605. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11606. // A merged copy of the same function, instantiated as a member of
  11607. // the same class, is OK.
  11608. if (declaresSameEntity(OrigFD, Original) &&
  11609. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11610. cast<Decl>(FD->getLexicalDeclContext())))
  11611. continue;
  11612. }
  11613. if (Original->isThisDeclarationADefinition()) {
  11614. Definition = I;
  11615. break;
  11616. }
  11617. }
  11618. }
  11619. }
  11620. }
  11621. if (!Definition)
  11622. // Similar to friend functions a friend function template may be a
  11623. // definition and do not have a body if it is instantiated in a class
  11624. // template.
  11625. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11626. for (auto I : FTD->redecls()) {
  11627. auto D = cast<FunctionTemplateDecl>(I);
  11628. if (D != FTD) {
  11629. assert(!D->isThisDeclarationADefinition() &&
  11630. "More than one definition in redeclaration chain");
  11631. if (D->getFriendObjectKind() != Decl::FOK_None)
  11632. if (FunctionTemplateDecl *FT =
  11633. D->getInstantiatedFromMemberTemplate()) {
  11634. if (FT->isThisDeclarationADefinition()) {
  11635. Definition = D->getTemplatedDecl();
  11636. break;
  11637. }
  11638. }
  11639. }
  11640. }
  11641. }
  11642. if (!Definition)
  11643. return;
  11644. if (canRedefineFunction(Definition, getLangOpts()))
  11645. return;
  11646. // Don't emit an error when this is redefinition of a typo-corrected
  11647. // definition.
  11648. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11649. return;
  11650. // If we don't have a visible definition of the function, and it's inline or
  11651. // a template, skip the new definition.
  11652. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11653. (Definition->getFormalLinkage() == InternalLinkage ||
  11654. Definition->isInlined() ||
  11655. Definition->getDescribedFunctionTemplate() ||
  11656. Definition->getNumTemplateParameterLists())) {
  11657. SkipBody->ShouldSkip = true;
  11658. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11659. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11660. makeMergedDefinitionVisible(TD);
  11661. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11662. return;
  11663. }
  11664. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11665. Definition->getStorageClass() == SC_Extern)
  11666. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11667. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11668. else
  11669. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11670. Diag(Definition->getLocation(), diag::note_previous_definition);
  11671. FD->setInvalidDecl();
  11672. }
  11673. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11674. Sema &S) {
  11675. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11676. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11677. LSI->CallOperator = CallOperator;
  11678. LSI->Lambda = LambdaClass;
  11679. LSI->ReturnType = CallOperator->getReturnType();
  11680. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11681. if (LCD == LCD_None)
  11682. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11683. else if (LCD == LCD_ByCopy)
  11684. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11685. else if (LCD == LCD_ByRef)
  11686. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11687. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11688. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11689. LSI->Mutable = !CallOperator->isConst();
  11690. // Add the captures to the LSI so they can be noted as already
  11691. // captured within tryCaptureVar.
  11692. auto I = LambdaClass->field_begin();
  11693. for (const auto &C : LambdaClass->captures()) {
  11694. if (C.capturesVariable()) {
  11695. VarDecl *VD = C.getCapturedVar();
  11696. if (VD->isInitCapture())
  11697. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11698. QualType CaptureType = VD->getType();
  11699. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11700. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11701. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11702. /*EllipsisLoc*/C.isPackExpansion()
  11703. ? C.getEllipsisLoc() : SourceLocation(),
  11704. CaptureType, /*Invalid*/false);
  11705. } else if (C.capturesThis()) {
  11706. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11707. C.getCaptureKind() == LCK_StarThis);
  11708. } else {
  11709. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11710. I->getType());
  11711. }
  11712. ++I;
  11713. }
  11714. }
  11715. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11716. SkipBodyInfo *SkipBody) {
  11717. if (!D) {
  11718. // Parsing the function declaration failed in some way. Push on a fake scope
  11719. // anyway so we can try to parse the function body.
  11720. PushFunctionScope();
  11721. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11722. return D;
  11723. }
  11724. FunctionDecl *FD = nullptr;
  11725. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11726. FD = FunTmpl->getTemplatedDecl();
  11727. else
  11728. FD = cast<FunctionDecl>(D);
  11729. // Do not push if it is a lambda because one is already pushed when building
  11730. // the lambda in ActOnStartOfLambdaDefinition().
  11731. if (!isLambdaCallOperator(FD))
  11732. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11733. // Check for defining attributes before the check for redefinition.
  11734. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11735. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11736. FD->dropAttr<AliasAttr>();
  11737. FD->setInvalidDecl();
  11738. }
  11739. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11740. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11741. FD->dropAttr<IFuncAttr>();
  11742. FD->setInvalidDecl();
  11743. }
  11744. // See if this is a redefinition. If 'will have body' is already set, then
  11745. // these checks were already performed when it was set.
  11746. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11747. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11748. // If we're skipping the body, we're done. Don't enter the scope.
  11749. if (SkipBody && SkipBody->ShouldSkip)
  11750. return D;
  11751. }
  11752. // Mark this function as "will have a body eventually". This lets users to
  11753. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11754. // this function.
  11755. FD->setWillHaveBody();
  11756. // If we are instantiating a generic lambda call operator, push
  11757. // a LambdaScopeInfo onto the function stack. But use the information
  11758. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11759. // LambdaScopeInfo.
  11760. // When the template operator is being specialized, the LambdaScopeInfo,
  11761. // has to be properly restored so that tryCaptureVariable doesn't try
  11762. // and capture any new variables. In addition when calculating potential
  11763. // captures during transformation of nested lambdas, it is necessary to
  11764. // have the LSI properly restored.
  11765. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11766. assert(inTemplateInstantiation() &&
  11767. "There should be an active template instantiation on the stack "
  11768. "when instantiating a generic lambda!");
  11769. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11770. } else {
  11771. // Enter a new function scope
  11772. PushFunctionScope();
  11773. }
  11774. // Builtin functions cannot be defined.
  11775. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11776. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11777. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11778. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11779. FD->setInvalidDecl();
  11780. }
  11781. }
  11782. // The return type of a function definition must be complete
  11783. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11784. QualType ResultType = FD->getReturnType();
  11785. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11786. !FD->isInvalidDecl() &&
  11787. RequireCompleteType(FD->getLocation(), ResultType,
  11788. diag::err_func_def_incomplete_result))
  11789. FD->setInvalidDecl();
  11790. if (FnBodyScope)
  11791. PushDeclContext(FnBodyScope, FD);
  11792. // Check the validity of our function parameters
  11793. CheckParmsForFunctionDef(FD->parameters(),
  11794. /*CheckParameterNames=*/true);
  11795. // Add non-parameter declarations already in the function to the current
  11796. // scope.
  11797. if (FnBodyScope) {
  11798. for (Decl *NPD : FD->decls()) {
  11799. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11800. if (!NonParmDecl)
  11801. continue;
  11802. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11803. "parameters should not be in newly created FD yet");
  11804. // If the decl has a name, make it accessible in the current scope.
  11805. if (NonParmDecl->getDeclName())
  11806. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11807. // Similarly, dive into enums and fish their constants out, making them
  11808. // accessible in this scope.
  11809. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11810. for (auto *EI : ED->enumerators())
  11811. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11812. }
  11813. }
  11814. }
  11815. // Introduce our parameters into the function scope
  11816. for (auto Param : FD->parameters()) {
  11817. Param->setOwningFunction(FD);
  11818. // If this has an identifier, add it to the scope stack.
  11819. if (Param->getIdentifier() && FnBodyScope) {
  11820. CheckShadow(FnBodyScope, Param);
  11821. PushOnScopeChains(Param, FnBodyScope);
  11822. }
  11823. }
  11824. // Ensure that the function's exception specification is instantiated.
  11825. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11826. ResolveExceptionSpec(D->getLocation(), FPT);
  11827. // dllimport cannot be applied to non-inline function definitions.
  11828. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11829. !FD->isTemplateInstantiation()) {
  11830. assert(!FD->hasAttr<DLLExportAttr>());
  11831. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11832. FD->setInvalidDecl();
  11833. return D;
  11834. }
  11835. // We want to attach documentation to original Decl (which might be
  11836. // a function template).
  11837. ActOnDocumentableDecl(D);
  11838. if (getCurLexicalContext()->isObjCContainer() &&
  11839. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11840. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11841. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11842. return D;
  11843. }
  11844. /// Given the set of return statements within a function body,
  11845. /// compute the variables that are subject to the named return value
  11846. /// optimization.
  11847. ///
  11848. /// Each of the variables that is subject to the named return value
  11849. /// optimization will be marked as NRVO variables in the AST, and any
  11850. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11851. /// use the named return value optimization.
  11852. ///
  11853. /// This function applies a very simplistic algorithm for NRVO: if every return
  11854. /// statement in the scope of a variable has the same NRVO candidate, that
  11855. /// candidate is an NRVO variable.
  11856. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11857. ReturnStmt **Returns = Scope->Returns.data();
  11858. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11859. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11860. if (!NRVOCandidate->isNRVOVariable())
  11861. Returns[I]->setNRVOCandidate(nullptr);
  11862. }
  11863. }
  11864. }
  11865. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11866. // We can't delay parsing the body of a constexpr function template (yet).
  11867. if (D.getDeclSpec().hasConstexprSpecifier())
  11868. return false;
  11869. // We can't delay parsing the body of a function template with a deduced
  11870. // return type (yet).
  11871. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11872. // If the placeholder introduces a non-deduced trailing return type,
  11873. // we can still delay parsing it.
  11874. if (D.getNumTypeObjects()) {
  11875. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11876. if (Outer.Kind == DeclaratorChunk::Function &&
  11877. Outer.Fun.hasTrailingReturnType()) {
  11878. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11879. return Ty.isNull() || !Ty->isUndeducedType();
  11880. }
  11881. }
  11882. return false;
  11883. }
  11884. return true;
  11885. }
  11886. bool Sema::canSkipFunctionBody(Decl *D) {
  11887. // We cannot skip the body of a function (or function template) which is
  11888. // constexpr, since we may need to evaluate its body in order to parse the
  11889. // rest of the file.
  11890. // We cannot skip the body of a function with an undeduced return type,
  11891. // because any callers of that function need to know the type.
  11892. if (const FunctionDecl *FD = D->getAsFunction()) {
  11893. if (FD->isConstexpr())
  11894. return false;
  11895. // We can't simply call Type::isUndeducedType here, because inside template
  11896. // auto can be deduced to a dependent type, which is not considered
  11897. // "undeduced".
  11898. if (FD->getReturnType()->getContainedDeducedType())
  11899. return false;
  11900. }
  11901. return Consumer.shouldSkipFunctionBody(D);
  11902. }
  11903. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11904. if (!Decl)
  11905. return nullptr;
  11906. if (FunctionDecl *FD = Decl->getAsFunction())
  11907. FD->setHasSkippedBody();
  11908. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11909. MD->setHasSkippedBody();
  11910. return Decl;
  11911. }
  11912. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11913. return ActOnFinishFunctionBody(D, BodyArg, false);
  11914. }
  11915. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  11916. /// body.
  11917. class ExitFunctionBodyRAII {
  11918. public:
  11919. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  11920. ~ExitFunctionBodyRAII() {
  11921. if (!IsLambda)
  11922. S.PopExpressionEvaluationContext();
  11923. }
  11924. private:
  11925. Sema &S;
  11926. bool IsLambda = false;
  11927. };
  11928. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  11929. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  11930. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  11931. if (EscapeInfo.count(BD))
  11932. return EscapeInfo[BD];
  11933. bool R = false;
  11934. const BlockDecl *CurBD = BD;
  11935. do {
  11936. R = !CurBD->doesNotEscape();
  11937. if (R)
  11938. break;
  11939. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  11940. } while (CurBD);
  11941. return EscapeInfo[BD] = R;
  11942. };
  11943. // If the location where 'self' is implicitly retained is inside a escaping
  11944. // block, emit a diagnostic.
  11945. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  11946. S.ImplicitlyRetainedSelfLocs)
  11947. if (IsOrNestedInEscapingBlock(P.second))
  11948. S.Diag(P.first, diag::warn_implicitly_retains_self)
  11949. << FixItHint::CreateInsertion(P.first, "self->");
  11950. }
  11951. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11952. bool IsInstantiation) {
  11953. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11954. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11955. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11956. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  11957. CheckCompletedCoroutineBody(FD, Body);
  11958. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  11959. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  11960. // meant to pop the context added in ActOnStartOfFunctionDef().
  11961. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  11962. if (FD) {
  11963. FD->setBody(Body);
  11964. FD->setWillHaveBody(false);
  11965. if (getLangOpts().CPlusPlus14) {
  11966. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11967. FD->getReturnType()->isUndeducedType()) {
  11968. // If the function has a deduced result type but contains no 'return'
  11969. // statements, the result type as written must be exactly 'auto', and
  11970. // the deduced result type is 'void'.
  11971. if (!FD->getReturnType()->getAs<AutoType>()) {
  11972. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11973. << FD->getReturnType();
  11974. FD->setInvalidDecl();
  11975. } else {
  11976. // Substitute 'void' for the 'auto' in the type.
  11977. TypeLoc ResultType = getReturnTypeLoc(FD);
  11978. Context.adjustDeducedFunctionResultType(
  11979. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11980. }
  11981. }
  11982. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11983. // In C++11, we don't use 'auto' deduction rules for lambda call
  11984. // operators because we don't support return type deduction.
  11985. auto *LSI = getCurLambda();
  11986. if (LSI->HasImplicitReturnType) {
  11987. deduceClosureReturnType(*LSI);
  11988. // C++11 [expr.prim.lambda]p4:
  11989. // [...] if there are no return statements in the compound-statement
  11990. // [the deduced type is] the type void
  11991. QualType RetType =
  11992. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11993. // Update the return type to the deduced type.
  11994. const FunctionProtoType *Proto =
  11995. FD->getType()->getAs<FunctionProtoType>();
  11996. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11997. Proto->getExtProtoInfo()));
  11998. }
  11999. }
  12000. // If the function implicitly returns zero (like 'main') or is naked,
  12001. // don't complain about missing return statements.
  12002. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  12003. WP.disableCheckFallThrough();
  12004. // MSVC permits the use of pure specifier (=0) on function definition,
  12005. // defined at class scope, warn about this non-standard construct.
  12006. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  12007. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  12008. if (!FD->isInvalidDecl()) {
  12009. // Don't diagnose unused parameters of defaulted or deleted functions.
  12010. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  12011. DiagnoseUnusedParameters(FD->parameters());
  12012. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  12013. FD->getReturnType(), FD);
  12014. // If this is a structor, we need a vtable.
  12015. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  12016. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  12017. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  12018. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  12019. // Try to apply the named return value optimization. We have to check
  12020. // if we can do this here because lambdas keep return statements around
  12021. // to deduce an implicit return type.
  12022. if (FD->getReturnType()->isRecordType() &&
  12023. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  12024. computeNRVO(Body, getCurFunction());
  12025. }
  12026. // GNU warning -Wmissing-prototypes:
  12027. // Warn if a global function is defined without a previous
  12028. // prototype declaration. This warning is issued even if the
  12029. // definition itself provides a prototype. The aim is to detect
  12030. // global functions that fail to be declared in header files.
  12031. const FunctionDecl *PossiblePrototype = nullptr;
  12032. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  12033. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  12034. if (PossiblePrototype) {
  12035. // We found a declaration that is not a prototype,
  12036. // but that could be a zero-parameter prototype
  12037. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  12038. TypeLoc TL = TI->getTypeLoc();
  12039. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  12040. Diag(PossiblePrototype->getLocation(),
  12041. diag::note_declaration_not_a_prototype)
  12042. << (FD->getNumParams() != 0)
  12043. << (FD->getNumParams() == 0
  12044. ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
  12045. : FixItHint{});
  12046. }
  12047. } else {
  12048. Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  12049. << /* function */ 1
  12050. << (FD->getStorageClass() == SC_None
  12051. ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
  12052. "static ")
  12053. : FixItHint{});
  12054. }
  12055. // GNU warning -Wstrict-prototypes
  12056. // Warn if K&R function is defined without a previous declaration.
  12057. // This warning is issued only if the definition itself does not provide
  12058. // a prototype. Only K&R definitions do not provide a prototype.
  12059. // An empty list in a function declarator that is part of a definition
  12060. // of that function specifies that the function has no parameters
  12061. // (C99 6.7.5.3p14)
  12062. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  12063. !LangOpts.CPlusPlus) {
  12064. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  12065. TypeLoc TL = TI->getTypeLoc();
  12066. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  12067. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  12068. }
  12069. }
  12070. // Warn on CPUDispatch with an actual body.
  12071. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  12072. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  12073. if (!CmpndBody->body_empty())
  12074. Diag(CmpndBody->body_front()->getBeginLoc(),
  12075. diag::warn_dispatch_body_ignored);
  12076. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  12077. const CXXMethodDecl *KeyFunction;
  12078. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  12079. MD->isVirtual() &&
  12080. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  12081. MD == KeyFunction->getCanonicalDecl()) {
  12082. // Update the key-function state if necessary for this ABI.
  12083. if (FD->isInlined() &&
  12084. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  12085. Context.setNonKeyFunction(MD);
  12086. // If the newly-chosen key function is already defined, then we
  12087. // need to mark the vtable as used retroactively.
  12088. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  12089. const FunctionDecl *Definition;
  12090. if (KeyFunction && KeyFunction->isDefined(Definition))
  12091. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  12092. } else {
  12093. // We just defined they key function; mark the vtable as used.
  12094. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  12095. }
  12096. }
  12097. }
  12098. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  12099. "Function parsing confused");
  12100. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  12101. assert(MD == getCurMethodDecl() && "Method parsing confused");
  12102. MD->setBody(Body);
  12103. if (!MD->isInvalidDecl()) {
  12104. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  12105. MD->getReturnType(), MD);
  12106. if (Body)
  12107. computeNRVO(Body, getCurFunction());
  12108. }
  12109. if (getCurFunction()->ObjCShouldCallSuper) {
  12110. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  12111. << MD->getSelector().getAsString();
  12112. getCurFunction()->ObjCShouldCallSuper = false;
  12113. }
  12114. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  12115. const ObjCMethodDecl *InitMethod = nullptr;
  12116. bool isDesignated =
  12117. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  12118. assert(isDesignated && InitMethod);
  12119. (void)isDesignated;
  12120. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  12121. auto IFace = MD->getClassInterface();
  12122. if (!IFace)
  12123. return false;
  12124. auto SuperD = IFace->getSuperClass();
  12125. if (!SuperD)
  12126. return false;
  12127. return SuperD->getIdentifier() ==
  12128. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  12129. };
  12130. // Don't issue this warning for unavailable inits or direct subclasses
  12131. // of NSObject.
  12132. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  12133. Diag(MD->getLocation(),
  12134. diag::warn_objc_designated_init_missing_super_call);
  12135. Diag(InitMethod->getLocation(),
  12136. diag::note_objc_designated_init_marked_here);
  12137. }
  12138. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  12139. }
  12140. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  12141. // Don't issue this warning for unavaialable inits.
  12142. if (!MD->isUnavailable())
  12143. Diag(MD->getLocation(),
  12144. diag::warn_objc_secondary_init_missing_init_call);
  12145. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  12146. }
  12147. diagnoseImplicitlyRetainedSelf(*this);
  12148. } else {
  12149. // Parsing the function declaration failed in some way. Pop the fake scope
  12150. // we pushed on.
  12151. PopFunctionScopeInfo(ActivePolicy, dcl);
  12152. return nullptr;
  12153. }
  12154. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12155. DiagnoseUnguardedAvailabilityViolations(dcl);
  12156. assert(!getCurFunction()->ObjCShouldCallSuper &&
  12157. "This should only be set for ObjC methods, which should have been "
  12158. "handled in the block above.");
  12159. // Verify and clean out per-function state.
  12160. if (Body && (!FD || !FD->isDefaulted())) {
  12161. // C++ constructors that have function-try-blocks can't have return
  12162. // statements in the handlers of that block. (C++ [except.handle]p14)
  12163. // Verify this.
  12164. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  12165. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  12166. // Verify that gotos and switch cases don't jump into scopes illegally.
  12167. if (getCurFunction()->NeedsScopeChecking() &&
  12168. !PP.isCodeCompletionEnabled())
  12169. DiagnoseInvalidJumps(Body);
  12170. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  12171. if (!Destructor->getParent()->isDependentType())
  12172. CheckDestructor(Destructor);
  12173. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12174. Destructor->getParent());
  12175. }
  12176. // If any errors have occurred, clear out any temporaries that may have
  12177. // been leftover. This ensures that these temporaries won't be picked up for
  12178. // deletion in some later function.
  12179. if (getDiagnostics().hasErrorOccurred() ||
  12180. getDiagnostics().getSuppressAllDiagnostics()) {
  12181. DiscardCleanupsInEvaluationContext();
  12182. }
  12183. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  12184. !isa<FunctionTemplateDecl>(dcl)) {
  12185. // Since the body is valid, issue any analysis-based warnings that are
  12186. // enabled.
  12187. ActivePolicy = &WP;
  12188. }
  12189. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  12190. (!CheckConstexprFunctionDecl(FD) ||
  12191. !CheckConstexprFunctionBody(FD, Body)))
  12192. FD->setInvalidDecl();
  12193. if (FD && FD->hasAttr<NakedAttr>()) {
  12194. for (const Stmt *S : Body->children()) {
  12195. // Allow local register variables without initializer as they don't
  12196. // require prologue.
  12197. bool RegisterVariables = false;
  12198. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  12199. for (const auto *Decl : DS->decls()) {
  12200. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  12201. RegisterVariables =
  12202. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  12203. if (!RegisterVariables)
  12204. break;
  12205. }
  12206. }
  12207. }
  12208. if (RegisterVariables)
  12209. continue;
  12210. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  12211. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  12212. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  12213. FD->setInvalidDecl();
  12214. break;
  12215. }
  12216. }
  12217. }
  12218. assert(ExprCleanupObjects.size() ==
  12219. ExprEvalContexts.back().NumCleanupObjects &&
  12220. "Leftover temporaries in function");
  12221. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  12222. assert(MaybeODRUseExprs.empty() &&
  12223. "Leftover expressions for odr-use checking");
  12224. }
  12225. if (!IsInstantiation)
  12226. PopDeclContext();
  12227. PopFunctionScopeInfo(ActivePolicy, dcl);
  12228. // If any errors have occurred, clear out any temporaries that may have
  12229. // been leftover. This ensures that these temporaries won't be picked up for
  12230. // deletion in some later function.
  12231. if (getDiagnostics().hasErrorOccurred()) {
  12232. DiscardCleanupsInEvaluationContext();
  12233. }
  12234. return dcl;
  12235. }
  12236. /// When we finish delayed parsing of an attribute, we must attach it to the
  12237. /// relevant Decl.
  12238. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  12239. ParsedAttributes &Attrs) {
  12240. // Always attach attributes to the underlying decl.
  12241. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  12242. D = TD->getTemplatedDecl();
  12243. ProcessDeclAttributeList(S, D, Attrs);
  12244. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  12245. if (Method->isStatic())
  12246. checkThisInStaticMemberFunctionAttributes(Method);
  12247. }
  12248. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  12249. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  12250. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  12251. IdentifierInfo &II, Scope *S) {
  12252. // Find the scope in which the identifier is injected and the corresponding
  12253. // DeclContext.
  12254. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  12255. // In that case, we inject the declaration into the translation unit scope
  12256. // instead.
  12257. Scope *BlockScope = S;
  12258. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  12259. BlockScope = BlockScope->getParent();
  12260. Scope *ContextScope = BlockScope;
  12261. while (!ContextScope->getEntity())
  12262. ContextScope = ContextScope->getParent();
  12263. ContextRAII SavedContext(*this, ContextScope->getEntity());
  12264. // Before we produce a declaration for an implicitly defined
  12265. // function, see whether there was a locally-scoped declaration of
  12266. // this name as a function or variable. If so, use that
  12267. // (non-visible) declaration, and complain about it.
  12268. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  12269. if (ExternCPrev) {
  12270. // We still need to inject the function into the enclosing block scope so
  12271. // that later (non-call) uses can see it.
  12272. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  12273. // C89 footnote 38:
  12274. // If in fact it is not defined as having type "function returning int",
  12275. // the behavior is undefined.
  12276. if (!isa<FunctionDecl>(ExternCPrev) ||
  12277. !Context.typesAreCompatible(
  12278. cast<FunctionDecl>(ExternCPrev)->getType(),
  12279. Context.getFunctionNoProtoType(Context.IntTy))) {
  12280. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  12281. << ExternCPrev << !getLangOpts().C99;
  12282. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  12283. return ExternCPrev;
  12284. }
  12285. }
  12286. // Extension in C99. Legal in C90, but warn about it.
  12287. unsigned diag_id;
  12288. if (II.getName().startswith("__builtin_"))
  12289. diag_id = diag::warn_builtin_unknown;
  12290. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12291. else if (getLangOpts().OpenCL)
  12292. diag_id = diag::err_opencl_implicit_function_decl;
  12293. else if (getLangOpts().C99)
  12294. diag_id = diag::ext_implicit_function_decl;
  12295. else
  12296. diag_id = diag::warn_implicit_function_decl;
  12297. Diag(Loc, diag_id) << &II;
  12298. // If we found a prior declaration of this function, don't bother building
  12299. // another one. We've already pushed that one into scope, so there's nothing
  12300. // more to do.
  12301. if (ExternCPrev)
  12302. return ExternCPrev;
  12303. // Because typo correction is expensive, only do it if the implicit
  12304. // function declaration is going to be treated as an error.
  12305. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12306. TypoCorrection Corrected;
  12307. DeclFilterCCC<FunctionDecl> CCC{};
  12308. if (S && (Corrected =
  12309. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12310. S, nullptr, CCC, CTK_NonError)))
  12311. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12312. /*ErrorRecovery*/false);
  12313. }
  12314. // Set a Declarator for the implicit definition: int foo();
  12315. const char *Dummy;
  12316. AttributeFactory attrFactory;
  12317. DeclSpec DS(attrFactory);
  12318. unsigned DiagID;
  12319. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12320. Context.getPrintingPolicy());
  12321. (void)Error; // Silence warning.
  12322. assert(!Error && "Error setting up implicit decl!");
  12323. SourceLocation NoLoc;
  12324. Declarator D(DS, DeclaratorContext::BlockContext);
  12325. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12326. /*IsAmbiguous=*/false,
  12327. /*LParenLoc=*/NoLoc,
  12328. /*Params=*/nullptr,
  12329. /*NumParams=*/0,
  12330. /*EllipsisLoc=*/NoLoc,
  12331. /*RParenLoc=*/NoLoc,
  12332. /*RefQualifierIsLvalueRef=*/true,
  12333. /*RefQualifierLoc=*/NoLoc,
  12334. /*MutableLoc=*/NoLoc, EST_None,
  12335. /*ESpecRange=*/SourceRange(),
  12336. /*Exceptions=*/nullptr,
  12337. /*ExceptionRanges=*/nullptr,
  12338. /*NumExceptions=*/0,
  12339. /*NoexceptExpr=*/nullptr,
  12340. /*ExceptionSpecTokens=*/nullptr,
  12341. /*DeclsInPrototype=*/None, Loc,
  12342. Loc, D),
  12343. std::move(DS.getAttributes()), SourceLocation());
  12344. D.SetIdentifier(&II, Loc);
  12345. // Insert this function into the enclosing block scope.
  12346. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12347. FD->setImplicit();
  12348. AddKnownFunctionAttributes(FD);
  12349. return FD;
  12350. }
  12351. /// Adds any function attributes that we know a priori based on
  12352. /// the declaration of this function.
  12353. ///
  12354. /// These attributes can apply both to implicitly-declared builtins
  12355. /// (like __builtin___printf_chk) or to library-declared functions
  12356. /// like NSLog or printf.
  12357. ///
  12358. /// We need to check for duplicate attributes both here and where user-written
  12359. /// attributes are applied to declarations.
  12360. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12361. if (FD->isInvalidDecl())
  12362. return;
  12363. // If this is a built-in function, map its builtin attributes to
  12364. // actual attributes.
  12365. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12366. // Handle printf-formatting attributes.
  12367. unsigned FormatIdx;
  12368. bool HasVAListArg;
  12369. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12370. if (!FD->hasAttr<FormatAttr>()) {
  12371. const char *fmt = "printf";
  12372. unsigned int NumParams = FD->getNumParams();
  12373. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12374. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12375. fmt = "NSString";
  12376. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12377. &Context.Idents.get(fmt),
  12378. FormatIdx+1,
  12379. HasVAListArg ? 0 : FormatIdx+2,
  12380. FD->getLocation()));
  12381. }
  12382. }
  12383. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12384. HasVAListArg)) {
  12385. if (!FD->hasAttr<FormatAttr>())
  12386. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12387. &Context.Idents.get("scanf"),
  12388. FormatIdx+1,
  12389. HasVAListArg ? 0 : FormatIdx+2,
  12390. FD->getLocation()));
  12391. }
  12392. // Handle automatically recognized callbacks.
  12393. SmallVector<int, 4> Encoding;
  12394. if (!FD->hasAttr<CallbackAttr>() &&
  12395. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12396. FD->addAttr(CallbackAttr::CreateImplicit(
  12397. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12398. // Mark const if we don't care about errno and that is the only thing
  12399. // preventing the function from being const. This allows IRgen to use LLVM
  12400. // intrinsics for such functions.
  12401. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12402. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12403. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12404. // We make "fma" on some platforms const because we know it does not set
  12405. // errno in those environments even though it could set errno based on the
  12406. // C standard.
  12407. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12408. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12409. !FD->hasAttr<ConstAttr>()) {
  12410. switch (BuiltinID) {
  12411. case Builtin::BI__builtin_fma:
  12412. case Builtin::BI__builtin_fmaf:
  12413. case Builtin::BI__builtin_fmal:
  12414. case Builtin::BIfma:
  12415. case Builtin::BIfmaf:
  12416. case Builtin::BIfmal:
  12417. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12418. break;
  12419. default:
  12420. break;
  12421. }
  12422. }
  12423. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12424. !FD->hasAttr<ReturnsTwiceAttr>())
  12425. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12426. FD->getLocation()));
  12427. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12428. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12429. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12430. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12431. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12432. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12433. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12434. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12435. // Add the appropriate attribute, depending on the CUDA compilation mode
  12436. // and which target the builtin belongs to. For example, during host
  12437. // compilation, aux builtins are __device__, while the rest are __host__.
  12438. if (getLangOpts().CUDAIsDevice !=
  12439. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12440. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12441. else
  12442. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12443. }
  12444. }
  12445. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12446. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12447. // across.
  12448. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12449. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12450. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12451. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12452. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12453. }
  12454. IdentifierInfo *Name = FD->getIdentifier();
  12455. if (!Name)
  12456. return;
  12457. if ((!getLangOpts().CPlusPlus &&
  12458. FD->getDeclContext()->isTranslationUnit()) ||
  12459. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12460. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12461. LinkageSpecDecl::lang_c)) {
  12462. // Okay: this could be a libc/libm/Objective-C function we know
  12463. // about.
  12464. } else
  12465. return;
  12466. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12467. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12468. // target-specific builtins, perhaps?
  12469. if (!FD->hasAttr<FormatAttr>())
  12470. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12471. &Context.Idents.get("printf"), 2,
  12472. Name->isStr("vasprintf") ? 0 : 3,
  12473. FD->getLocation()));
  12474. }
  12475. if (Name->isStr("__CFStringMakeConstantString")) {
  12476. // We already have a __builtin___CFStringMakeConstantString,
  12477. // but builds that use -fno-constant-cfstrings don't go through that.
  12478. if (!FD->hasAttr<FormatArgAttr>())
  12479. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12480. FD->getLocation()));
  12481. }
  12482. }
  12483. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12484. TypeSourceInfo *TInfo) {
  12485. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12486. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12487. if (!TInfo) {
  12488. assert(D.isInvalidType() && "no declarator info for valid type");
  12489. TInfo = Context.getTrivialTypeSourceInfo(T);
  12490. }
  12491. // Scope manipulation handled by caller.
  12492. TypedefDecl *NewTD =
  12493. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12494. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12495. // Bail out immediately if we have an invalid declaration.
  12496. if (D.isInvalidType()) {
  12497. NewTD->setInvalidDecl();
  12498. return NewTD;
  12499. }
  12500. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12501. if (CurContext->isFunctionOrMethod())
  12502. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12503. << 2 << NewTD->getDeclName()
  12504. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12505. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12506. else
  12507. NewTD->setModulePrivate();
  12508. }
  12509. // C++ [dcl.typedef]p8:
  12510. // If the typedef declaration defines an unnamed class (or
  12511. // enum), the first typedef-name declared by the declaration
  12512. // to be that class type (or enum type) is used to denote the
  12513. // class type (or enum type) for linkage purposes only.
  12514. // We need to check whether the type was declared in the declaration.
  12515. switch (D.getDeclSpec().getTypeSpecType()) {
  12516. case TST_enum:
  12517. case TST_struct:
  12518. case TST_interface:
  12519. case TST_union:
  12520. case TST_class: {
  12521. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12522. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12523. break;
  12524. }
  12525. default:
  12526. break;
  12527. }
  12528. return NewTD;
  12529. }
  12530. /// Check that this is a valid underlying type for an enum declaration.
  12531. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12532. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12533. QualType T = TI->getType();
  12534. if (T->isDependentType())
  12535. return false;
  12536. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12537. if (BT->isInteger())
  12538. return false;
  12539. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12540. return true;
  12541. }
  12542. /// Check whether this is a valid redeclaration of a previous enumeration.
  12543. /// \return true if the redeclaration was invalid.
  12544. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12545. QualType EnumUnderlyingTy, bool IsFixed,
  12546. const EnumDecl *Prev) {
  12547. if (IsScoped != Prev->isScoped()) {
  12548. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12549. << Prev->isScoped();
  12550. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12551. return true;
  12552. }
  12553. if (IsFixed && Prev->isFixed()) {
  12554. if (!EnumUnderlyingTy->isDependentType() &&
  12555. !Prev->getIntegerType()->isDependentType() &&
  12556. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12557. Prev->getIntegerType())) {
  12558. // TODO: Highlight the underlying type of the redeclaration.
  12559. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12560. << EnumUnderlyingTy << Prev->getIntegerType();
  12561. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12562. << Prev->getIntegerTypeRange();
  12563. return true;
  12564. }
  12565. } else if (IsFixed != Prev->isFixed()) {
  12566. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12567. << Prev->isFixed();
  12568. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12569. return true;
  12570. }
  12571. return false;
  12572. }
  12573. /// Get diagnostic %select index for tag kind for
  12574. /// redeclaration diagnostic message.
  12575. /// WARNING: Indexes apply to particular diagnostics only!
  12576. ///
  12577. /// \returns diagnostic %select index.
  12578. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12579. switch (Tag) {
  12580. case TTK_Struct: return 0;
  12581. case TTK_Interface: return 1;
  12582. case TTK_Class: return 2;
  12583. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12584. }
  12585. }
  12586. /// Determine if tag kind is a class-key compatible with
  12587. /// class for redeclaration (class, struct, or __interface).
  12588. ///
  12589. /// \returns true iff the tag kind is compatible.
  12590. static bool isClassCompatTagKind(TagTypeKind Tag)
  12591. {
  12592. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12593. }
  12594. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12595. TagTypeKind TTK) {
  12596. if (isa<TypedefDecl>(PrevDecl))
  12597. return NTK_Typedef;
  12598. else if (isa<TypeAliasDecl>(PrevDecl))
  12599. return NTK_TypeAlias;
  12600. else if (isa<ClassTemplateDecl>(PrevDecl))
  12601. return NTK_Template;
  12602. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12603. return NTK_TypeAliasTemplate;
  12604. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12605. return NTK_TemplateTemplateArgument;
  12606. switch (TTK) {
  12607. case TTK_Struct:
  12608. case TTK_Interface:
  12609. case TTK_Class:
  12610. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12611. case TTK_Union:
  12612. return NTK_NonUnion;
  12613. case TTK_Enum:
  12614. return NTK_NonEnum;
  12615. }
  12616. llvm_unreachable("invalid TTK");
  12617. }
  12618. /// Determine whether a tag with a given kind is acceptable
  12619. /// as a redeclaration of the given tag declaration.
  12620. ///
  12621. /// \returns true if the new tag kind is acceptable, false otherwise.
  12622. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12623. TagTypeKind NewTag, bool isDefinition,
  12624. SourceLocation NewTagLoc,
  12625. const IdentifierInfo *Name) {
  12626. // C++ [dcl.type.elab]p3:
  12627. // The class-key or enum keyword present in the
  12628. // elaborated-type-specifier shall agree in kind with the
  12629. // declaration to which the name in the elaborated-type-specifier
  12630. // refers. This rule also applies to the form of
  12631. // elaborated-type-specifier that declares a class-name or
  12632. // friend class since it can be construed as referring to the
  12633. // definition of the class. Thus, in any
  12634. // elaborated-type-specifier, the enum keyword shall be used to
  12635. // refer to an enumeration (7.2), the union class-key shall be
  12636. // used to refer to a union (clause 9), and either the class or
  12637. // struct class-key shall be used to refer to a class (clause 9)
  12638. // declared using the class or struct class-key.
  12639. TagTypeKind OldTag = Previous->getTagKind();
  12640. if (OldTag != NewTag &&
  12641. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12642. return false;
  12643. // Tags are compatible, but we might still want to warn on mismatched tags.
  12644. // Non-class tags can't be mismatched at this point.
  12645. if (!isClassCompatTagKind(NewTag))
  12646. return true;
  12647. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12648. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12649. // declarations in system headers that are designed to be specialized, but if
  12650. // a user asks us to warn, we should warn if their code contains mismatched
  12651. // declarations.
  12652. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12653. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12654. Loc);
  12655. };
  12656. if (IsIgnoredLoc(NewTagLoc))
  12657. return true;
  12658. auto IsIgnored = [&](const TagDecl *Tag) {
  12659. return IsIgnoredLoc(Tag->getLocation());
  12660. };
  12661. while (IsIgnored(Previous)) {
  12662. Previous = Previous->getPreviousDecl();
  12663. if (!Previous)
  12664. return true;
  12665. OldTag = Previous->getTagKind();
  12666. }
  12667. bool isTemplate = false;
  12668. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12669. isTemplate = Record->getDescribedClassTemplate();
  12670. if (inTemplateInstantiation()) {
  12671. if (OldTag != NewTag) {
  12672. // In a template instantiation, do not offer fix-its for tag mismatches
  12673. // since they usually mess up the template instead of fixing the problem.
  12674. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12675. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12676. << getRedeclDiagFromTagKind(OldTag);
  12677. // FIXME: Note previous location?
  12678. }
  12679. return true;
  12680. }
  12681. if (isDefinition) {
  12682. // On definitions, check all previous tags and issue a fix-it for each
  12683. // one that doesn't match the current tag.
  12684. if (Previous->getDefinition()) {
  12685. // Don't suggest fix-its for redefinitions.
  12686. return true;
  12687. }
  12688. bool previousMismatch = false;
  12689. for (const TagDecl *I : Previous->redecls()) {
  12690. if (I->getTagKind() != NewTag) {
  12691. // Ignore previous declarations for which the warning was disabled.
  12692. if (IsIgnored(I))
  12693. continue;
  12694. if (!previousMismatch) {
  12695. previousMismatch = true;
  12696. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12697. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12698. << getRedeclDiagFromTagKind(I->getTagKind());
  12699. }
  12700. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12701. << getRedeclDiagFromTagKind(NewTag)
  12702. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12703. TypeWithKeyword::getTagTypeKindName(NewTag));
  12704. }
  12705. }
  12706. return true;
  12707. }
  12708. // Identify the prevailing tag kind: this is the kind of the definition (if
  12709. // there is a non-ignored definition), or otherwise the kind of the prior
  12710. // (non-ignored) declaration.
  12711. const TagDecl *PrevDef = Previous->getDefinition();
  12712. if (PrevDef && IsIgnored(PrevDef))
  12713. PrevDef = nullptr;
  12714. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12715. if (Redecl->getTagKind() != NewTag) {
  12716. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12717. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12718. << getRedeclDiagFromTagKind(OldTag);
  12719. Diag(Redecl->getLocation(), diag::note_previous_use);
  12720. // If there is a previous definition, suggest a fix-it.
  12721. if (PrevDef) {
  12722. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12723. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12724. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12725. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12726. }
  12727. }
  12728. return true;
  12729. }
  12730. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12731. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12732. /// This should provide the commented out code in the following snippet:
  12733. /// namespace N {
  12734. /// struct X;
  12735. /// namespace M {
  12736. /// struct Y { friend struct /*N::*/ X; };
  12737. /// }
  12738. /// }
  12739. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12740. SourceLocation NameLoc) {
  12741. // While the decl is in a namespace, do repeated lookup of that name and see
  12742. // if we get the same namespace back. If we do not, continue until
  12743. // translation unit scope, at which point we have a fully qualified NNS.
  12744. SmallVector<IdentifierInfo *, 4> Namespaces;
  12745. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12746. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12747. // This tag should be declared in a namespace, which can only be enclosed by
  12748. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12749. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12750. if (!Namespace || Namespace->isAnonymousNamespace())
  12751. return FixItHint();
  12752. IdentifierInfo *II = Namespace->getIdentifier();
  12753. Namespaces.push_back(II);
  12754. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12755. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12756. if (Lookup == Namespace)
  12757. break;
  12758. }
  12759. // Once we have all the namespaces, reverse them to go outermost first, and
  12760. // build an NNS.
  12761. SmallString<64> Insertion;
  12762. llvm::raw_svector_ostream OS(Insertion);
  12763. if (DC->isTranslationUnit())
  12764. OS << "::";
  12765. std::reverse(Namespaces.begin(), Namespaces.end());
  12766. for (auto *II : Namespaces)
  12767. OS << II->getName() << "::";
  12768. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12769. }
  12770. /// Determine whether a tag originally declared in context \p OldDC can
  12771. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12772. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12773. /// using-declaration).
  12774. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12775. DeclContext *NewDC) {
  12776. OldDC = OldDC->getRedeclContext();
  12777. NewDC = NewDC->getRedeclContext();
  12778. if (OldDC->Equals(NewDC))
  12779. return true;
  12780. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12781. // encloses the other).
  12782. if (S.getLangOpts().MSVCCompat &&
  12783. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12784. return true;
  12785. return false;
  12786. }
  12787. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12788. /// former case, Name will be non-null. In the later case, Name will be null.
  12789. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12790. /// reference/declaration/definition of a tag.
  12791. ///
  12792. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12793. /// trailing-type-specifier) other than one in an alias-declaration.
  12794. ///
  12795. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12796. /// skip the definition of this tag and treat it as if it were a declaration.
  12797. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12798. SourceLocation KWLoc, CXXScopeSpec &SS,
  12799. IdentifierInfo *Name, SourceLocation NameLoc,
  12800. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12801. SourceLocation ModulePrivateLoc,
  12802. MultiTemplateParamsArg TemplateParameterLists,
  12803. bool &OwnedDecl, bool &IsDependent,
  12804. SourceLocation ScopedEnumKWLoc,
  12805. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12806. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12807. SkipBodyInfo *SkipBody) {
  12808. // If this is not a definition, it must have a name.
  12809. IdentifierInfo *OrigName = Name;
  12810. assert((Name != nullptr || TUK == TUK_Definition) &&
  12811. "Nameless record must be a definition!");
  12812. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12813. OwnedDecl = false;
  12814. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12815. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12816. // FIXME: Check member specializations more carefully.
  12817. bool isMemberSpecialization = false;
  12818. bool Invalid = false;
  12819. // We only need to do this matching if we have template parameters
  12820. // or a scope specifier, which also conveniently avoids this work
  12821. // for non-C++ cases.
  12822. if (TemplateParameterLists.size() > 0 ||
  12823. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12824. if (TemplateParameterList *TemplateParams =
  12825. MatchTemplateParametersToScopeSpecifier(
  12826. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12827. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12828. if (Kind == TTK_Enum) {
  12829. Diag(KWLoc, diag::err_enum_template);
  12830. return nullptr;
  12831. }
  12832. if (TemplateParams->size() > 0) {
  12833. // This is a declaration or definition of a class template (which may
  12834. // be a member of another template).
  12835. if (Invalid)
  12836. return nullptr;
  12837. OwnedDecl = false;
  12838. DeclResult Result = CheckClassTemplate(
  12839. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12840. AS, ModulePrivateLoc,
  12841. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12842. TemplateParameterLists.data(), SkipBody);
  12843. return Result.get();
  12844. } else {
  12845. // The "template<>" header is extraneous.
  12846. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12847. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12848. isMemberSpecialization = true;
  12849. }
  12850. }
  12851. }
  12852. // Figure out the underlying type if this a enum declaration. We need to do
  12853. // this early, because it's needed to detect if this is an incompatible
  12854. // redeclaration.
  12855. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12856. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12857. if (Kind == TTK_Enum) {
  12858. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12859. // No underlying type explicitly specified, or we failed to parse the
  12860. // type, default to int.
  12861. EnumUnderlying = Context.IntTy.getTypePtr();
  12862. } else if (UnderlyingType.get()) {
  12863. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12864. // integral type; any cv-qualification is ignored.
  12865. TypeSourceInfo *TI = nullptr;
  12866. GetTypeFromParser(UnderlyingType.get(), &TI);
  12867. EnumUnderlying = TI;
  12868. if (CheckEnumUnderlyingType(TI))
  12869. // Recover by falling back to int.
  12870. EnumUnderlying = Context.IntTy.getTypePtr();
  12871. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12872. UPPC_FixedUnderlyingType))
  12873. EnumUnderlying = Context.IntTy.getTypePtr();
  12874. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12875. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12876. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12877. // the underlying type unless the user enables -fms-compatibility. This
  12878. // makes unfixed forward declared enums incomplete and is more conforming.
  12879. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12880. EnumUnderlying = Context.IntTy.getTypePtr();
  12881. }
  12882. }
  12883. DeclContext *SearchDC = CurContext;
  12884. DeclContext *DC = CurContext;
  12885. bool isStdBadAlloc = false;
  12886. bool isStdAlignValT = false;
  12887. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12888. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12889. Redecl = NotForRedeclaration;
  12890. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12891. /// implemented asks for structural equivalence checking, the returned decl
  12892. /// here is passed back to the parser, allowing the tag body to be parsed.
  12893. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12894. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12895. // If there is an identifier, use the location of the identifier as the
  12896. // location of the decl, otherwise use the location of the struct/union
  12897. // keyword.
  12898. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12899. TagDecl *New = nullptr;
  12900. if (Kind == TTK_Enum) {
  12901. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12902. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12903. // If this is an undefined enum, bail.
  12904. if (TUK != TUK_Definition && !Invalid)
  12905. return nullptr;
  12906. if (EnumUnderlying) {
  12907. EnumDecl *ED = cast<EnumDecl>(New);
  12908. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12909. ED->setIntegerTypeSourceInfo(TI);
  12910. else
  12911. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12912. ED->setPromotionType(ED->getIntegerType());
  12913. }
  12914. } else { // struct/union
  12915. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12916. nullptr);
  12917. }
  12918. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12919. // Add alignment attributes if necessary; these attributes are checked
  12920. // when the ASTContext lays out the structure.
  12921. //
  12922. // It is important for implementing the correct semantics that this
  12923. // happen here (in ActOnTag). The #pragma pack stack is
  12924. // maintained as a result of parser callbacks which can occur at
  12925. // many points during the parsing of a struct declaration (because
  12926. // the #pragma tokens are effectively skipped over during the
  12927. // parsing of the struct).
  12928. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  12929. AddAlignmentAttributesForRecord(RD);
  12930. AddMsStructLayoutForRecord(RD);
  12931. }
  12932. }
  12933. New->setLexicalDeclContext(CurContext);
  12934. return New;
  12935. };
  12936. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12937. if (Name && SS.isNotEmpty()) {
  12938. // We have a nested-name tag ('struct foo::bar').
  12939. // Check for invalid 'foo::'.
  12940. if (SS.isInvalid()) {
  12941. Name = nullptr;
  12942. goto CreateNewDecl;
  12943. }
  12944. // If this is a friend or a reference to a class in a dependent
  12945. // context, don't try to make a decl for it.
  12946. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12947. DC = computeDeclContext(SS, false);
  12948. if (!DC) {
  12949. IsDependent = true;
  12950. return nullptr;
  12951. }
  12952. } else {
  12953. DC = computeDeclContext(SS, true);
  12954. if (!DC) {
  12955. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12956. << SS.getRange();
  12957. return nullptr;
  12958. }
  12959. }
  12960. if (RequireCompleteDeclContext(SS, DC))
  12961. return nullptr;
  12962. SearchDC = DC;
  12963. // Look-up name inside 'foo::'.
  12964. LookupQualifiedName(Previous, DC);
  12965. if (Previous.isAmbiguous())
  12966. return nullptr;
  12967. if (Previous.empty()) {
  12968. // Name lookup did not find anything. However, if the
  12969. // nested-name-specifier refers to the current instantiation,
  12970. // and that current instantiation has any dependent base
  12971. // classes, we might find something at instantiation time: treat
  12972. // this as a dependent elaborated-type-specifier.
  12973. // But this only makes any sense for reference-like lookups.
  12974. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12975. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12976. IsDependent = true;
  12977. return nullptr;
  12978. }
  12979. // A tag 'foo::bar' must already exist.
  12980. Diag(NameLoc, diag::err_not_tag_in_scope)
  12981. << Kind << Name << DC << SS.getRange();
  12982. Name = nullptr;
  12983. Invalid = true;
  12984. goto CreateNewDecl;
  12985. }
  12986. } else if (Name) {
  12987. // C++14 [class.mem]p14:
  12988. // If T is the name of a class, then each of the following shall have a
  12989. // name different from T:
  12990. // -- every member of class T that is itself a type
  12991. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12992. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12993. return nullptr;
  12994. // If this is a named struct, check to see if there was a previous forward
  12995. // declaration or definition.
  12996. // FIXME: We're looking into outer scopes here, even when we
  12997. // shouldn't be. Doing so can result in ambiguities that we
  12998. // shouldn't be diagnosing.
  12999. LookupName(Previous, S);
  13000. // When declaring or defining a tag, ignore ambiguities introduced
  13001. // by types using'ed into this scope.
  13002. if (Previous.isAmbiguous() &&
  13003. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  13004. LookupResult::Filter F = Previous.makeFilter();
  13005. while (F.hasNext()) {
  13006. NamedDecl *ND = F.next();
  13007. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  13008. SearchDC->getRedeclContext()))
  13009. F.erase();
  13010. }
  13011. F.done();
  13012. }
  13013. // C++11 [namespace.memdef]p3:
  13014. // If the name in a friend declaration is neither qualified nor
  13015. // a template-id and the declaration is a function or an
  13016. // elaborated-type-specifier, the lookup to determine whether
  13017. // the entity has been previously declared shall not consider
  13018. // any scopes outside the innermost enclosing namespace.
  13019. //
  13020. // MSVC doesn't implement the above rule for types, so a friend tag
  13021. // declaration may be a redeclaration of a type declared in an enclosing
  13022. // scope. They do implement this rule for friend functions.
  13023. //
  13024. // Does it matter that this should be by scope instead of by
  13025. // semantic context?
  13026. if (!Previous.empty() && TUK == TUK_Friend) {
  13027. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  13028. LookupResult::Filter F = Previous.makeFilter();
  13029. bool FriendSawTagOutsideEnclosingNamespace = false;
  13030. while (F.hasNext()) {
  13031. NamedDecl *ND = F.next();
  13032. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  13033. if (DC->isFileContext() &&
  13034. !EnclosingNS->Encloses(ND->getDeclContext())) {
  13035. if (getLangOpts().MSVCCompat)
  13036. FriendSawTagOutsideEnclosingNamespace = true;
  13037. else
  13038. F.erase();
  13039. }
  13040. }
  13041. F.done();
  13042. // Diagnose this MSVC extension in the easy case where lookup would have
  13043. // unambiguously found something outside the enclosing namespace.
  13044. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  13045. NamedDecl *ND = Previous.getFoundDecl();
  13046. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  13047. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  13048. }
  13049. }
  13050. // Note: there used to be some attempt at recovery here.
  13051. if (Previous.isAmbiguous())
  13052. return nullptr;
  13053. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  13054. // FIXME: This makes sure that we ignore the contexts associated
  13055. // with C structs, unions, and enums when looking for a matching
  13056. // tag declaration or definition. See the similar lookup tweak
  13057. // in Sema::LookupName; is there a better way to deal with this?
  13058. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  13059. SearchDC = SearchDC->getParent();
  13060. }
  13061. }
  13062. if (Previous.isSingleResult() &&
  13063. Previous.getFoundDecl()->isTemplateParameter()) {
  13064. // Maybe we will complain about the shadowed template parameter.
  13065. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  13066. // Just pretend that we didn't see the previous declaration.
  13067. Previous.clear();
  13068. }
  13069. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  13070. DC->Equals(getStdNamespace())) {
  13071. if (Name->isStr("bad_alloc")) {
  13072. // This is a declaration of or a reference to "std::bad_alloc".
  13073. isStdBadAlloc = true;
  13074. // If std::bad_alloc has been implicitly declared (but made invisible to
  13075. // name lookup), fill in this implicit declaration as the previous
  13076. // declaration, so that the declarations get chained appropriately.
  13077. if (Previous.empty() && StdBadAlloc)
  13078. Previous.addDecl(getStdBadAlloc());
  13079. } else if (Name->isStr("align_val_t")) {
  13080. isStdAlignValT = true;
  13081. if (Previous.empty() && StdAlignValT)
  13082. Previous.addDecl(getStdAlignValT());
  13083. }
  13084. }
  13085. // If we didn't find a previous declaration, and this is a reference
  13086. // (or friend reference), move to the correct scope. In C++, we
  13087. // also need to do a redeclaration lookup there, just in case
  13088. // there's a shadow friend decl.
  13089. if (Name && Previous.empty() &&
  13090. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  13091. if (Invalid) goto CreateNewDecl;
  13092. assert(SS.isEmpty());
  13093. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  13094. // C++ [basic.scope.pdecl]p5:
  13095. // -- for an elaborated-type-specifier of the form
  13096. //
  13097. // class-key identifier
  13098. //
  13099. // if the elaborated-type-specifier is used in the
  13100. // decl-specifier-seq or parameter-declaration-clause of a
  13101. // function defined in namespace scope, the identifier is
  13102. // declared as a class-name in the namespace that contains
  13103. // the declaration; otherwise, except as a friend
  13104. // declaration, the identifier is declared in the smallest
  13105. // non-class, non-function-prototype scope that contains the
  13106. // declaration.
  13107. //
  13108. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  13109. // C structs and unions.
  13110. //
  13111. // It is an error in C++ to declare (rather than define) an enum
  13112. // type, including via an elaborated type specifier. We'll
  13113. // diagnose that later; for now, declare the enum in the same
  13114. // scope as we would have picked for any other tag type.
  13115. //
  13116. // GNU C also supports this behavior as part of its incomplete
  13117. // enum types extension, while GNU C++ does not.
  13118. //
  13119. // Find the context where we'll be declaring the tag.
  13120. // FIXME: We would like to maintain the current DeclContext as the
  13121. // lexical context,
  13122. SearchDC = getTagInjectionContext(SearchDC);
  13123. // Find the scope where we'll be declaring the tag.
  13124. S = getTagInjectionScope(S, getLangOpts());
  13125. } else {
  13126. assert(TUK == TUK_Friend);
  13127. // C++ [namespace.memdef]p3:
  13128. // If a friend declaration in a non-local class first declares a
  13129. // class or function, the friend class or function is a member of
  13130. // the innermost enclosing namespace.
  13131. SearchDC = SearchDC->getEnclosingNamespaceContext();
  13132. }
  13133. // In C++, we need to do a redeclaration lookup to properly
  13134. // diagnose some problems.
  13135. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  13136. // hidden declaration so that we don't get ambiguity errors when using a
  13137. // type declared by an elaborated-type-specifier. In C that is not correct
  13138. // and we should instead merge compatible types found by lookup.
  13139. if (getLangOpts().CPlusPlus) {
  13140. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13141. LookupQualifiedName(Previous, SearchDC);
  13142. } else {
  13143. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13144. LookupName(Previous, S);
  13145. }
  13146. }
  13147. // If we have a known previous declaration to use, then use it.
  13148. if (Previous.empty() && SkipBody && SkipBody->Previous)
  13149. Previous.addDecl(SkipBody->Previous);
  13150. if (!Previous.empty()) {
  13151. NamedDecl *PrevDecl = Previous.getFoundDecl();
  13152. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  13153. // It's okay to have a tag decl in the same scope as a typedef
  13154. // which hides a tag decl in the same scope. Finding this
  13155. // insanity with a redeclaration lookup can only actually happen
  13156. // in C++.
  13157. //
  13158. // This is also okay for elaborated-type-specifiers, which is
  13159. // technically forbidden by the current standard but which is
  13160. // okay according to the likely resolution of an open issue;
  13161. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  13162. if (getLangOpts().CPlusPlus) {
  13163. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13164. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  13165. TagDecl *Tag = TT->getDecl();
  13166. if (Tag->getDeclName() == Name &&
  13167. Tag->getDeclContext()->getRedeclContext()
  13168. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  13169. PrevDecl = Tag;
  13170. Previous.clear();
  13171. Previous.addDecl(Tag);
  13172. Previous.resolveKind();
  13173. }
  13174. }
  13175. }
  13176. }
  13177. // If this is a redeclaration of a using shadow declaration, it must
  13178. // declare a tag in the same context. In MSVC mode, we allow a
  13179. // redefinition if either context is within the other.
  13180. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  13181. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  13182. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  13183. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  13184. !(OldTag && isAcceptableTagRedeclContext(
  13185. *this, OldTag->getDeclContext(), SearchDC))) {
  13186. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  13187. Diag(Shadow->getTargetDecl()->getLocation(),
  13188. diag::note_using_decl_target);
  13189. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  13190. << 0;
  13191. // Recover by ignoring the old declaration.
  13192. Previous.clear();
  13193. goto CreateNewDecl;
  13194. }
  13195. }
  13196. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  13197. // If this is a use of a previous tag, or if the tag is already declared
  13198. // in the same scope (so that the definition/declaration completes or
  13199. // rementions the tag), reuse the decl.
  13200. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  13201. isDeclInScope(DirectPrevDecl, SearchDC, S,
  13202. SS.isNotEmpty() || isMemberSpecialization)) {
  13203. // Make sure that this wasn't declared as an enum and now used as a
  13204. // struct or something similar.
  13205. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  13206. TUK == TUK_Definition, KWLoc,
  13207. Name)) {
  13208. bool SafeToContinue
  13209. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  13210. Kind != TTK_Enum);
  13211. if (SafeToContinue)
  13212. Diag(KWLoc, diag::err_use_with_wrong_tag)
  13213. << Name
  13214. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  13215. PrevTagDecl->getKindName());
  13216. else
  13217. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  13218. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  13219. if (SafeToContinue)
  13220. Kind = PrevTagDecl->getTagKind();
  13221. else {
  13222. // Recover by making this an anonymous redefinition.
  13223. Name = nullptr;
  13224. Previous.clear();
  13225. Invalid = true;
  13226. }
  13227. }
  13228. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  13229. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  13230. // If this is an elaborated-type-specifier for a scoped enumeration,
  13231. // the 'class' keyword is not necessary and not permitted.
  13232. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13233. if (ScopedEnum)
  13234. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  13235. << PrevEnum->isScoped()
  13236. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  13237. return PrevTagDecl;
  13238. }
  13239. QualType EnumUnderlyingTy;
  13240. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13241. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  13242. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  13243. EnumUnderlyingTy = QualType(T, 0);
  13244. // All conflicts with previous declarations are recovered by
  13245. // returning the previous declaration, unless this is a definition,
  13246. // in which case we want the caller to bail out.
  13247. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  13248. ScopedEnum, EnumUnderlyingTy,
  13249. IsFixed, PrevEnum))
  13250. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  13251. }
  13252. // C++11 [class.mem]p1:
  13253. // A member shall not be declared twice in the member-specification,
  13254. // except that a nested class or member class template can be declared
  13255. // and then later defined.
  13256. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  13257. S->isDeclScope(PrevDecl)) {
  13258. Diag(NameLoc, diag::ext_member_redeclared);
  13259. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  13260. }
  13261. if (!Invalid) {
  13262. // If this is a use, just return the declaration we found, unless
  13263. // we have attributes.
  13264. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13265. if (!Attrs.empty()) {
  13266. // FIXME: Diagnose these attributes. For now, we create a new
  13267. // declaration to hold them.
  13268. } else if (TUK == TUK_Reference &&
  13269. (PrevTagDecl->getFriendObjectKind() ==
  13270. Decl::FOK_Undeclared ||
  13271. PrevDecl->getOwningModule() != getCurrentModule()) &&
  13272. SS.isEmpty()) {
  13273. // This declaration is a reference to an existing entity, but
  13274. // has different visibility from that entity: it either makes
  13275. // a friend visible or it makes a type visible in a new module.
  13276. // In either case, create a new declaration. We only do this if
  13277. // the declaration would have meant the same thing if no prior
  13278. // declaration were found, that is, if it was found in the same
  13279. // scope where we would have injected a declaration.
  13280. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  13281. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  13282. return PrevTagDecl;
  13283. // This is in the injected scope, create a new declaration in
  13284. // that scope.
  13285. S = getTagInjectionScope(S, getLangOpts());
  13286. } else {
  13287. return PrevTagDecl;
  13288. }
  13289. }
  13290. // Diagnose attempts to redefine a tag.
  13291. if (TUK == TUK_Definition) {
  13292. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13293. // If we're defining a specialization and the previous definition
  13294. // is from an implicit instantiation, don't emit an error
  13295. // here; we'll catch this in the general case below.
  13296. bool IsExplicitSpecializationAfterInstantiation = false;
  13297. if (isMemberSpecialization) {
  13298. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13299. IsExplicitSpecializationAfterInstantiation =
  13300. RD->getTemplateSpecializationKind() !=
  13301. TSK_ExplicitSpecialization;
  13302. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13303. IsExplicitSpecializationAfterInstantiation =
  13304. ED->getTemplateSpecializationKind() !=
  13305. TSK_ExplicitSpecialization;
  13306. }
  13307. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13308. // not keep more that one definition around (merge them). However,
  13309. // ensure the decl passes the structural compatibility check in
  13310. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13311. NamedDecl *Hidden = nullptr;
  13312. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13313. // There is a definition of this tag, but it is not visible. We
  13314. // explicitly make use of C++'s one definition rule here, and
  13315. // assume that this definition is identical to the hidden one
  13316. // we already have. Make the existing definition visible and
  13317. // use it in place of this one.
  13318. if (!getLangOpts().CPlusPlus) {
  13319. // Postpone making the old definition visible until after we
  13320. // complete parsing the new one and do the structural
  13321. // comparison.
  13322. SkipBody->CheckSameAsPrevious = true;
  13323. SkipBody->New = createTagFromNewDecl();
  13324. SkipBody->Previous = Def;
  13325. return Def;
  13326. } else {
  13327. SkipBody->ShouldSkip = true;
  13328. SkipBody->Previous = Def;
  13329. makeMergedDefinitionVisible(Hidden);
  13330. // Carry on and handle it like a normal definition. We'll
  13331. // skip starting the definitiion later.
  13332. }
  13333. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13334. // A redeclaration in function prototype scope in C isn't
  13335. // visible elsewhere, so merely issue a warning.
  13336. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13337. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13338. else
  13339. Diag(NameLoc, diag::err_redefinition) << Name;
  13340. notePreviousDefinition(Def,
  13341. NameLoc.isValid() ? NameLoc : KWLoc);
  13342. // If this is a redefinition, recover by making this
  13343. // struct be anonymous, which will make any later
  13344. // references get the previous definition.
  13345. Name = nullptr;
  13346. Previous.clear();
  13347. Invalid = true;
  13348. }
  13349. } else {
  13350. // If the type is currently being defined, complain
  13351. // about a nested redefinition.
  13352. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13353. if (TD->isBeingDefined()) {
  13354. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13355. Diag(PrevTagDecl->getLocation(),
  13356. diag::note_previous_definition);
  13357. Name = nullptr;
  13358. Previous.clear();
  13359. Invalid = true;
  13360. }
  13361. }
  13362. // Okay, this is definition of a previously declared or referenced
  13363. // tag. We're going to create a new Decl for it.
  13364. }
  13365. // Okay, we're going to make a redeclaration. If this is some kind
  13366. // of reference, make sure we build the redeclaration in the same DC
  13367. // as the original, and ignore the current access specifier.
  13368. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13369. SearchDC = PrevTagDecl->getDeclContext();
  13370. AS = AS_none;
  13371. }
  13372. }
  13373. // If we get here we have (another) forward declaration or we
  13374. // have a definition. Just create a new decl.
  13375. } else {
  13376. // If we get here, this is a definition of a new tag type in a nested
  13377. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13378. // new decl/type. We set PrevDecl to NULL so that the entities
  13379. // have distinct types.
  13380. Previous.clear();
  13381. }
  13382. // If we get here, we're going to create a new Decl. If PrevDecl
  13383. // is non-NULL, it's a definition of the tag declared by
  13384. // PrevDecl. If it's NULL, we have a new definition.
  13385. // Otherwise, PrevDecl is not a tag, but was found with tag
  13386. // lookup. This is only actually possible in C++, where a few
  13387. // things like templates still live in the tag namespace.
  13388. } else {
  13389. // Use a better diagnostic if an elaborated-type-specifier
  13390. // found the wrong kind of type on the first
  13391. // (non-redeclaration) lookup.
  13392. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13393. !Previous.isForRedeclaration()) {
  13394. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13395. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13396. << Kind;
  13397. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13398. Invalid = true;
  13399. // Otherwise, only diagnose if the declaration is in scope.
  13400. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13401. SS.isNotEmpty() || isMemberSpecialization)) {
  13402. // do nothing
  13403. // Diagnose implicit declarations introduced by elaborated types.
  13404. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13405. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13406. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13407. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13408. Invalid = true;
  13409. // Otherwise it's a declaration. Call out a particularly common
  13410. // case here.
  13411. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13412. unsigned Kind = 0;
  13413. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13414. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13415. << Name << Kind << TND->getUnderlyingType();
  13416. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13417. Invalid = true;
  13418. // Otherwise, diagnose.
  13419. } else {
  13420. // The tag name clashes with something else in the target scope,
  13421. // issue an error and recover by making this tag be anonymous.
  13422. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13423. notePreviousDefinition(PrevDecl, NameLoc);
  13424. Name = nullptr;
  13425. Invalid = true;
  13426. }
  13427. // The existing declaration isn't relevant to us; we're in a
  13428. // new scope, so clear out the previous declaration.
  13429. Previous.clear();
  13430. }
  13431. }
  13432. CreateNewDecl:
  13433. TagDecl *PrevDecl = nullptr;
  13434. if (Previous.isSingleResult())
  13435. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13436. // If there is an identifier, use the location of the identifier as the
  13437. // location of the decl, otherwise use the location of the struct/union
  13438. // keyword.
  13439. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13440. // Otherwise, create a new declaration. If there is a previous
  13441. // declaration of the same entity, the two will be linked via
  13442. // PrevDecl.
  13443. TagDecl *New;
  13444. if (Kind == TTK_Enum) {
  13445. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13446. // enum X { A, B, C } D; D should chain to X.
  13447. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13448. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13449. ScopedEnumUsesClassTag, IsFixed);
  13450. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13451. StdAlignValT = cast<EnumDecl>(New);
  13452. // If this is an undefined enum, warn.
  13453. if (TUK != TUK_Definition && !Invalid) {
  13454. TagDecl *Def;
  13455. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13456. // C++0x: 7.2p2: opaque-enum-declaration.
  13457. // Conflicts are diagnosed above. Do nothing.
  13458. }
  13459. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13460. Diag(Loc, diag::ext_forward_ref_enum_def)
  13461. << New;
  13462. Diag(Def->getLocation(), diag::note_previous_definition);
  13463. } else {
  13464. unsigned DiagID = diag::ext_forward_ref_enum;
  13465. if (getLangOpts().MSVCCompat)
  13466. DiagID = diag::ext_ms_forward_ref_enum;
  13467. else if (getLangOpts().CPlusPlus)
  13468. DiagID = diag::err_forward_ref_enum;
  13469. Diag(Loc, DiagID);
  13470. }
  13471. }
  13472. if (EnumUnderlying) {
  13473. EnumDecl *ED = cast<EnumDecl>(New);
  13474. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13475. ED->setIntegerTypeSourceInfo(TI);
  13476. else
  13477. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13478. ED->setPromotionType(ED->getIntegerType());
  13479. assert(ED->isComplete() && "enum with type should be complete");
  13480. }
  13481. } else {
  13482. // struct/union/class
  13483. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13484. // struct X { int A; } D; D should chain to X.
  13485. if (getLangOpts().CPlusPlus) {
  13486. // FIXME: Look for a way to use RecordDecl for simple structs.
  13487. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13488. cast_or_null<CXXRecordDecl>(PrevDecl));
  13489. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13490. StdBadAlloc = cast<CXXRecordDecl>(New);
  13491. } else
  13492. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13493. cast_or_null<RecordDecl>(PrevDecl));
  13494. }
  13495. // C++11 [dcl.type]p3:
  13496. // A type-specifier-seq shall not define a class or enumeration [...].
  13497. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13498. TUK == TUK_Definition) {
  13499. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13500. << Context.getTagDeclType(New);
  13501. Invalid = true;
  13502. }
  13503. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13504. DC->getDeclKind() == Decl::Enum) {
  13505. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13506. << Context.getTagDeclType(New);
  13507. Invalid = true;
  13508. }
  13509. // Maybe add qualifier info.
  13510. if (SS.isNotEmpty()) {
  13511. if (SS.isSet()) {
  13512. // If this is either a declaration or a definition, check the
  13513. // nested-name-specifier against the current context.
  13514. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13515. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13516. isMemberSpecialization))
  13517. Invalid = true;
  13518. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13519. if (TemplateParameterLists.size() > 0) {
  13520. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13521. }
  13522. }
  13523. else
  13524. Invalid = true;
  13525. }
  13526. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13527. // Add alignment attributes if necessary; these attributes are checked when
  13528. // the ASTContext lays out the structure.
  13529. //
  13530. // It is important for implementing the correct semantics that this
  13531. // happen here (in ActOnTag). The #pragma pack stack is
  13532. // maintained as a result of parser callbacks which can occur at
  13533. // many points during the parsing of a struct declaration (because
  13534. // the #pragma tokens are effectively skipped over during the
  13535. // parsing of the struct).
  13536. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13537. AddAlignmentAttributesForRecord(RD);
  13538. AddMsStructLayoutForRecord(RD);
  13539. }
  13540. }
  13541. if (ModulePrivateLoc.isValid()) {
  13542. if (isMemberSpecialization)
  13543. Diag(New->getLocation(), diag::err_module_private_specialization)
  13544. << 2
  13545. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13546. // __module_private__ does not apply to local classes. However, we only
  13547. // diagnose this as an error when the declaration specifiers are
  13548. // freestanding. Here, we just ignore the __module_private__.
  13549. else if (!SearchDC->isFunctionOrMethod())
  13550. New->setModulePrivate();
  13551. }
  13552. // If this is a specialization of a member class (of a class template),
  13553. // check the specialization.
  13554. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13555. Invalid = true;
  13556. // If we're declaring or defining a tag in function prototype scope in C,
  13557. // note that this type can only be used within the function and add it to
  13558. // the list of decls to inject into the function definition scope.
  13559. if ((Name || Kind == TTK_Enum) &&
  13560. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13561. if (getLangOpts().CPlusPlus) {
  13562. // C++ [dcl.fct]p6:
  13563. // Types shall not be defined in return or parameter types.
  13564. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13565. Diag(Loc, diag::err_type_defined_in_param_type)
  13566. << Name;
  13567. Invalid = true;
  13568. }
  13569. } else if (!PrevDecl) {
  13570. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13571. }
  13572. }
  13573. if (Invalid)
  13574. New->setInvalidDecl();
  13575. // Set the lexical context. If the tag has a C++ scope specifier, the
  13576. // lexical context will be different from the semantic context.
  13577. New->setLexicalDeclContext(CurContext);
  13578. // Mark this as a friend decl if applicable.
  13579. // In Microsoft mode, a friend declaration also acts as a forward
  13580. // declaration so we always pass true to setObjectOfFriendDecl to make
  13581. // the tag name visible.
  13582. if (TUK == TUK_Friend)
  13583. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13584. // Set the access specifier.
  13585. if (!Invalid && SearchDC->isRecord())
  13586. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13587. if (PrevDecl)
  13588. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13589. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13590. New->startDefinition();
  13591. ProcessDeclAttributeList(S, New, Attrs);
  13592. AddPragmaAttributes(S, New);
  13593. // If this has an identifier, add it to the scope stack.
  13594. if (TUK == TUK_Friend) {
  13595. // We might be replacing an existing declaration in the lookup tables;
  13596. // if so, borrow its access specifier.
  13597. if (PrevDecl)
  13598. New->setAccess(PrevDecl->getAccess());
  13599. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13600. DC->makeDeclVisibleInContext(New);
  13601. if (Name) // can be null along some error paths
  13602. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13603. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13604. } else if (Name) {
  13605. S = getNonFieldDeclScope(S);
  13606. PushOnScopeChains(New, S, true);
  13607. } else {
  13608. CurContext->addDecl(New);
  13609. }
  13610. // If this is the C FILE type, notify the AST context.
  13611. if (IdentifierInfo *II = New->getIdentifier())
  13612. if (!New->isInvalidDecl() &&
  13613. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13614. II->isStr("FILE"))
  13615. Context.setFILEDecl(New);
  13616. if (PrevDecl)
  13617. mergeDeclAttributes(New, PrevDecl);
  13618. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13619. // record.
  13620. AddPushedVisibilityAttribute(New);
  13621. if (isMemberSpecialization && !New->isInvalidDecl())
  13622. CompleteMemberSpecialization(New, Previous);
  13623. OwnedDecl = true;
  13624. // In C++, don't return an invalid declaration. We can't recover well from
  13625. // the cases where we make the type anonymous.
  13626. if (Invalid && getLangOpts().CPlusPlus) {
  13627. if (New->isBeingDefined())
  13628. if (auto RD = dyn_cast<RecordDecl>(New))
  13629. RD->completeDefinition();
  13630. return nullptr;
  13631. } else if (SkipBody && SkipBody->ShouldSkip) {
  13632. return SkipBody->Previous;
  13633. } else {
  13634. return New;
  13635. }
  13636. }
  13637. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13638. AdjustDeclIfTemplate(TagD);
  13639. TagDecl *Tag = cast<TagDecl>(TagD);
  13640. // Enter the tag context.
  13641. PushDeclContext(S, Tag);
  13642. ActOnDocumentableDecl(TagD);
  13643. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13644. // record.
  13645. AddPushedVisibilityAttribute(Tag);
  13646. }
  13647. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13648. SkipBodyInfo &SkipBody) {
  13649. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13650. return false;
  13651. // Make the previous decl visible.
  13652. makeMergedDefinitionVisible(SkipBody.Previous);
  13653. return true;
  13654. }
  13655. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13656. assert(isa<ObjCContainerDecl>(IDecl) &&
  13657. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13658. DeclContext *OCD = cast<DeclContext>(IDecl);
  13659. assert(getContainingDC(OCD) == CurContext &&
  13660. "The next DeclContext should be lexically contained in the current one.");
  13661. CurContext = OCD;
  13662. return IDecl;
  13663. }
  13664. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13665. SourceLocation FinalLoc,
  13666. bool IsFinalSpelledSealed,
  13667. SourceLocation LBraceLoc) {
  13668. AdjustDeclIfTemplate(TagD);
  13669. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13670. FieldCollector->StartClass();
  13671. if (!Record->getIdentifier())
  13672. return;
  13673. if (FinalLoc.isValid())
  13674. Record->addAttr(new (Context)
  13675. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  13676. // C++ [class]p2:
  13677. // [...] The class-name is also inserted into the scope of the
  13678. // class itself; this is known as the injected-class-name. For
  13679. // purposes of access checking, the injected-class-name is treated
  13680. // as if it were a public member name.
  13681. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13682. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13683. Record->getLocation(), Record->getIdentifier(),
  13684. /*PrevDecl=*/nullptr,
  13685. /*DelayTypeCreation=*/true);
  13686. Context.getTypeDeclType(InjectedClassName, Record);
  13687. InjectedClassName->setImplicit();
  13688. InjectedClassName->setAccess(AS_public);
  13689. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13690. InjectedClassName->setDescribedClassTemplate(Template);
  13691. PushOnScopeChains(InjectedClassName, S);
  13692. assert(InjectedClassName->isInjectedClassName() &&
  13693. "Broken injected-class-name");
  13694. }
  13695. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13696. SourceRange BraceRange) {
  13697. AdjustDeclIfTemplate(TagD);
  13698. TagDecl *Tag = cast<TagDecl>(TagD);
  13699. Tag->setBraceRange(BraceRange);
  13700. // Make sure we "complete" the definition even it is invalid.
  13701. if (Tag->isBeingDefined()) {
  13702. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13703. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13704. RD->completeDefinition();
  13705. }
  13706. if (isa<CXXRecordDecl>(Tag)) {
  13707. FieldCollector->FinishClass();
  13708. }
  13709. // Exit this scope of this tag's definition.
  13710. PopDeclContext();
  13711. if (getCurLexicalContext()->isObjCContainer() &&
  13712. Tag->getDeclContext()->isFileContext())
  13713. Tag->setTopLevelDeclInObjCContainer();
  13714. // Notify the consumer that we've defined a tag.
  13715. if (!Tag->isInvalidDecl())
  13716. Consumer.HandleTagDeclDefinition(Tag);
  13717. }
  13718. void Sema::ActOnObjCContainerFinishDefinition() {
  13719. // Exit this scope of this interface definition.
  13720. PopDeclContext();
  13721. }
  13722. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13723. assert(DC == CurContext && "Mismatch of container contexts");
  13724. OriginalLexicalContext = DC;
  13725. ActOnObjCContainerFinishDefinition();
  13726. }
  13727. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13728. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13729. OriginalLexicalContext = nullptr;
  13730. }
  13731. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13732. AdjustDeclIfTemplate(TagD);
  13733. TagDecl *Tag = cast<TagDecl>(TagD);
  13734. Tag->setInvalidDecl();
  13735. // Make sure we "complete" the definition even it is invalid.
  13736. if (Tag->isBeingDefined()) {
  13737. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13738. RD->completeDefinition();
  13739. }
  13740. // We're undoing ActOnTagStartDefinition here, not
  13741. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13742. // the FieldCollector.
  13743. PopDeclContext();
  13744. }
  13745. // Note that FieldName may be null for anonymous bitfields.
  13746. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13747. IdentifierInfo *FieldName,
  13748. QualType FieldTy, bool IsMsStruct,
  13749. Expr *BitWidth, bool *ZeroWidth) {
  13750. // Default to true; that shouldn't confuse checks for emptiness
  13751. if (ZeroWidth)
  13752. *ZeroWidth = true;
  13753. // C99 6.7.2.1p4 - verify the field type.
  13754. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13755. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13756. // Handle incomplete types with specific error.
  13757. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13758. return ExprError();
  13759. if (FieldName)
  13760. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13761. << FieldName << FieldTy << BitWidth->getSourceRange();
  13762. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13763. << FieldTy << BitWidth->getSourceRange();
  13764. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13765. UPPC_BitFieldWidth))
  13766. return ExprError();
  13767. // If the bit-width is type- or value-dependent, don't try to check
  13768. // it now.
  13769. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13770. return BitWidth;
  13771. llvm::APSInt Value;
  13772. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13773. if (ICE.isInvalid())
  13774. return ICE;
  13775. BitWidth = ICE.get();
  13776. if (Value != 0 && ZeroWidth)
  13777. *ZeroWidth = false;
  13778. // Zero-width bitfield is ok for anonymous field.
  13779. if (Value == 0 && FieldName)
  13780. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13781. if (Value.isSigned() && Value.isNegative()) {
  13782. if (FieldName)
  13783. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13784. << FieldName << Value.toString(10);
  13785. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13786. << Value.toString(10);
  13787. }
  13788. if (!FieldTy->isDependentType()) {
  13789. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13790. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13791. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13792. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13793. // ABI.
  13794. bool CStdConstraintViolation =
  13795. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13796. bool MSBitfieldViolation =
  13797. Value.ugt(TypeStorageSize) &&
  13798. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13799. if (CStdConstraintViolation || MSBitfieldViolation) {
  13800. unsigned DiagWidth =
  13801. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13802. if (FieldName)
  13803. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13804. << FieldName << (unsigned)Value.getZExtValue()
  13805. << !CStdConstraintViolation << DiagWidth;
  13806. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13807. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13808. << DiagWidth;
  13809. }
  13810. // Warn on types where the user might conceivably expect to get all
  13811. // specified bits as value bits: that's all integral types other than
  13812. // 'bool'.
  13813. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13814. if (FieldName)
  13815. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13816. << FieldName << (unsigned)Value.getZExtValue()
  13817. << (unsigned)TypeWidth;
  13818. else
  13819. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13820. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13821. }
  13822. }
  13823. return BitWidth;
  13824. }
  13825. /// ActOnField - Each field of a C struct/union is passed into this in order
  13826. /// to create a FieldDecl object for it.
  13827. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13828. Declarator &D, Expr *BitfieldWidth) {
  13829. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13830. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13831. /*InitStyle=*/ICIS_NoInit, AS_public);
  13832. return Res;
  13833. }
  13834. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13835. ///
  13836. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13837. SourceLocation DeclStart,
  13838. Declarator &D, Expr *BitWidth,
  13839. InClassInitStyle InitStyle,
  13840. AccessSpecifier AS) {
  13841. if (D.isDecompositionDeclarator()) {
  13842. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13843. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13844. << Decomp.getSourceRange();
  13845. return nullptr;
  13846. }
  13847. IdentifierInfo *II = D.getIdentifier();
  13848. SourceLocation Loc = DeclStart;
  13849. if (II) Loc = D.getIdentifierLoc();
  13850. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13851. QualType T = TInfo->getType();
  13852. if (getLangOpts().CPlusPlus) {
  13853. CheckExtraCXXDefaultArguments(D);
  13854. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13855. UPPC_DataMemberType)) {
  13856. D.setInvalidType();
  13857. T = Context.IntTy;
  13858. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13859. }
  13860. }
  13861. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13862. if (D.getDeclSpec().isInlineSpecified())
  13863. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13864. << getLangOpts().CPlusPlus17;
  13865. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13866. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13867. diag::err_invalid_thread)
  13868. << DeclSpec::getSpecifierName(TSCS);
  13869. // Check to see if this name was declared as a member previously
  13870. NamedDecl *PrevDecl = nullptr;
  13871. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13872. ForVisibleRedeclaration);
  13873. LookupName(Previous, S);
  13874. switch (Previous.getResultKind()) {
  13875. case LookupResult::Found:
  13876. case LookupResult::FoundUnresolvedValue:
  13877. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13878. break;
  13879. case LookupResult::FoundOverloaded:
  13880. PrevDecl = Previous.getRepresentativeDecl();
  13881. break;
  13882. case LookupResult::NotFound:
  13883. case LookupResult::NotFoundInCurrentInstantiation:
  13884. case LookupResult::Ambiguous:
  13885. break;
  13886. }
  13887. Previous.suppressDiagnostics();
  13888. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13889. // Maybe we will complain about the shadowed template parameter.
  13890. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13891. // Just pretend that we didn't see the previous declaration.
  13892. PrevDecl = nullptr;
  13893. }
  13894. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13895. PrevDecl = nullptr;
  13896. bool Mutable
  13897. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13898. SourceLocation TSSL = D.getBeginLoc();
  13899. FieldDecl *NewFD
  13900. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13901. TSSL, AS, PrevDecl, &D);
  13902. if (NewFD->isInvalidDecl())
  13903. Record->setInvalidDecl();
  13904. if (D.getDeclSpec().isModulePrivateSpecified())
  13905. NewFD->setModulePrivate();
  13906. if (NewFD->isInvalidDecl() && PrevDecl) {
  13907. // Don't introduce NewFD into scope; there's already something
  13908. // with the same name in the same scope.
  13909. } else if (II) {
  13910. PushOnScopeChains(NewFD, S);
  13911. } else
  13912. Record->addDecl(NewFD);
  13913. return NewFD;
  13914. }
  13915. /// Build a new FieldDecl and check its well-formedness.
  13916. ///
  13917. /// This routine builds a new FieldDecl given the fields name, type,
  13918. /// record, etc. \p PrevDecl should refer to any previous declaration
  13919. /// with the same name and in the same scope as the field to be
  13920. /// created.
  13921. ///
  13922. /// \returns a new FieldDecl.
  13923. ///
  13924. /// \todo The Declarator argument is a hack. It will be removed once
  13925. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13926. TypeSourceInfo *TInfo,
  13927. RecordDecl *Record, SourceLocation Loc,
  13928. bool Mutable, Expr *BitWidth,
  13929. InClassInitStyle InitStyle,
  13930. SourceLocation TSSL,
  13931. AccessSpecifier AS, NamedDecl *PrevDecl,
  13932. Declarator *D) {
  13933. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13934. bool InvalidDecl = false;
  13935. if (D) InvalidDecl = D->isInvalidType();
  13936. // If we receive a broken type, recover by assuming 'int' and
  13937. // marking this declaration as invalid.
  13938. if (T.isNull()) {
  13939. InvalidDecl = true;
  13940. T = Context.IntTy;
  13941. }
  13942. QualType EltTy = Context.getBaseElementType(T);
  13943. if (!EltTy->isDependentType()) {
  13944. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13945. // Fields of incomplete type force their record to be invalid.
  13946. Record->setInvalidDecl();
  13947. InvalidDecl = true;
  13948. } else {
  13949. NamedDecl *Def;
  13950. EltTy->isIncompleteType(&Def);
  13951. if (Def && Def->isInvalidDecl()) {
  13952. Record->setInvalidDecl();
  13953. InvalidDecl = true;
  13954. }
  13955. }
  13956. }
  13957. // TR 18037 does not allow fields to be declared with address space
  13958. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  13959. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13960. Diag(Loc, diag::err_field_with_address_space);
  13961. Record->setInvalidDecl();
  13962. InvalidDecl = true;
  13963. }
  13964. if (LangOpts.OpenCL) {
  13965. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13966. // used as structure or union field: image, sampler, event or block types.
  13967. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  13968. T->isBlockPointerType()) {
  13969. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13970. Record->setInvalidDecl();
  13971. InvalidDecl = true;
  13972. }
  13973. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13974. if (BitWidth) {
  13975. Diag(Loc, diag::err_opencl_bitfields);
  13976. InvalidDecl = true;
  13977. }
  13978. }
  13979. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13980. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13981. T.hasQualifiers()) {
  13982. InvalidDecl = true;
  13983. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13984. }
  13985. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13986. // than a variably modified type.
  13987. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13988. bool SizeIsNegative;
  13989. llvm::APSInt Oversized;
  13990. TypeSourceInfo *FixedTInfo =
  13991. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13992. SizeIsNegative,
  13993. Oversized);
  13994. if (FixedTInfo) {
  13995. Diag(Loc, diag::warn_illegal_constant_array_size);
  13996. TInfo = FixedTInfo;
  13997. T = FixedTInfo->getType();
  13998. } else {
  13999. if (SizeIsNegative)
  14000. Diag(Loc, diag::err_typecheck_negative_array_size);
  14001. else if (Oversized.getBoolValue())
  14002. Diag(Loc, diag::err_array_too_large)
  14003. << Oversized.toString(10);
  14004. else
  14005. Diag(Loc, diag::err_typecheck_field_variable_size);
  14006. InvalidDecl = true;
  14007. }
  14008. }
  14009. // Fields can not have abstract class types
  14010. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  14011. diag::err_abstract_type_in_decl,
  14012. AbstractFieldType))
  14013. InvalidDecl = true;
  14014. bool ZeroWidth = false;
  14015. if (InvalidDecl)
  14016. BitWidth = nullptr;
  14017. // If this is declared as a bit-field, check the bit-field.
  14018. if (BitWidth) {
  14019. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  14020. &ZeroWidth).get();
  14021. if (!BitWidth) {
  14022. InvalidDecl = true;
  14023. BitWidth = nullptr;
  14024. ZeroWidth = false;
  14025. }
  14026. }
  14027. // Check that 'mutable' is consistent with the type of the declaration.
  14028. if (!InvalidDecl && Mutable) {
  14029. unsigned DiagID = 0;
  14030. if (T->isReferenceType())
  14031. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  14032. : diag::err_mutable_reference;
  14033. else if (T.isConstQualified())
  14034. DiagID = diag::err_mutable_const;
  14035. if (DiagID) {
  14036. SourceLocation ErrLoc = Loc;
  14037. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  14038. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  14039. Diag(ErrLoc, DiagID);
  14040. if (DiagID != diag::ext_mutable_reference) {
  14041. Mutable = false;
  14042. InvalidDecl = true;
  14043. }
  14044. }
  14045. }
  14046. // C++11 [class.union]p8 (DR1460):
  14047. // At most one variant member of a union may have a
  14048. // brace-or-equal-initializer.
  14049. if (InitStyle != ICIS_NoInit)
  14050. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  14051. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  14052. BitWidth, Mutable, InitStyle);
  14053. if (InvalidDecl)
  14054. NewFD->setInvalidDecl();
  14055. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  14056. Diag(Loc, diag::err_duplicate_member) << II;
  14057. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14058. NewFD->setInvalidDecl();
  14059. }
  14060. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  14061. if (Record->isUnion()) {
  14062. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14063. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14064. if (RDecl->getDefinition()) {
  14065. // C++ [class.union]p1: An object of a class with a non-trivial
  14066. // constructor, a non-trivial copy constructor, a non-trivial
  14067. // destructor, or a non-trivial copy assignment operator
  14068. // cannot be a member of a union, nor can an array of such
  14069. // objects.
  14070. if (CheckNontrivialField(NewFD))
  14071. NewFD->setInvalidDecl();
  14072. }
  14073. }
  14074. // C++ [class.union]p1: If a union contains a member of reference type,
  14075. // the program is ill-formed, except when compiling with MSVC extensions
  14076. // enabled.
  14077. if (EltTy->isReferenceType()) {
  14078. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  14079. diag::ext_union_member_of_reference_type :
  14080. diag::err_union_member_of_reference_type)
  14081. << NewFD->getDeclName() << EltTy;
  14082. if (!getLangOpts().MicrosoftExt)
  14083. NewFD->setInvalidDecl();
  14084. }
  14085. }
  14086. }
  14087. // FIXME: We need to pass in the attributes given an AST
  14088. // representation, not a parser representation.
  14089. if (D) {
  14090. // FIXME: The current scope is almost... but not entirely... correct here.
  14091. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  14092. if (NewFD->hasAttrs())
  14093. CheckAlignasUnderalignment(NewFD);
  14094. }
  14095. // In auto-retain/release, infer strong retension for fields of
  14096. // retainable type.
  14097. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  14098. NewFD->setInvalidDecl();
  14099. if (T.isObjCGCWeak())
  14100. Diag(Loc, diag::warn_attribute_weak_on_field);
  14101. NewFD->setAccess(AS);
  14102. return NewFD;
  14103. }
  14104. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  14105. assert(FD);
  14106. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  14107. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  14108. return false;
  14109. QualType EltTy = Context.getBaseElementType(FD->getType());
  14110. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14111. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14112. if (RDecl->getDefinition()) {
  14113. // We check for copy constructors before constructors
  14114. // because otherwise we'll never get complaints about
  14115. // copy constructors.
  14116. CXXSpecialMember member = CXXInvalid;
  14117. // We're required to check for any non-trivial constructors. Since the
  14118. // implicit default constructor is suppressed if there are any
  14119. // user-declared constructors, we just need to check that there is a
  14120. // trivial default constructor and a trivial copy constructor. (We don't
  14121. // worry about move constructors here, since this is a C++98 check.)
  14122. if (RDecl->hasNonTrivialCopyConstructor())
  14123. member = CXXCopyConstructor;
  14124. else if (!RDecl->hasTrivialDefaultConstructor())
  14125. member = CXXDefaultConstructor;
  14126. else if (RDecl->hasNonTrivialCopyAssignment())
  14127. member = CXXCopyAssignment;
  14128. else if (RDecl->hasNonTrivialDestructor())
  14129. member = CXXDestructor;
  14130. if (member != CXXInvalid) {
  14131. if (!getLangOpts().CPlusPlus11 &&
  14132. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  14133. // Objective-C++ ARC: it is an error to have a non-trivial field of
  14134. // a union. However, system headers in Objective-C programs
  14135. // occasionally have Objective-C lifetime objects within unions,
  14136. // and rather than cause the program to fail, we make those
  14137. // members unavailable.
  14138. SourceLocation Loc = FD->getLocation();
  14139. if (getSourceManager().isInSystemHeader(Loc)) {
  14140. if (!FD->hasAttr<UnavailableAttr>())
  14141. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14142. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  14143. return false;
  14144. }
  14145. }
  14146. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  14147. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  14148. diag::err_illegal_union_or_anon_struct_member)
  14149. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  14150. DiagnoseNontrivial(RDecl, member);
  14151. return !getLangOpts().CPlusPlus11;
  14152. }
  14153. }
  14154. }
  14155. return false;
  14156. }
  14157. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  14158. /// AST enum value.
  14159. static ObjCIvarDecl::AccessControl
  14160. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  14161. switch (ivarVisibility) {
  14162. default: llvm_unreachable("Unknown visitibility kind");
  14163. case tok::objc_private: return ObjCIvarDecl::Private;
  14164. case tok::objc_public: return ObjCIvarDecl::Public;
  14165. case tok::objc_protected: return ObjCIvarDecl::Protected;
  14166. case tok::objc_package: return ObjCIvarDecl::Package;
  14167. }
  14168. }
  14169. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  14170. /// in order to create an IvarDecl object for it.
  14171. Decl *Sema::ActOnIvar(Scope *S,
  14172. SourceLocation DeclStart,
  14173. Declarator &D, Expr *BitfieldWidth,
  14174. tok::ObjCKeywordKind Visibility) {
  14175. IdentifierInfo *II = D.getIdentifier();
  14176. Expr *BitWidth = (Expr*)BitfieldWidth;
  14177. SourceLocation Loc = DeclStart;
  14178. if (II) Loc = D.getIdentifierLoc();
  14179. // FIXME: Unnamed fields can be handled in various different ways, for
  14180. // example, unnamed unions inject all members into the struct namespace!
  14181. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14182. QualType T = TInfo->getType();
  14183. if (BitWidth) {
  14184. // 6.7.2.1p3, 6.7.2.1p4
  14185. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  14186. if (!BitWidth)
  14187. D.setInvalidType();
  14188. } else {
  14189. // Not a bitfield.
  14190. // validate II.
  14191. }
  14192. if (T->isReferenceType()) {
  14193. Diag(Loc, diag::err_ivar_reference_type);
  14194. D.setInvalidType();
  14195. }
  14196. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14197. // than a variably modified type.
  14198. else if (T->isVariablyModifiedType()) {
  14199. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  14200. D.setInvalidType();
  14201. }
  14202. // Get the visibility (access control) for this ivar.
  14203. ObjCIvarDecl::AccessControl ac =
  14204. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  14205. : ObjCIvarDecl::None;
  14206. // Must set ivar's DeclContext to its enclosing interface.
  14207. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  14208. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  14209. return nullptr;
  14210. ObjCContainerDecl *EnclosingContext;
  14211. if (ObjCImplementationDecl *IMPDecl =
  14212. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14213. if (LangOpts.ObjCRuntime.isFragile()) {
  14214. // Case of ivar declared in an implementation. Context is that of its class.
  14215. EnclosingContext = IMPDecl->getClassInterface();
  14216. assert(EnclosingContext && "Implementation has no class interface!");
  14217. }
  14218. else
  14219. EnclosingContext = EnclosingDecl;
  14220. } else {
  14221. if (ObjCCategoryDecl *CDecl =
  14222. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14223. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  14224. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  14225. return nullptr;
  14226. }
  14227. }
  14228. EnclosingContext = EnclosingDecl;
  14229. }
  14230. // Construct the decl.
  14231. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  14232. DeclStart, Loc, II, T,
  14233. TInfo, ac, (Expr *)BitfieldWidth);
  14234. if (II) {
  14235. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  14236. ForVisibleRedeclaration);
  14237. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  14238. && !isa<TagDecl>(PrevDecl)) {
  14239. Diag(Loc, diag::err_duplicate_member) << II;
  14240. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14241. NewID->setInvalidDecl();
  14242. }
  14243. }
  14244. // Process attributes attached to the ivar.
  14245. ProcessDeclAttributes(S, NewID, D);
  14246. if (D.isInvalidType())
  14247. NewID->setInvalidDecl();
  14248. // In ARC, infer 'retaining' for ivars of retainable type.
  14249. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  14250. NewID->setInvalidDecl();
  14251. if (D.getDeclSpec().isModulePrivateSpecified())
  14252. NewID->setModulePrivate();
  14253. if (II) {
  14254. // FIXME: When interfaces are DeclContexts, we'll need to add
  14255. // these to the interface.
  14256. S->AddDecl(NewID);
  14257. IdResolver.AddDecl(NewID);
  14258. }
  14259. if (LangOpts.ObjCRuntime.isNonFragile() &&
  14260. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  14261. Diag(Loc, diag::warn_ivars_in_interface);
  14262. return NewID;
  14263. }
  14264. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  14265. /// class and class extensions. For every class \@interface and class
  14266. /// extension \@interface, if the last ivar is a bitfield of any type,
  14267. /// then add an implicit `char :0` ivar to the end of that interface.
  14268. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  14269. SmallVectorImpl<Decl *> &AllIvarDecls) {
  14270. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  14271. return;
  14272. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  14273. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  14274. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  14275. return;
  14276. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  14277. if (!ID) {
  14278. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  14279. if (!CD->IsClassExtension())
  14280. return;
  14281. }
  14282. // No need to add this to end of @implementation.
  14283. else
  14284. return;
  14285. }
  14286. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14287. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14288. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14289. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14290. DeclLoc, DeclLoc, nullptr,
  14291. Context.CharTy,
  14292. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14293. DeclLoc),
  14294. ObjCIvarDecl::Private, BW,
  14295. true);
  14296. AllIvarDecls.push_back(Ivar);
  14297. }
  14298. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14299. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14300. SourceLocation RBrac,
  14301. const ParsedAttributesView &Attrs) {
  14302. assert(EnclosingDecl && "missing record or interface decl");
  14303. // If this is an Objective-C @implementation or category and we have
  14304. // new fields here we should reset the layout of the interface since
  14305. // it will now change.
  14306. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14307. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14308. switch (DC->getKind()) {
  14309. default: break;
  14310. case Decl::ObjCCategory:
  14311. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14312. break;
  14313. case Decl::ObjCImplementation:
  14314. Context.
  14315. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14316. break;
  14317. }
  14318. }
  14319. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14320. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14321. // Start counting up the number of named members; make sure to include
  14322. // members of anonymous structs and unions in the total.
  14323. unsigned NumNamedMembers = 0;
  14324. if (Record) {
  14325. for (const auto *I : Record->decls()) {
  14326. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14327. if (IFD->getDeclName())
  14328. ++NumNamedMembers;
  14329. }
  14330. }
  14331. // Verify that all the fields are okay.
  14332. SmallVector<FieldDecl*, 32> RecFields;
  14333. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14334. i != end; ++i) {
  14335. FieldDecl *FD = cast<FieldDecl>(*i);
  14336. // Get the type for the field.
  14337. const Type *FDTy = FD->getType().getTypePtr();
  14338. if (!FD->isAnonymousStructOrUnion()) {
  14339. // Remember all fields written by the user.
  14340. RecFields.push_back(FD);
  14341. }
  14342. // If the field is already invalid for some reason, don't emit more
  14343. // diagnostics about it.
  14344. if (FD->isInvalidDecl()) {
  14345. EnclosingDecl->setInvalidDecl();
  14346. continue;
  14347. }
  14348. // C99 6.7.2.1p2:
  14349. // A structure or union shall not contain a member with
  14350. // incomplete or function type (hence, a structure shall not
  14351. // contain an instance of itself, but may contain a pointer to
  14352. // an instance of itself), except that the last member of a
  14353. // structure with more than one named member may have incomplete
  14354. // array type; such a structure (and any union containing,
  14355. // possibly recursively, a member that is such a structure)
  14356. // shall not be a member of a structure or an element of an
  14357. // array.
  14358. bool IsLastField = (i + 1 == Fields.end());
  14359. if (FDTy->isFunctionType()) {
  14360. // Field declared as a function.
  14361. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14362. << FD->getDeclName();
  14363. FD->setInvalidDecl();
  14364. EnclosingDecl->setInvalidDecl();
  14365. continue;
  14366. } else if (FDTy->isIncompleteArrayType() &&
  14367. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14368. if (Record) {
  14369. // Flexible array member.
  14370. // Microsoft and g++ is more permissive regarding flexible array.
  14371. // It will accept flexible array in union and also
  14372. // as the sole element of a struct/class.
  14373. unsigned DiagID = 0;
  14374. if (!Record->isUnion() && !IsLastField) {
  14375. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14376. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14377. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14378. FD->setInvalidDecl();
  14379. EnclosingDecl->setInvalidDecl();
  14380. continue;
  14381. } else if (Record->isUnion())
  14382. DiagID = getLangOpts().MicrosoftExt
  14383. ? diag::ext_flexible_array_union_ms
  14384. : getLangOpts().CPlusPlus
  14385. ? diag::ext_flexible_array_union_gnu
  14386. : diag::err_flexible_array_union;
  14387. else if (NumNamedMembers < 1)
  14388. DiagID = getLangOpts().MicrosoftExt
  14389. ? diag::ext_flexible_array_empty_aggregate_ms
  14390. : getLangOpts().CPlusPlus
  14391. ? diag::ext_flexible_array_empty_aggregate_gnu
  14392. : diag::err_flexible_array_empty_aggregate;
  14393. if (DiagID)
  14394. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14395. << Record->getTagKind();
  14396. // While the layout of types that contain virtual bases is not specified
  14397. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14398. // virtual bases after the derived members. This would make a flexible
  14399. // array member declared at the end of an object not adjacent to the end
  14400. // of the type.
  14401. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14402. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14403. << FD->getDeclName() << Record->getTagKind();
  14404. if (!getLangOpts().C99)
  14405. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14406. << FD->getDeclName() << Record->getTagKind();
  14407. // If the element type has a non-trivial destructor, we would not
  14408. // implicitly destroy the elements, so disallow it for now.
  14409. //
  14410. // FIXME: GCC allows this. We should probably either implicitly delete
  14411. // the destructor of the containing class, or just allow this.
  14412. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14413. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14414. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14415. << FD->getDeclName() << FD->getType();
  14416. FD->setInvalidDecl();
  14417. EnclosingDecl->setInvalidDecl();
  14418. continue;
  14419. }
  14420. // Okay, we have a legal flexible array member at the end of the struct.
  14421. Record->setHasFlexibleArrayMember(true);
  14422. } else {
  14423. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14424. // unless they are followed by another ivar. That check is done
  14425. // elsewhere, after synthesized ivars are known.
  14426. }
  14427. } else if (!FDTy->isDependentType() &&
  14428. RequireCompleteType(FD->getLocation(), FD->getType(),
  14429. diag::err_field_incomplete)) {
  14430. // Incomplete type
  14431. FD->setInvalidDecl();
  14432. EnclosingDecl->setInvalidDecl();
  14433. continue;
  14434. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14435. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14436. // A type which contains a flexible array member is considered to be a
  14437. // flexible array member.
  14438. Record->setHasFlexibleArrayMember(true);
  14439. if (!Record->isUnion()) {
  14440. // If this is a struct/class and this is not the last element, reject
  14441. // it. Note that GCC supports variable sized arrays in the middle of
  14442. // structures.
  14443. if (!IsLastField)
  14444. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14445. << FD->getDeclName() << FD->getType();
  14446. else {
  14447. // We support flexible arrays at the end of structs in
  14448. // other structs as an extension.
  14449. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14450. << FD->getDeclName();
  14451. }
  14452. }
  14453. }
  14454. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14455. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14456. diag::err_abstract_type_in_decl,
  14457. AbstractIvarType)) {
  14458. // Ivars can not have abstract class types
  14459. FD->setInvalidDecl();
  14460. }
  14461. if (Record && FDTTy->getDecl()->hasObjectMember())
  14462. Record->setHasObjectMember(true);
  14463. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14464. Record->setHasVolatileMember(true);
  14465. } else if (FDTy->isObjCObjectType()) {
  14466. /// A field cannot be an Objective-c object
  14467. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14468. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14469. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14470. FD->setType(T);
  14471. } else if (getLangOpts().ObjC &&
  14472. getLangOpts().getGC() != LangOptions::NonGC &&
  14473. Record && !Record->hasObjectMember()) {
  14474. if (FD->getType()->isObjCObjectPointerType() ||
  14475. FD->getType().isObjCGCStrong())
  14476. Record->setHasObjectMember(true);
  14477. else if (Context.getAsArrayType(FD->getType())) {
  14478. QualType BaseType = Context.getBaseElementType(FD->getType());
  14479. if (BaseType->isRecordType() &&
  14480. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  14481. Record->setHasObjectMember(true);
  14482. else if (BaseType->isObjCObjectPointerType() ||
  14483. BaseType.isObjCGCStrong())
  14484. Record->setHasObjectMember(true);
  14485. }
  14486. }
  14487. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  14488. QualType FT = FD->getType();
  14489. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  14490. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14491. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  14492. Record->isUnion())
  14493. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  14494. }
  14495. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14496. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  14497. Record->setNonTrivialToPrimitiveCopy(true);
  14498. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  14499. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  14500. }
  14501. if (FT.isDestructedType()) {
  14502. Record->setNonTrivialToPrimitiveDestroy(true);
  14503. Record->setParamDestroyedInCallee(true);
  14504. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  14505. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  14506. }
  14507. if (const auto *RT = FT->getAs<RecordType>()) {
  14508. if (RT->getDecl()->getArgPassingRestrictions() ==
  14509. RecordDecl::APK_CanNeverPassInRegs)
  14510. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14511. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14512. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14513. }
  14514. if (Record && FD->getType().isVolatileQualified())
  14515. Record->setHasVolatileMember(true);
  14516. // Keep track of the number of named members.
  14517. if (FD->getIdentifier())
  14518. ++NumNamedMembers;
  14519. }
  14520. // Okay, we successfully defined 'Record'.
  14521. if (Record) {
  14522. bool Completed = false;
  14523. if (CXXRecord) {
  14524. if (!CXXRecord->isInvalidDecl()) {
  14525. // Set access bits correctly on the directly-declared conversions.
  14526. for (CXXRecordDecl::conversion_iterator
  14527. I = CXXRecord->conversion_begin(),
  14528. E = CXXRecord->conversion_end(); I != E; ++I)
  14529. I.setAccess((*I)->getAccess());
  14530. }
  14531. if (!CXXRecord->isDependentType()) {
  14532. // Add any implicitly-declared members to this class.
  14533. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14534. if (!CXXRecord->isInvalidDecl()) {
  14535. // If we have virtual base classes, we may end up finding multiple
  14536. // final overriders for a given virtual function. Check for this
  14537. // problem now.
  14538. if (CXXRecord->getNumVBases()) {
  14539. CXXFinalOverriderMap FinalOverriders;
  14540. CXXRecord->getFinalOverriders(FinalOverriders);
  14541. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14542. MEnd = FinalOverriders.end();
  14543. M != MEnd; ++M) {
  14544. for (OverridingMethods::iterator SO = M->second.begin(),
  14545. SOEnd = M->second.end();
  14546. SO != SOEnd; ++SO) {
  14547. assert(SO->second.size() > 0 &&
  14548. "Virtual function without overriding functions?");
  14549. if (SO->second.size() == 1)
  14550. continue;
  14551. // C++ [class.virtual]p2:
  14552. // In a derived class, if a virtual member function of a base
  14553. // class subobject has more than one final overrider the
  14554. // program is ill-formed.
  14555. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14556. << (const NamedDecl *)M->first << Record;
  14557. Diag(M->first->getLocation(),
  14558. diag::note_overridden_virtual_function);
  14559. for (OverridingMethods::overriding_iterator
  14560. OM = SO->second.begin(),
  14561. OMEnd = SO->second.end();
  14562. OM != OMEnd; ++OM)
  14563. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14564. << (const NamedDecl *)M->first << OM->Method->getParent();
  14565. Record->setInvalidDecl();
  14566. }
  14567. }
  14568. CXXRecord->completeDefinition(&FinalOverriders);
  14569. Completed = true;
  14570. }
  14571. }
  14572. }
  14573. }
  14574. if (!Completed)
  14575. Record->completeDefinition();
  14576. // Handle attributes before checking the layout.
  14577. ProcessDeclAttributeList(S, Record, Attrs);
  14578. // We may have deferred checking for a deleted destructor. Check now.
  14579. if (CXXRecord) {
  14580. auto *Dtor = CXXRecord->getDestructor();
  14581. if (Dtor && Dtor->isImplicit() &&
  14582. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14583. CXXRecord->setImplicitDestructorIsDeleted();
  14584. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14585. }
  14586. }
  14587. if (Record->hasAttrs()) {
  14588. CheckAlignasUnderalignment(Record);
  14589. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14590. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14591. IA->getRange(), IA->getBestCase(),
  14592. IA->getSemanticSpelling());
  14593. }
  14594. // Check if the structure/union declaration is a type that can have zero
  14595. // size in C. For C this is a language extension, for C++ it may cause
  14596. // compatibility problems.
  14597. bool CheckForZeroSize;
  14598. if (!getLangOpts().CPlusPlus) {
  14599. CheckForZeroSize = true;
  14600. } else {
  14601. // For C++ filter out types that cannot be referenced in C code.
  14602. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14603. CheckForZeroSize =
  14604. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14605. !CXXRecord->isDependentType() &&
  14606. CXXRecord->isCLike();
  14607. }
  14608. if (CheckForZeroSize) {
  14609. bool ZeroSize = true;
  14610. bool IsEmpty = true;
  14611. unsigned NonBitFields = 0;
  14612. for (RecordDecl::field_iterator I = Record->field_begin(),
  14613. E = Record->field_end();
  14614. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14615. IsEmpty = false;
  14616. if (I->isUnnamedBitfield()) {
  14617. if (!I->isZeroLengthBitField(Context))
  14618. ZeroSize = false;
  14619. } else {
  14620. ++NonBitFields;
  14621. QualType FieldType = I->getType();
  14622. if (FieldType->isIncompleteType() ||
  14623. !Context.getTypeSizeInChars(FieldType).isZero())
  14624. ZeroSize = false;
  14625. }
  14626. }
  14627. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14628. // allowed in C++, but warn if its declaration is inside
  14629. // extern "C" block.
  14630. if (ZeroSize) {
  14631. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14632. diag::warn_zero_size_struct_union_in_extern_c :
  14633. diag::warn_zero_size_struct_union_compat)
  14634. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14635. }
  14636. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14637. // but are accepted by GCC.
  14638. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14639. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14640. diag::ext_no_named_members_in_struct_union)
  14641. << Record->isUnion();
  14642. }
  14643. }
  14644. } else {
  14645. ObjCIvarDecl **ClsFields =
  14646. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14647. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14648. ID->setEndOfDefinitionLoc(RBrac);
  14649. // Add ivar's to class's DeclContext.
  14650. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14651. ClsFields[i]->setLexicalDeclContext(ID);
  14652. ID->addDecl(ClsFields[i]);
  14653. }
  14654. // Must enforce the rule that ivars in the base classes may not be
  14655. // duplicates.
  14656. if (ID->getSuperClass())
  14657. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14658. } else if (ObjCImplementationDecl *IMPDecl =
  14659. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14660. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14661. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14662. // Ivar declared in @implementation never belongs to the implementation.
  14663. // Only it is in implementation's lexical context.
  14664. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14665. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14666. IMPDecl->setIvarLBraceLoc(LBrac);
  14667. IMPDecl->setIvarRBraceLoc(RBrac);
  14668. } else if (ObjCCategoryDecl *CDecl =
  14669. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14670. // case of ivars in class extension; all other cases have been
  14671. // reported as errors elsewhere.
  14672. // FIXME. Class extension does not have a LocEnd field.
  14673. // CDecl->setLocEnd(RBrac);
  14674. // Add ivar's to class extension's DeclContext.
  14675. // Diagnose redeclaration of private ivars.
  14676. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14677. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14678. if (IDecl) {
  14679. if (const ObjCIvarDecl *ClsIvar =
  14680. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14681. Diag(ClsFields[i]->getLocation(),
  14682. diag::err_duplicate_ivar_declaration);
  14683. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14684. continue;
  14685. }
  14686. for (const auto *Ext : IDecl->known_extensions()) {
  14687. if (const ObjCIvarDecl *ClsExtIvar
  14688. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14689. Diag(ClsFields[i]->getLocation(),
  14690. diag::err_duplicate_ivar_declaration);
  14691. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14692. continue;
  14693. }
  14694. }
  14695. }
  14696. ClsFields[i]->setLexicalDeclContext(CDecl);
  14697. CDecl->addDecl(ClsFields[i]);
  14698. }
  14699. CDecl->setIvarLBraceLoc(LBrac);
  14700. CDecl->setIvarRBraceLoc(RBrac);
  14701. }
  14702. }
  14703. }
  14704. /// Determine whether the given integral value is representable within
  14705. /// the given type T.
  14706. static bool isRepresentableIntegerValue(ASTContext &Context,
  14707. llvm::APSInt &Value,
  14708. QualType T) {
  14709. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14710. "Integral type required!");
  14711. unsigned BitWidth = Context.getIntWidth(T);
  14712. if (Value.isUnsigned() || Value.isNonNegative()) {
  14713. if (T->isSignedIntegerOrEnumerationType())
  14714. --BitWidth;
  14715. return Value.getActiveBits() <= BitWidth;
  14716. }
  14717. return Value.getMinSignedBits() <= BitWidth;
  14718. }
  14719. // Given an integral type, return the next larger integral type
  14720. // (or a NULL type of no such type exists).
  14721. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14722. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14723. // enum checking below.
  14724. assert((T->isIntegralType(Context) ||
  14725. T->isEnumeralType()) && "Integral type required!");
  14726. const unsigned NumTypes = 4;
  14727. QualType SignedIntegralTypes[NumTypes] = {
  14728. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14729. };
  14730. QualType UnsignedIntegralTypes[NumTypes] = {
  14731. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14732. Context.UnsignedLongLongTy
  14733. };
  14734. unsigned BitWidth = Context.getTypeSize(T);
  14735. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14736. : UnsignedIntegralTypes;
  14737. for (unsigned I = 0; I != NumTypes; ++I)
  14738. if (Context.getTypeSize(Types[I]) > BitWidth)
  14739. return Types[I];
  14740. return QualType();
  14741. }
  14742. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14743. EnumConstantDecl *LastEnumConst,
  14744. SourceLocation IdLoc,
  14745. IdentifierInfo *Id,
  14746. Expr *Val) {
  14747. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14748. llvm::APSInt EnumVal(IntWidth);
  14749. QualType EltTy;
  14750. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14751. Val = nullptr;
  14752. if (Val)
  14753. Val = DefaultLvalueConversion(Val).get();
  14754. if (Val) {
  14755. if (Enum->isDependentType() || Val->isTypeDependent())
  14756. EltTy = Context.DependentTy;
  14757. else {
  14758. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  14759. !getLangOpts().MSVCCompat) {
  14760. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14761. // constant-expression in the enumerator-definition shall be a converted
  14762. // constant expression of the underlying type.
  14763. EltTy = Enum->getIntegerType();
  14764. ExprResult Converted =
  14765. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14766. CCEK_Enumerator);
  14767. if (Converted.isInvalid())
  14768. Val = nullptr;
  14769. else
  14770. Val = Converted.get();
  14771. } else if (!Val->isValueDependent() &&
  14772. !(Val = VerifyIntegerConstantExpression(Val,
  14773. &EnumVal).get())) {
  14774. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14775. } else {
  14776. if (Enum->isComplete()) {
  14777. EltTy = Enum->getIntegerType();
  14778. // In Obj-C and Microsoft mode, require the enumeration value to be
  14779. // representable in the underlying type of the enumeration. In C++11,
  14780. // we perform a non-narrowing conversion as part of converted constant
  14781. // expression checking.
  14782. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14783. if (getLangOpts().MSVCCompat) {
  14784. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14785. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  14786. } else
  14787. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14788. } else
  14789. Val = ImpCastExprToType(Val, EltTy,
  14790. EltTy->isBooleanType() ?
  14791. CK_IntegralToBoolean : CK_IntegralCast)
  14792. .get();
  14793. } else if (getLangOpts().CPlusPlus) {
  14794. // C++11 [dcl.enum]p5:
  14795. // If the underlying type is not fixed, the type of each enumerator
  14796. // is the type of its initializing value:
  14797. // - If an initializer is specified for an enumerator, the
  14798. // initializing value has the same type as the expression.
  14799. EltTy = Val->getType();
  14800. } else {
  14801. // C99 6.7.2.2p2:
  14802. // The expression that defines the value of an enumeration constant
  14803. // shall be an integer constant expression that has a value
  14804. // representable as an int.
  14805. // Complain if the value is not representable in an int.
  14806. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14807. Diag(IdLoc, diag::ext_enum_value_not_int)
  14808. << EnumVal.toString(10) << Val->getSourceRange()
  14809. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14810. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14811. // Force the type of the expression to 'int'.
  14812. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14813. }
  14814. EltTy = Val->getType();
  14815. }
  14816. }
  14817. }
  14818. }
  14819. if (!Val) {
  14820. if (Enum->isDependentType())
  14821. EltTy = Context.DependentTy;
  14822. else if (!LastEnumConst) {
  14823. // C++0x [dcl.enum]p5:
  14824. // If the underlying type is not fixed, the type of each enumerator
  14825. // is the type of its initializing value:
  14826. // - If no initializer is specified for the first enumerator, the
  14827. // initializing value has an unspecified integral type.
  14828. //
  14829. // GCC uses 'int' for its unspecified integral type, as does
  14830. // C99 6.7.2.2p3.
  14831. if (Enum->isFixed()) {
  14832. EltTy = Enum->getIntegerType();
  14833. }
  14834. else {
  14835. EltTy = Context.IntTy;
  14836. }
  14837. } else {
  14838. // Assign the last value + 1.
  14839. EnumVal = LastEnumConst->getInitVal();
  14840. ++EnumVal;
  14841. EltTy = LastEnumConst->getType();
  14842. // Check for overflow on increment.
  14843. if (EnumVal < LastEnumConst->getInitVal()) {
  14844. // C++0x [dcl.enum]p5:
  14845. // If the underlying type is not fixed, the type of each enumerator
  14846. // is the type of its initializing value:
  14847. //
  14848. // - Otherwise the type of the initializing value is the same as
  14849. // the type of the initializing value of the preceding enumerator
  14850. // unless the incremented value is not representable in that type,
  14851. // in which case the type is an unspecified integral type
  14852. // sufficient to contain the incremented value. If no such type
  14853. // exists, the program is ill-formed.
  14854. QualType T = getNextLargerIntegralType(Context, EltTy);
  14855. if (T.isNull() || Enum->isFixed()) {
  14856. // There is no integral type larger enough to represent this
  14857. // value. Complain, then allow the value to wrap around.
  14858. EnumVal = LastEnumConst->getInitVal();
  14859. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14860. ++EnumVal;
  14861. if (Enum->isFixed())
  14862. // When the underlying type is fixed, this is ill-formed.
  14863. Diag(IdLoc, diag::err_enumerator_wrapped)
  14864. << EnumVal.toString(10)
  14865. << EltTy;
  14866. else
  14867. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14868. << EnumVal.toString(10);
  14869. } else {
  14870. EltTy = T;
  14871. }
  14872. // Retrieve the last enumerator's value, extent that type to the
  14873. // type that is supposed to be large enough to represent the incremented
  14874. // value, then increment.
  14875. EnumVal = LastEnumConst->getInitVal();
  14876. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14877. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14878. ++EnumVal;
  14879. // If we're not in C++, diagnose the overflow of enumerator values,
  14880. // which in C99 means that the enumerator value is not representable in
  14881. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14882. // permits enumerator values that are representable in some larger
  14883. // integral type.
  14884. if (!getLangOpts().CPlusPlus && !T.isNull())
  14885. Diag(IdLoc, diag::warn_enum_value_overflow);
  14886. } else if (!getLangOpts().CPlusPlus &&
  14887. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14888. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14889. Diag(IdLoc, diag::ext_enum_value_not_int)
  14890. << EnumVal.toString(10) << 1;
  14891. }
  14892. }
  14893. }
  14894. if (!EltTy->isDependentType()) {
  14895. // Make the enumerator value match the signedness and size of the
  14896. // enumerator's type.
  14897. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14898. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14899. }
  14900. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14901. Val, EnumVal);
  14902. }
  14903. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14904. SourceLocation IILoc) {
  14905. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14906. !getLangOpts().CPlusPlus)
  14907. return SkipBodyInfo();
  14908. // We have an anonymous enum definition. Look up the first enumerator to
  14909. // determine if we should merge the definition with an existing one and
  14910. // skip the body.
  14911. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14912. forRedeclarationInCurContext());
  14913. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14914. if (!PrevECD)
  14915. return SkipBodyInfo();
  14916. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14917. NamedDecl *Hidden;
  14918. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14919. SkipBodyInfo Skip;
  14920. Skip.Previous = Hidden;
  14921. return Skip;
  14922. }
  14923. return SkipBodyInfo();
  14924. }
  14925. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14926. SourceLocation IdLoc, IdentifierInfo *Id,
  14927. const ParsedAttributesView &Attrs,
  14928. SourceLocation EqualLoc, Expr *Val) {
  14929. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14930. EnumConstantDecl *LastEnumConst =
  14931. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14932. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14933. // we find one that is.
  14934. S = getNonFieldDeclScope(S);
  14935. // Verify that there isn't already something declared with this name in this
  14936. // scope.
  14937. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  14938. LookupName(R, S);
  14939. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  14940. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14941. // Maybe we will complain about the shadowed template parameter.
  14942. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14943. // Just pretend that we didn't see the previous declaration.
  14944. PrevDecl = nullptr;
  14945. }
  14946. // C++ [class.mem]p15:
  14947. // If T is the name of a class, then each of the following shall have a name
  14948. // different from T:
  14949. // - every enumerator of every member of class T that is an unscoped
  14950. // enumerated type
  14951. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14952. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14953. DeclarationNameInfo(Id, IdLoc));
  14954. EnumConstantDecl *New =
  14955. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14956. if (!New)
  14957. return nullptr;
  14958. if (PrevDecl) {
  14959. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  14960. // Check for other kinds of shadowing not already handled.
  14961. CheckShadow(New, PrevDecl, R);
  14962. }
  14963. // When in C++, we may get a TagDecl with the same name; in this case the
  14964. // enum constant will 'hide' the tag.
  14965. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14966. "Received TagDecl when not in C++!");
  14967. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14968. if (isa<EnumConstantDecl>(PrevDecl))
  14969. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14970. else
  14971. Diag(IdLoc, diag::err_redefinition) << Id;
  14972. notePreviousDefinition(PrevDecl, IdLoc);
  14973. return nullptr;
  14974. }
  14975. }
  14976. // Process attributes.
  14977. ProcessDeclAttributeList(S, New, Attrs);
  14978. AddPragmaAttributes(S, New);
  14979. // Register this decl in the current scope stack.
  14980. New->setAccess(TheEnumDecl->getAccess());
  14981. PushOnScopeChains(New, S);
  14982. ActOnDocumentableDecl(New);
  14983. return New;
  14984. }
  14985. // Returns true when the enum initial expression does not trigger the
  14986. // duplicate enum warning. A few common cases are exempted as follows:
  14987. // Element2 = Element1
  14988. // Element2 = Element1 + 1
  14989. // Element2 = Element1 - 1
  14990. // Where Element2 and Element1 are from the same enum.
  14991. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14992. Expr *InitExpr = ECD->getInitExpr();
  14993. if (!InitExpr)
  14994. return true;
  14995. InitExpr = InitExpr->IgnoreImpCasts();
  14996. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14997. if (!BO->isAdditiveOp())
  14998. return true;
  14999. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  15000. if (!IL)
  15001. return true;
  15002. if (IL->getValue() != 1)
  15003. return true;
  15004. InitExpr = BO->getLHS();
  15005. }
  15006. // This checks if the elements are from the same enum.
  15007. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  15008. if (!DRE)
  15009. return true;
  15010. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  15011. if (!EnumConstant)
  15012. return true;
  15013. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  15014. Enum)
  15015. return true;
  15016. return false;
  15017. }
  15018. // Emits a warning when an element is implicitly set a value that
  15019. // a previous element has already been set to.
  15020. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  15021. EnumDecl *Enum, QualType EnumType) {
  15022. // Avoid anonymous enums
  15023. if (!Enum->getIdentifier())
  15024. return;
  15025. // Only check for small enums.
  15026. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  15027. return;
  15028. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  15029. return;
  15030. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  15031. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  15032. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  15033. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  15034. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  15035. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  15036. llvm::APSInt Val = D->getInitVal();
  15037. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  15038. };
  15039. DuplicatesVector DupVector;
  15040. ValueToVectorMap EnumMap;
  15041. // Populate the EnumMap with all values represented by enum constants without
  15042. // an initializer.
  15043. for (auto *Element : Elements) {
  15044. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  15045. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  15046. // this constant. Skip this enum since it may be ill-formed.
  15047. if (!ECD) {
  15048. return;
  15049. }
  15050. // Constants with initalizers are handled in the next loop.
  15051. if (ECD->getInitExpr())
  15052. continue;
  15053. // Duplicate values are handled in the next loop.
  15054. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  15055. }
  15056. if (EnumMap.size() == 0)
  15057. return;
  15058. // Create vectors for any values that has duplicates.
  15059. for (auto *Element : Elements) {
  15060. // The last loop returned if any constant was null.
  15061. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  15062. if (!ValidDuplicateEnum(ECD, Enum))
  15063. continue;
  15064. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  15065. if (Iter == EnumMap.end())
  15066. continue;
  15067. DeclOrVector& Entry = Iter->second;
  15068. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  15069. // Ensure constants are different.
  15070. if (D == ECD)
  15071. continue;
  15072. // Create new vector and push values onto it.
  15073. auto Vec = llvm::make_unique<ECDVector>();
  15074. Vec->push_back(D);
  15075. Vec->push_back(ECD);
  15076. // Update entry to point to the duplicates vector.
  15077. Entry = Vec.get();
  15078. // Store the vector somewhere we can consult later for quick emission of
  15079. // diagnostics.
  15080. DupVector.emplace_back(std::move(Vec));
  15081. continue;
  15082. }
  15083. ECDVector *Vec = Entry.get<ECDVector*>();
  15084. // Make sure constants are not added more than once.
  15085. if (*Vec->begin() == ECD)
  15086. continue;
  15087. Vec->push_back(ECD);
  15088. }
  15089. // Emit diagnostics.
  15090. for (const auto &Vec : DupVector) {
  15091. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  15092. // Emit warning for one enum constant.
  15093. auto *FirstECD = Vec->front();
  15094. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  15095. << FirstECD << FirstECD->getInitVal().toString(10)
  15096. << FirstECD->getSourceRange();
  15097. // Emit one note for each of the remaining enum constants with
  15098. // the same value.
  15099. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  15100. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  15101. << ECD << ECD->getInitVal().toString(10)
  15102. << ECD->getSourceRange();
  15103. }
  15104. }
  15105. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  15106. bool AllowMask) const {
  15107. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  15108. assert(ED->isCompleteDefinition() && "expected enum definition");
  15109. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  15110. llvm::APInt &FlagBits = R.first->second;
  15111. if (R.second) {
  15112. for (auto *E : ED->enumerators()) {
  15113. const auto &EVal = E->getInitVal();
  15114. // Only single-bit enumerators introduce new flag values.
  15115. if (EVal.isPowerOf2())
  15116. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  15117. }
  15118. }
  15119. // A value is in a flag enum if either its bits are a subset of the enum's
  15120. // flag bits (the first condition) or we are allowing masks and the same is
  15121. // true of its complement (the second condition). When masks are allowed, we
  15122. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  15123. //
  15124. // While it's true that any value could be used as a mask, the assumption is
  15125. // that a mask will have all of the insignificant bits set. Anything else is
  15126. // likely a logic error.
  15127. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  15128. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  15129. }
  15130. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  15131. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  15132. const ParsedAttributesView &Attrs) {
  15133. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  15134. QualType EnumType = Context.getTypeDeclType(Enum);
  15135. ProcessDeclAttributeList(S, Enum, Attrs);
  15136. if (Enum->isDependentType()) {
  15137. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15138. EnumConstantDecl *ECD =
  15139. cast_or_null<EnumConstantDecl>(Elements[i]);
  15140. if (!ECD) continue;
  15141. ECD->setType(EnumType);
  15142. }
  15143. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  15144. return;
  15145. }
  15146. // TODO: If the result value doesn't fit in an int, it must be a long or long
  15147. // long value. ISO C does not support this, but GCC does as an extension,
  15148. // emit a warning.
  15149. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15150. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  15151. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  15152. // Verify that all the values are okay, compute the size of the values, and
  15153. // reverse the list.
  15154. unsigned NumNegativeBits = 0;
  15155. unsigned NumPositiveBits = 0;
  15156. // Keep track of whether all elements have type int.
  15157. bool AllElementsInt = true;
  15158. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15159. EnumConstantDecl *ECD =
  15160. cast_or_null<EnumConstantDecl>(Elements[i]);
  15161. if (!ECD) continue; // Already issued a diagnostic.
  15162. const llvm::APSInt &InitVal = ECD->getInitVal();
  15163. // Keep track of the size of positive and negative values.
  15164. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  15165. NumPositiveBits = std::max(NumPositiveBits,
  15166. (unsigned)InitVal.getActiveBits());
  15167. else
  15168. NumNegativeBits = std::max(NumNegativeBits,
  15169. (unsigned)InitVal.getMinSignedBits());
  15170. // Keep track of whether every enum element has type int (very common).
  15171. if (AllElementsInt)
  15172. AllElementsInt = ECD->getType() == Context.IntTy;
  15173. }
  15174. // Figure out the type that should be used for this enum.
  15175. QualType BestType;
  15176. unsigned BestWidth;
  15177. // C++0x N3000 [conv.prom]p3:
  15178. // An rvalue of an unscoped enumeration type whose underlying
  15179. // type is not fixed can be converted to an rvalue of the first
  15180. // of the following types that can represent all the values of
  15181. // the enumeration: int, unsigned int, long int, unsigned long
  15182. // int, long long int, or unsigned long long int.
  15183. // C99 6.4.4.3p2:
  15184. // An identifier declared as an enumeration constant has type int.
  15185. // The C99 rule is modified by a gcc extension
  15186. QualType BestPromotionType;
  15187. bool Packed = Enum->hasAttr<PackedAttr>();
  15188. // -fshort-enums is the equivalent to specifying the packed attribute on all
  15189. // enum definitions.
  15190. if (LangOpts.ShortEnums)
  15191. Packed = true;
  15192. // If the enum already has a type because it is fixed or dictated by the
  15193. // target, promote that type instead of analyzing the enumerators.
  15194. if (Enum->isComplete()) {
  15195. BestType = Enum->getIntegerType();
  15196. if (BestType->isPromotableIntegerType())
  15197. BestPromotionType = Context.getPromotedIntegerType(BestType);
  15198. else
  15199. BestPromotionType = BestType;
  15200. BestWidth = Context.getIntWidth(BestType);
  15201. }
  15202. else if (NumNegativeBits) {
  15203. // If there is a negative value, figure out the smallest integer type (of
  15204. // int/long/longlong) that fits.
  15205. // If it's packed, check also if it fits a char or a short.
  15206. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  15207. BestType = Context.SignedCharTy;
  15208. BestWidth = CharWidth;
  15209. } else if (Packed && NumNegativeBits <= ShortWidth &&
  15210. NumPositiveBits < ShortWidth) {
  15211. BestType = Context.ShortTy;
  15212. BestWidth = ShortWidth;
  15213. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  15214. BestType = Context.IntTy;
  15215. BestWidth = IntWidth;
  15216. } else {
  15217. BestWidth = Context.getTargetInfo().getLongWidth();
  15218. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  15219. BestType = Context.LongTy;
  15220. } else {
  15221. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15222. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  15223. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  15224. BestType = Context.LongLongTy;
  15225. }
  15226. }
  15227. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  15228. } else {
  15229. // If there is no negative value, figure out the smallest type that fits
  15230. // all of the enumerator values.
  15231. // If it's packed, check also if it fits a char or a short.
  15232. if (Packed && NumPositiveBits <= CharWidth) {
  15233. BestType = Context.UnsignedCharTy;
  15234. BestPromotionType = Context.IntTy;
  15235. BestWidth = CharWidth;
  15236. } else if (Packed && NumPositiveBits <= ShortWidth) {
  15237. BestType = Context.UnsignedShortTy;
  15238. BestPromotionType = Context.IntTy;
  15239. BestWidth = ShortWidth;
  15240. } else if (NumPositiveBits <= IntWidth) {
  15241. BestType = Context.UnsignedIntTy;
  15242. BestWidth = IntWidth;
  15243. BestPromotionType
  15244. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15245. ? Context.UnsignedIntTy : Context.IntTy;
  15246. } else if (NumPositiveBits <=
  15247. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  15248. BestType = Context.UnsignedLongTy;
  15249. BestPromotionType
  15250. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15251. ? Context.UnsignedLongTy : Context.LongTy;
  15252. } else {
  15253. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15254. assert(NumPositiveBits <= BestWidth &&
  15255. "How could an initializer get larger than ULL?");
  15256. BestType = Context.UnsignedLongLongTy;
  15257. BestPromotionType
  15258. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15259. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  15260. }
  15261. }
  15262. // Loop over all of the enumerator constants, changing their types to match
  15263. // the type of the enum if needed.
  15264. for (auto *D : Elements) {
  15265. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  15266. if (!ECD) continue; // Already issued a diagnostic.
  15267. // Standard C says the enumerators have int type, but we allow, as an
  15268. // extension, the enumerators to be larger than int size. If each
  15269. // enumerator value fits in an int, type it as an int, otherwise type it the
  15270. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15271. // that X has type 'int', not 'unsigned'.
  15272. // Determine whether the value fits into an int.
  15273. llvm::APSInt InitVal = ECD->getInitVal();
  15274. // If it fits into an integer type, force it. Otherwise force it to match
  15275. // the enum decl type.
  15276. QualType NewTy;
  15277. unsigned NewWidth;
  15278. bool NewSign;
  15279. if (!getLangOpts().CPlusPlus &&
  15280. !Enum->isFixed() &&
  15281. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15282. NewTy = Context.IntTy;
  15283. NewWidth = IntWidth;
  15284. NewSign = true;
  15285. } else if (ECD->getType() == BestType) {
  15286. // Already the right type!
  15287. if (getLangOpts().CPlusPlus)
  15288. // C++ [dcl.enum]p4: Following the closing brace of an
  15289. // enum-specifier, each enumerator has the type of its
  15290. // enumeration.
  15291. ECD->setType(EnumType);
  15292. continue;
  15293. } else {
  15294. NewTy = BestType;
  15295. NewWidth = BestWidth;
  15296. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15297. }
  15298. // Adjust the APSInt value.
  15299. InitVal = InitVal.extOrTrunc(NewWidth);
  15300. InitVal.setIsSigned(NewSign);
  15301. ECD->setInitVal(InitVal);
  15302. // Adjust the Expr initializer and type.
  15303. if (ECD->getInitExpr() &&
  15304. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15305. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15306. CK_IntegralCast,
  15307. ECD->getInitExpr(),
  15308. /*base paths*/ nullptr,
  15309. VK_RValue));
  15310. if (getLangOpts().CPlusPlus)
  15311. // C++ [dcl.enum]p4: Following the closing brace of an
  15312. // enum-specifier, each enumerator has the type of its
  15313. // enumeration.
  15314. ECD->setType(EnumType);
  15315. else
  15316. ECD->setType(NewTy);
  15317. }
  15318. Enum->completeDefinition(BestType, BestPromotionType,
  15319. NumPositiveBits, NumNegativeBits);
  15320. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15321. if (Enum->isClosedFlag()) {
  15322. for (Decl *D : Elements) {
  15323. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15324. if (!ECD) continue; // Already issued a diagnostic.
  15325. llvm::APSInt InitVal = ECD->getInitVal();
  15326. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15327. !IsValueInFlagEnum(Enum, InitVal, true))
  15328. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15329. << ECD << Enum;
  15330. }
  15331. }
  15332. // Now that the enum type is defined, ensure it's not been underaligned.
  15333. if (Enum->hasAttrs())
  15334. CheckAlignasUnderalignment(Enum);
  15335. }
  15336. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15337. SourceLocation StartLoc,
  15338. SourceLocation EndLoc) {
  15339. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15340. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15341. AsmString, StartLoc,
  15342. EndLoc);
  15343. CurContext->addDecl(New);
  15344. return New;
  15345. }
  15346. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15347. IdentifierInfo* AliasName,
  15348. SourceLocation PragmaLoc,
  15349. SourceLocation NameLoc,
  15350. SourceLocation AliasNameLoc) {
  15351. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15352. LookupOrdinaryName);
  15353. AsmLabelAttr *Attr =
  15354. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  15355. // If a declaration that:
  15356. // 1) declares a function or a variable
  15357. // 2) has external linkage
  15358. // already exists, add a label attribute to it.
  15359. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15360. if (isDeclExternC(PrevDecl))
  15361. PrevDecl->addAttr(Attr);
  15362. else
  15363. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15364. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15365. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15366. } else
  15367. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15368. }
  15369. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15370. SourceLocation PragmaLoc,
  15371. SourceLocation NameLoc) {
  15372. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15373. if (PrevDecl) {
  15374. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  15375. } else {
  15376. (void)WeakUndeclaredIdentifiers.insert(
  15377. std::pair<IdentifierInfo*,WeakInfo>
  15378. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15379. }
  15380. }
  15381. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15382. IdentifierInfo* AliasName,
  15383. SourceLocation PragmaLoc,
  15384. SourceLocation NameLoc,
  15385. SourceLocation AliasNameLoc) {
  15386. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15387. LookupOrdinaryName);
  15388. WeakInfo W = WeakInfo(Name, NameLoc);
  15389. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15390. if (!PrevDecl->hasAttr<AliasAttr>())
  15391. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15392. DeclApplyPragmaWeak(TUScope, ND, W);
  15393. } else {
  15394. (void)WeakUndeclaredIdentifiers.insert(
  15395. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15396. }
  15397. }
  15398. Decl *Sema::getObjCDeclContext() const {
  15399. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15400. }